repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/base/BaseRuleController.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/base/BaseRuleController.java
package com.alibaba.csp.sentinel.dashboard.controller.base; import java.util.concurrent.TimeUnit; /** * Nacos持久化通用处理类 * * @author zyf * @date 2022-04-13 */ public class BaseRuleController { /** * 延迟一下 * * 解释:列表加载数据的时候,Nacos持久化还没做完,导致加载数据不对 */ public static void delayTime(){ try { TimeUnit.MILLISECONDS.sleep(100); System.out.println("-------------睡100毫秒-----------"); } catch (InterruptedException e) { e.printStackTrace(); } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayApiController.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayApiController.java
package com.alibaba.csp.sentinel.dashboard.controller.gateway; import com.alibaba.csp.sentinel.dashboard.auth.AuthAction; import com.alibaba.csp.sentinel.dashboard.auth.AuthService; import com.alibaba.csp.sentinel.dashboard.controller.base.BaseRuleController; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiPredicateItemEntity; import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo; import com.alibaba.csp.sentinel.dashboard.domain.Result; import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api.AddApiReqVo; import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api.ApiPredicateItemVo; import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.api.UpdateApiReqVo; import com.alibaba.csp.sentinel.dashboard.repository.gateway.InMemApiDefinitionStore; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.*; import static com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants.*; /** * 网关API规则控制器 * * @author zyf * @date 2022-04-13 */ @RestController @RequestMapping(value = "/gateway/api") public class GatewayApiController extends BaseRuleController { private final Logger logger = LoggerFactory.getLogger(GatewayApiController.class); @Autowired private InMemApiDefinitionStore repository; @Autowired @Qualifier("gateWayApiNacosProvider") private DynamicRuleProvider<List<ApiDefinitionEntity>> apiProvider; @Autowired @Qualifier("gateWayApiNacosPublisher") private DynamicRulePublisher<List<ApiDefinitionEntity>> apiPublisher; @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = apiProvider.getRules(app); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } } @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); // API名称 String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); // 匹配规则列表 List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); // 匹配模式 Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); // 匹配串 String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); // 检查API名称不能重复 List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); } @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } // 匹配规则列表 List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); // 匹配模式 int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); // 匹配串 String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); } @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); } private boolean publishApis(String app, String ip, Integer port) { List<ApiDefinitionEntity> apis = repository.findAllByApp(app); try { apiPublisher.publish(app, apis); //延迟加载 delayTime(); return true; } catch (Exception e) { logger.error("publish api error!"); e.printStackTrace(); return false; } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayFlowRuleController.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/gateway/GatewayFlowRuleController.java
package com.alibaba.csp.sentinel.dashboard.controller.gateway; import com.alibaba.csp.sentinel.dashboard.auth.AuthAction; import com.alibaba.csp.sentinel.dashboard.auth.AuthService; import com.alibaba.csp.sentinel.dashboard.controller.base.BaseRuleController; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayParamFlowItemEntity; import com.alibaba.csp.sentinel.dashboard.domain.Result; import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.AddFlowRuleReqVo; import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.GatewayParamFlowItemVo; import com.alibaba.csp.sentinel.dashboard.domain.vo.gateway.rule.UpdateFlowRuleReqVo; import com.alibaba.csp.sentinel.dashboard.repository.gateway.InMemGatewayFlowRuleStore; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.util.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.Date; import java.util.List; import static com.alibaba.csp.sentinel.slots.block.RuleConstant.*; import static com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants.*; import static com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity.*; /** * 网关限流规则控制器 * * @author zyf * @date 2022-04-13 */ @RestController @RequestMapping(value = "/gateway/flow") public class GatewayFlowRuleController extends BaseRuleController { private final Logger logger = LoggerFactory.getLogger(GatewayFlowRuleController.class); @Autowired private InMemGatewayFlowRuleStore repository; @Autowired @Qualifier("gateWayFlowRulesNacosProvider") private DynamicRuleProvider<List<GatewayFlowRuleEntity>> ruleProvider; @Autowired @Qualifier("gateWayFlowRulesNacosPublisher") private DynamicRulePublisher<List<GatewayFlowRuleEntity>> rulePublisher; @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = ruleProvider.getRules(app); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } } @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); // API类型, Route ID或API分组 Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); // API名称 String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); // 针对请求属性 GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填 if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { // 参数名称 String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); // 如果匹配串不为空,验证匹配模式 if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } // 阈值类型 0-线程数 1-QPS Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); // QPS阈值 Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); // 间隔 Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); // 间隔单位 Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); // 流控方式 0-快速失败 2-匀速排队 Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { // 0-快速失败, 则Burst size必填 Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { // 1-匀速排队, 则超时时间必填 Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); } @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } // 针对请求属性 GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); // 参数属性 0-ClientIP 1-Remote Host 2-Header 3-URL参数 4-Cookie Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); // 当参数属性为2-Header 3-URL参数 4-Cookie时,参数名称必填 if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { // 参数名称 String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); // 如果匹配串不为空,验证匹配模式 if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } // 阈值类型 0-线程数 1-QPS Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); // QPS阈值 Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); // 间隔 Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); // 间隔单位 Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); // 流控方式 0-快速失败 2-匀速排队 Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { // 0-快速失败, 则Burst size必填 Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { // 2-匀速排队, 则超时时间必填 Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); } @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); } private boolean publishRules(String app, String ip, Integer port) { List<GatewayFlowRuleEntity> rules = repository.findAllByApp(app); try { rulePublisher.publish(app, rules); //延迟加载 delayTime(); return true; } catch (Exception e) { logger.error("publish rules error!"); e.printStackTrace(); return false; } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/v2/FlowControllerV2.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/v2/FlowControllerV2.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.dashboard.controller.v2; import java.util.Date; import java.util.List; import com.alibaba.csp.sentinel.dashboard.auth.AuthAction; import com.alibaba.csp.sentinel.dashboard.auth.AuthService; import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType; import com.alibaba.csp.sentinel.dashboard.controller.base.BaseRuleController; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.repository.rule.InMemoryRuleRepositoryAdapter; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.dashboard.domain.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * 流控规则控制器 * * @author zyf * @date 2022-04-13 */ @RestController @RequestMapping(value = "/v2/flow") public class FlowControllerV2 extends BaseRuleController { private final Logger logger = LoggerFactory.getLogger(FlowControllerV2.class); @Autowired private InMemoryRuleRepositoryAdapter<FlowRuleEntity> repository; @Autowired @Qualifier("flowRuleNacosProvider") private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider; @Autowired @Qualifier("flowRuleNacosPublisher") private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher; @GetMapping("/rules") @AuthAction(PrivilegeType.READ_RULE) public Result<List<FlowRuleEntity>> apiQueryMachineRules(@RequestParam String app) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } try { List<FlowRuleEntity> rules = ruleProvider.getRules(app); if (rules != null && !rules.isEmpty()) { for (FlowRuleEntity entity : rules) { entity.setApp(app); if (entity.getClusterConfig() != null && entity.getClusterConfig().getFlowId() != null) { entity.setId(entity.getClusterConfig().getFlowId()); } } } rules = repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("Error when querying flow rules", throwable); return Result.ofThrowable(-1, throwable); } } private <R> Result<R> checkEntityInternal(FlowRuleEntity entity) { if (entity == null) { return Result.ofFail(-1, "invalid body"); } if (StringUtil.isBlank(entity.getApp())) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isBlank(entity.getLimitApp())) { return Result.ofFail(-1, "limitApp can't be null or empty"); } if (StringUtil.isBlank(entity.getResource())) { return Result.ofFail(-1, "resource can't be null or empty"); } if (entity.getGrade() == null) { return Result.ofFail(-1, "grade can't be null"); } if (entity.getGrade() != 0 && entity.getGrade() != 1) { return Result.ofFail(-1, "grade must be 0 or 1, but " + entity.getGrade() + " got"); } if (entity.getCount() == null || entity.getCount() < 0) { return Result.ofFail(-1, "count should be at lease zero"); } if (entity.getStrategy() == null) { return Result.ofFail(-1, "strategy can't be null"); } if (entity.getStrategy() != 0 && StringUtil.isBlank(entity.getRefResource())) { return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0"); } if (entity.getControlBehavior() == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } int controlBehavior = entity.getControlBehavior(); if (controlBehavior == 1 && entity.getWarmUpPeriodSec() == null) { return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1"); } if (controlBehavior == 2 && entity.getMaxQueueingTimeMs() == null) { return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2"); } if (entity.isClusterMode() && entity.getClusterConfig() == null) { return Result.ofFail(-1, "cluster config should be valid"); } return null; } @PostMapping("/rule") @AuthAction(value = AuthService.PrivilegeType.WRITE_RULE) public Result<FlowRuleEntity> apiAddFlowRule(@RequestBody FlowRuleEntity entity) { Result<FlowRuleEntity> checkResult = checkEntityInternal(entity); if (checkResult != null) { return checkResult; } entity.setId(null); Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); entity.setLimitApp(entity.getLimitApp().trim()); entity.setResource(entity.getResource().trim()); try { entity = repository.save(entity); publishRules(entity.getApp()); } catch (Throwable throwable) { logger.error("Failed to add flow rule", throwable); return Result.ofThrowable(-1, throwable); } return Result.ofSuccess(entity); } @PutMapping("/rule/{id}") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<FlowRuleEntity> apiUpdateFlowRule(@PathVariable("id") Long id, @RequestBody FlowRuleEntity entity) { if (id == null || id <= 0) { return Result.ofFail(-1, "Invalid id"); } FlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofFail(-1, "id " + id + " does not exist"); } if (entity == null) { return Result.ofFail(-1, "invalid body"); } entity.setApp(oldEntity.getApp()); entity.setIp(oldEntity.getIp()); entity.setPort(oldEntity.getPort()); Result<FlowRuleEntity> checkResult = checkEntityInternal(entity); if (checkResult != null) { return checkResult; } entity.setId(id); Date date = new Date(); entity.setGmtCreate(oldEntity.getGmtCreate()); entity.setGmtModified(date); try { entity = repository.save(entity); if (entity == null) { return Result.ofFail(-1, "save entity fail"); } publishRules(oldEntity.getApp()); } catch (Throwable throwable) { logger.error("Failed to update flow rule", throwable); return Result.ofThrowable(-1, throwable); } return Result.ofSuccess(entity); } @DeleteMapping("/rule/{id}") @AuthAction(PrivilegeType.DELETE_RULE) public Result<Long> apiDeleteRule(@PathVariable("id") Long id) { if (id == null || id <= 0) { return Result.ofFail(-1, "Invalid id"); } FlowRuleEntity oldEntity = repository.findById(id); if (ObjectUtils.isEmpty(oldEntity)) { return Result.ofSuccess(null); } try { repository.delete(id); publishRules(oldEntity.getApp()); } catch (Exception e) { return Result.ofFail(-1, e.getMessage()); } return Result.ofSuccess(id); } private void publishRules(/*@NonNull*/ String app) throws Exception { List<FlowRuleEntity> rules = repository.findAllByApp(app); rulePublisher.publish(app, rules); //延迟加载 delayTime(); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/NacosConfigProperties.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/NacosConfigProperties.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos; /** * @Description: nacos配置 * @author: zyf * @date: 2022/03/01$ * @version: V1.0 */ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "nacos.server") @Data public class NacosConfigProperties { private String ip; private String namespace; private String username; private String password; private String groupId; public String getServerAddr() { return this.getIp(); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/SentinelConfig.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/SentinelConfig.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.dashboard.rule.nacos; import java.util.List; import java.util.Properties; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.*; import com.alibaba.csp.sentinel.dashboard.rule.nacos.entity.AuthorityRuleCorrectEntity; import com.alibaba.csp.sentinel.dashboard.rule.nacos.entity.ParamFlowRuleCorrectEntity; import com.alibaba.nacos.api.PropertyKeyConst; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.fastjson.JSON; import com.alibaba.nacos.api.config.ConfigFactory; import com.alibaba.nacos.api.config.ConfigService; /** * sentinel配置类 * * @author zyf * @date 2022-04-13 */ @Configuration public class SentinelConfig { @Autowired private NacosConfigProperties nacosConfigProperties; /** * 流控规则 * @return */ @Bean public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() { return s -> JSON.parseArray(s, FlowRuleEntity.class); } /** * 降级规则 * @return */ @Bean public Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() { return s -> JSON.parseArray(s, DegradeRuleEntity.class); } /** * 热点参数 规则 * @return */ @Bean public Converter<List<ParamFlowRuleCorrectEntity>, String> paramFlowRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<ParamFlowRuleCorrectEntity>> paramFlowRuleEntityDecoder() { return s -> JSON.parseArray(s, ParamFlowRuleCorrectEntity.class); } /** * 系统规则 * @return */ @Bean public Converter<List<SystemRuleEntity>, String> systemRuleRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<SystemRuleEntity>> systemRuleRuleEntityDecoder() { return s -> JSON.parseArray(s, SystemRuleEntity.class); } /** * 授权规则 * @return */ @Bean public Converter<List<AuthorityRuleCorrectEntity>, String> authorityRuleRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<AuthorityRuleCorrectEntity>> authorityRuleRuleEntityDecoder() { return s -> JSON.parseArray(s, AuthorityRuleCorrectEntity.class); } /** * 网关API * * @return * @throws Exception */ @Bean public Converter<List<ApiDefinitionEntity>, String> apiDefinitionEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<ApiDefinitionEntity>> apiDefinitionEntityDecoder() { return s -> JSON.parseArray(s, ApiDefinitionEntity.class); } /** * 网关flowRule * * @return * @throws Exception */ @Bean public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() { return JSON::toJSONString; } @Bean public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() { return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class); } @Bean public ConfigService nacosConfigService() throws Exception { Properties properties=new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR,nacosConfigProperties.getServerAddr()); if(StringUtils.isNotBlank(nacosConfigProperties.getUsername())){ properties.put(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername()); } if(StringUtils.isNotBlank(nacosConfigProperties.getPassword())){ properties.put(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword()); } if(StringUtils.isNotBlank(nacosConfigProperties.getNamespace())){ properties.put(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace()); } return ConfigFactory.createConfigService(properties); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/system/SystemRuleNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/system/SystemRuleNacosProvider.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.system; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * 加载系统规则 * * @author zyf * @date 2022-04-13 */ @Component("systemRuleNacosProvider") public class SystemRuleNacosProvider implements DynamicRuleProvider<List<SystemRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<SystemRuleEntity>> converter; @Override public List<SystemRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + SentinelConStants.SYSTEM_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/system/SystemRuleNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/system/SystemRuleNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.system; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 持久化系统规则 * * @author zyf * @date 2022-04-13 */ @Component("systemRuleNacosPublisher") public class SystemRuleNacosPublisher implements DynamicRulePublisher<List<SystemRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<SystemRuleEntity>, String> converter; @Override public void publish(String app, List<SystemRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(app + SentinelConStants.SYSTEM_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, converter.convert(rules)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/flow/FlowRuleNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/flow/FlowRuleNacosProvider.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.dashboard.rule.nacos.flow; import java.util.ArrayList; import java.util.List; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; /** * 流控规则拉取 * * @author zyf * @date 2022-04-13 */ @Component("flowRuleNacosProvider") public class FlowRuleNacosProvider implements DynamicRuleProvider<List<FlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<FlowRuleEntity>> converter; @Override public List<FlowRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + SentinelConStants.FLOW_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/flow/FlowRuleNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/flow/FlowRuleNacosPublisher.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.dashboard.rule.nacos.flow; import java.util.List; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; /** * 流控规则推送 * * @author zyf * @date 2022-04-13 */ @Component("flowRuleNacosPublisher") public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<FlowRuleEntity>, String> converter; @Override public void publish(String app, List<FlowRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(app + SentinelConStants.FLOW_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, converter.convert(rules)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/paramflow/ParamFlowRuleNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/paramflow/ParamFlowRuleNacosProvider.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.paramflow; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import com.alibaba.csp.sentinel.dashboard.rule.nacos.entity.ParamFlowRuleCorrectEntity; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * 加载热点参数规则 * * @author zyf * @date 2022-04-13 */ @Component("paramFlowRuleNacosProvider") public class ParamFlowRuleNacosProvider implements DynamicRuleProvider<List<ParamFlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<ParamFlowRuleCorrectEntity>> converter; @Override public List<ParamFlowRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + SentinelConStants.PARAM_FLOW_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } List<ParamFlowRuleCorrectEntity> entityList = converter.convert(rules); return entityList.stream().map(rule -> { ParamFlowRule paramFlowRule = new ParamFlowRule(); BeanUtils.copyProperties(rule, paramFlowRule); ParamFlowRuleEntity entity = ParamFlowRuleEntity.fromParamFlowRule(rule.getApp(), rule.getIp(), rule.getPort(), paramFlowRule); entity.setId(rule.getId()); entity.setGmtCreate(rule.getGmtCreate()); return entity; }).collect(Collectors.toList()); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/paramflow/ParamFlowRuleNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/paramflow/ParamFlowRuleNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.paramflow; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import com.alibaba.csp.sentinel.dashboard.rule.nacos.entity.ParamFlowRuleCorrectEntity; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; /** * 持久化热点参数规则 * * @author zyf * @date 2022-04-13 */ @Component("paramFlowRuleNacosPublisher") public class ParamFlowRuleNacosPublisher implements DynamicRulePublisher<List<ParamFlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<ParamFlowRuleCorrectEntity>, String> converter; @Override public void publish(String app, List<ParamFlowRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } rules.forEach(e -> e.setApp(app)); // 转换 List<ParamFlowRuleCorrectEntity> list = rules.stream().map(rule -> { ParamFlowRuleCorrectEntity entity = new ParamFlowRuleCorrectEntity(); BeanUtils.copyProperties(rule, entity); return entity; }).collect(Collectors.toList()); configService.publishConfig(app + SentinelConStants.PARAM_FLOW_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, converter.convert(list)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayApiNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayApiNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.gateway; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 网关API规则推送 * * @author zyf * @date 2022-04-13 */ @Component("gateWayApiNacosPublisher") public class GateWayApiNacosPublisher implements DynamicRulePublisher<List<ApiDefinitionEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<ApiDefinitionEntity>, String> converter; @Override public void publish(String app, List<ApiDefinitionEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(app+ SentinelConStants.GETEWAY_API_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID,converter.convert(rules)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayFlowRulesNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayFlowRulesNacosProvider.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.gateway; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * 网关流控规则拉取 * * @author zyf * @date 2022-04-13 */ @Component("gateWayFlowRulesNacosProvider") public class GateWayFlowRulesNacosProvider implements DynamicRuleProvider<List<GatewayFlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<GatewayFlowRuleEntity>> converter; @Override public List<GatewayFlowRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + SentinelConStants.GETEWAY_FLOW_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayFlowRulesNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayFlowRulesNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.gateway; import java.util.List; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; /** * 网关流控规则推送 * * @author zyf * @date 2022-04-13 */ @Component("gateWayFlowRulesNacosPublisher") public class GateWayFlowRulesNacosPublisher implements DynamicRulePublisher<List<GatewayFlowRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<GatewayFlowRuleEntity>, String> converter; @Override public void publish(String app, List<GatewayFlowRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(app + SentinelConStants.GETEWAY_FLOW_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, converter.convert(rules)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayApiNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/gateway/GateWayApiNacosProvider.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.gateway; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * 网关API规则拉取 * * @author zyf * @date 2022-04-13 */ @Component("gateWayApiNacosProvider") public class GateWayApiNacosProvider implements DynamicRuleProvider<List<ApiDefinitionEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String , List<ApiDefinitionEntity>> converter; @Override public List<ApiDefinitionEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName+ SentinelConStants.GETEWAY_API_DATA_ID_POSTFIX , SentinelConStants.GROUP_ID,3000); if(StringUtil.isEmpty(rules)){ return new ArrayList<>(); } return converter.convert(rules); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/entity/ParamFlowRuleCorrectEntity.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/entity/ParamFlowRuleCorrectEntity.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.entity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity; import com.alibaba.csp.sentinel.slots.block.Rule; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowClusterConfig; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; import java.util.*; /** * @author zyf * @description 重写热点规则实体类,。查看sentinel-dashboard在自定义ParamFlowRuleNacosPublisher时候 推送的数据是ParamFlowRuleEntity。 客户端接收的ParamFlowRule类 * @date 2022-04-13 */ public class ParamFlowRuleCorrectEntity implements RuleEntity { private Long id; private String app; private String ip; private Integer port; private String limitApp; private String resource; private Date gmtCreate; private int grade = 1; private Integer paramIdx; private double count; private int controlBehavior = 0; private int maxQueueingTimeMs = 0; private int burstCount = 0; private long durationInSec = 1L; private List<ParamFlowItem> paramFlowItemList = new ArrayList(); private Map<Object, Integer> hotItems = new HashMap(); private boolean clusterMode = false; private ParamFlowClusterConfig clusterConfig; public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public Integer getParamIdx() { return paramIdx; } public void setParamIdx(Integer paramIdx) { this.paramIdx = paramIdx; } public double getCount() { return count; } public void setCount(double count) { this.count = count; } public int getControlBehavior() { return controlBehavior; } public void setControlBehavior(int controlBehavior) { this.controlBehavior = controlBehavior; } public int getMaxQueueingTimeMs() { return maxQueueingTimeMs; } public void setMaxQueueingTimeMs(int maxQueueingTimeMs) { this.maxQueueingTimeMs = maxQueueingTimeMs; } public int getBurstCount() { return burstCount; } public void setBurstCount(int burstCount) { this.burstCount = burstCount; } public long getDurationInSec() { return durationInSec; } public void setDurationInSec(long durationInSec) { this.durationInSec = durationInSec; } public List<ParamFlowItem> getParamFlowItemList() { return paramFlowItemList; } public void setParamFlowItemList(List<ParamFlowItem> paramFlowItemList) { this.paramFlowItemList = paramFlowItemList; } public Map<Object, Integer> getHotItems() { return hotItems; } public void setHotItems(Map<Object, Integer> hotItems) { this.hotItems = hotItems; } public boolean isClusterMode() { return clusterMode; } public void setClusterMode(boolean clusterMode) { this.clusterMode = clusterMode; } public ParamFlowClusterConfig getClusterConfig() { return clusterConfig; } public void setClusterConfig(ParamFlowClusterConfig clusterConfig) { this.clusterConfig = clusterConfig; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/entity/AuthorityRuleCorrectEntity.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/entity/AuthorityRuleCorrectEntity.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.entity; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity; import com.alibaba.csp.sentinel.slots.block.Rule; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; import java.util.Date; /** * @author zyf * @description 重写授权规则实体类,原因同热点规则 * @date 2022-04-13 */ public class AuthorityRuleCorrectEntity implements RuleEntity { private Long id; private String app; private String ip; private Integer port; private String limitApp; private String resource; private Date gmtCreate; private Date gmtModified; private int strategy; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public String getApp() { return app; } public void setApp(String app) { this.app = app; } @Override public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) { this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public int getStrategy() { return strategy; } public void setStrategy(int strategy) { this.strategy = strategy; } @Override public Rule toRule(){ AuthorityRule rule=new AuthorityRule(); return rule; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/authority/AuthorityRuleNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/authority/AuthorityRuleNacosProvider.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.authority; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.nacos.entity.AuthorityRuleCorrectEntity; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * 授权规则拉取(黑名单白名单) * * @author zyf * @date 2022-04-13 */ @Component("authorityRuleNacosProvider") public class AuthorityRuleNacosProvider implements DynamicRuleProvider<List<AuthorityRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<AuthorityRuleCorrectEntity>> converter; @Override public List<AuthorityRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + SentinelConStants.AUTHORITY_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } List<AuthorityRuleCorrectEntity> entityList = converter.convert(rules); return entityList.stream().map(rule -> { AuthorityRule authorityRule = new AuthorityRule(); BeanUtils.copyProperties(rule, authorityRule); AuthorityRuleEntity entity = AuthorityRuleEntity.fromAuthorityRule(rule.getApp(), rule.getIp(), rule.getPort(), authorityRule); entity.setId(rule.getId()); entity.setGmtCreate(rule.getGmtCreate()); return entity; }).collect(Collectors.toList()); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/authority/AuthorityRuleNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/authority/AuthorityRuleNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.authority; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.dashboard.rule.nacos.entity.AuthorityRuleCorrectEntity; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.stream.Collectors; /** * 授权规则持久化(黑名单白名单) * * @author zyf * @date 2022-04-13 */ @Component("authorityRuleNacosPublisher") public class AuthorityRuleNacosPublisher implements DynamicRulePublisher<List<AuthorityRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<AuthorityRuleCorrectEntity>, String> converter; @Override public void publish(String app, List<AuthorityRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } // 转换 List<AuthorityRuleCorrectEntity> list = rules.stream().map(rule -> { AuthorityRuleCorrectEntity entity = new AuthorityRuleCorrectEntity(); BeanUtils.copyProperties(rule, entity); return entity; }).collect(Collectors.toList()); configService.publishConfig(app + SentinelConStants.AUTHORITY_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, converter.convert(list)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/degrade/DegradeRuleNacosPublisher.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/degrade/DegradeRuleNacosPublisher.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.degrade; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.AssertUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * 降级规则推送 * * @author zyf * @date 2022-04-13 */ @Component("degradeRuleNacosPublisher") public class DegradeRuleNacosPublisher implements DynamicRulePublisher<List<DegradeRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<List<DegradeRuleEntity>, String> converter; @Override public void publish(String app, List<DegradeRuleEntity> rules) throws Exception { AssertUtil.notEmpty(app, "app name cannot be empty"); if (rules == null) { return; } configService.publishConfig(app + SentinelConStants.DEGRADE_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, converter.convert(rules)); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/degrade/DegradeRuleNacosProvider.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/rule/nacos/degrade/DegradeRuleNacosProvider.java
package com.alibaba.csp.sentinel.dashboard.rule.nacos.degrade; import com.alibaba.csp.sentinel.dashboard.constants.SentinelConStants; import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity; import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider; import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelConfig; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.util.StringUtil; import com.alibaba.nacos.api.config.ConfigService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; /** * 降级规则拉取 * * @author zyf * @date 2022-04-13 */ @Component("degradeRuleNacosProvider") public class DegradeRuleNacosProvider implements DynamicRuleProvider<List<DegradeRuleEntity>> { @Autowired private ConfigService configService; @Autowired private Converter<String, List<DegradeRuleEntity>> converter; @Override public List<DegradeRuleEntity> getRules(String appName) throws Exception { String rules = configService.getConfig(appName + SentinelConStants.DEGRADE_DATA_ID_POSTFIX, SentinelConStants.GROUP_ID, 3000); if (StringUtil.isEmpty(rules)) { return new ArrayList<>(); } return converter.convert(rules); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/constants/SentinelConStants.java
jeecg-boot/jeecg-server-cloud/jeecg-visual/jeecg-cloud-sentinel/src/main/java/com/alibaba/csp/sentinel/dashboard/constants/SentinelConStants.java
package com.alibaba.csp.sentinel.dashboard.constants; /** * sentinel常量配置 * @author zyf */ public class SentinelConStants { public static final String GROUP_ID = "SENTINEL_GROUP"; /** * 流控规则 */ public static final String FLOW_DATA_ID_POSTFIX = "-flow-rules"; /** * 热点参数 */ public static final String PARAM_FLOW_DATA_ID_POSTFIX = "-param-rules"; /** * 降级规则 */ public static final String DEGRADE_DATA_ID_POSTFIX = "-degrade-rules"; /** * 系统规则 */ public static final String SYSTEM_DATA_ID_POSTFIX = "-system-rules"; /** * 授权规则 */ public static final String AUTHORITY_DATA_ID_POSTFIX = "-authority-rules"; /** * 网关API */ public static final String GETEWAY_API_DATA_ID_POSTFIX = "-api-rules"; /** * 网关流控规则 */ public static final String GETEWAY_FLOW_DATA_ID_POSTFIX = "-flow-rules"; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/test/java/org/jeecg/test/sqlparse/TestIpUtil.java
jeecg-boot/jeecg-boot-base-core/src/test/java/org/jeecg/test/sqlparse/TestIpUtil.java
package org.jeecg.test.sqlparse; import org.jeecg.common.util.IpUtils; import org.jeecg.common.util.oConvertUtils; import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; /** * @author: scott * @date: 2024年04月29日 16:48 */ public class TestIpUtil { public static void main(String[] args) { Map<String, String[]> map = new HashMap<>(); map.put("key1", new String[]{"value1", "value2", "value3"}); map.put("key4", null); map.put("key2", new String[]{"value4", "value5"}); map.put("key3", new String[]{"value6"}); System.out.println(oConvertUtils.mapToString(map)); } @Test public void test() { String ip = "2408:8207:1851:10e0:50bd:1a50:60c8:b030, 115.231.101.180"; String[] ipAddresses = ip.split(","); for (String ipAddress : ipAddresses) { System.out.println(ipAddress); ipAddress = ipAddress.trim(); if (IpUtils.isValidIpAddress(ipAddress)) { System.out.println("ipAddress= " + ipAddress); } } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/ResourceUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/ResourceUtil.java
package org.jeecg.common.system.util; import lombok.extern.slf4j.Slf4j; import org.jeecg.common.system.annotation.EnumDict; import org.jeecg.common.system.vo.DictModel; import org.jeecg.common.util.oConvertUtils; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.util.ClassUtils; import java.lang.reflect.Method; import java.util.*; /** * 枚举字典数据 资源加载工具类 * * @Author taoYan * @Date 2022/7/8 10:40 **/ @Slf4j public class ResourceUtil { /** * 多个包扫描根路径 * * 之所以让用户手工配置扫描路径,是为了避免不必要的类加载开销,提升启动性能。 * 请务必将所有枚举类所在包路径添加到此配置中。 */ private final static String[] BASE_SCAN_PACKAGES = { "org.jeecg.common.constant.enums", "org.jeecg.modules.message.enums" }; /** * 枚举字典数据 */ private final static Map<String, List<DictModel>> enumDictData = new HashMap<>(5); /** * 所有枚举java类 */ private final static String CLASS_ENUM_PATTERN="/**/*Enum.class"; /** * 初始化状态标识 */ private static volatile boolean initialized = false; /** * 枚举类中获取字典数据的方法名 */ private final static String METHOD_NAME = "getDictList"; /** * 获取枚举字典数据 * 获取枚举类对应的字典数据 SysDictServiceImpl#queryAllDictItems() * * @return 枚举字典数据 */ public static Map<String, List<DictModel>> getEnumDictData() { if (!initialized) { synchronized (ResourceUtil.class) { if (!initialized) { long startTime = System.currentTimeMillis(); log.debug("【枚举字典加载】开始初始化枚举字典数据..."); initEnumDictData(); initialized = true; long endTime = System.currentTimeMillis(); log.debug("【枚举字典加载】枚举字典数据初始化完成,共加载 {} 个字典,总耗时: {}ms", enumDictData.size(), endTime - startTime); } } } return enumDictData; } /** * 使用多包路径扫描方式初始化枚举字典数据 */ private static void initEnumDictData() { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); long scanStartTime = System.currentTimeMillis(); List<Resource> allResources = new ArrayList<>(); // 扫描多个包路径 for (String basePackage : BASE_SCAN_PACKAGES) { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(basePackage) + CLASS_ENUM_PATTERN; try { Resource[] resources = resourcePatternResolver.getResources(pattern); allResources.addAll(Arrays.asList(resources)); log.debug("【枚举字典加载】扫描包 {} 找到 {} 个枚举类文件", basePackage, resources.length); } catch (Exception e) { log.warn("【枚举字典加载】扫描包 {} 时出现异常: {}", basePackage, e.getMessage()); } } long scanEndTime = System.currentTimeMillis(); log.debug("【枚举字典加载】文件扫描完成,总共找到 {} 个枚举类文件,扫描耗时: {}ms", allResources.size(), scanEndTime - scanStartTime); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); long processStartTime = System.currentTimeMillis(); int processedCount = 0; for (Resource resource : allResources) { try { MetadataReader reader = readerFactory.getMetadataReader(resource); String classname = reader.getClassMetadata().getClassName(); // 提前检查是否有@EnumDict注解,避免不必要的Class.forName if (hasEnumDictAnnotation(reader)) { processEnumClass(classname); processedCount++; } } catch (Exception e) { log.debug("处理资源异常: {} - {}", resource.getFilename(), e.getMessage()); } } long processEndTime = System.currentTimeMillis(); log.debug("【枚举字典加载】处理完成,实际处理 {} 个带注解的枚举类,处理耗时: {}ms", processedCount, processEndTime - processStartTime); } /** * 检查类是否有EnumDict注解(通过元数据,避免类加载) */ private static boolean hasEnumDictAnnotation(MetadataReader reader) { try { return reader.getAnnotationMetadata().hasAnnotation(EnumDict.class.getName()); } catch (Exception e) { return false; } } /** * 处理单个枚举类 */ private static void processEnumClass(String classname) { try { Class<?> clazz = Class.forName(classname); EnumDict enumDict = clazz.getAnnotation(EnumDict.class); if (enumDict != null) { String key = enumDict.value(); if (oConvertUtils.isNotEmpty(key)) { Method method = clazz.getDeclaredMethod(METHOD_NAME); List<DictModel> list = (List<DictModel>) method.invoke(null); enumDictData.put(key, list); log.debug("成功加载枚举字典: {} -> {}", key, classname); } } } catch (Exception e) { log.debug("处理枚举类异常: {} - {}", classname, e.getMessage()); } } /** * 用于后端字典翻译 SysDictServiceImpl#queryManyDictByKeys(java.util.List, java.util.List) * * @param dictCodeList 字典编码列表 * @param keys 键值列表 * @return 字典数据映射 */ public static Map<String, List<DictModel>> queryManyDictByKeys(List<String> dictCodeList, List<String> keys) { Map<String, List<DictModel>> enumDict = getEnumDictData(); Map<String, List<DictModel>> map = new HashMap<>(); // 使用更高效的查找方式 Set<String> dictCodeSet = new HashSet<>(dictCodeList); Set<String> keySet = new HashSet<>(keys); for (String code : enumDict.keySet()) { if (dictCodeSet.contains(code)) { List<DictModel> dictItemList = enumDict.get(code); for (DictModel dm : dictItemList) { String value = dm.getValue(); if (keySet.contains(value)) { // 修复bug:获取或创建该dictCode对应的list,而不是每次都创建新的list List<DictModel> list = map.computeIfAbsent(code, k -> new ArrayList<>()); list.add(new DictModel(value, dm.getText())); //break; } } } } return map; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/SqlConcatUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/SqlConcatUtil.java
package org.jeecg.common.system.util; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.metadata.OrderItem; import lombok.extern.slf4j.Slf4j; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.system.query.QueryRuleEnum; import org.jeecg.common.util.CommonUtils; import org.jeecg.common.util.oConvertUtils; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @Description: 查询过滤器,SQL拼接写法拆成独立工具类 * @author:qinfeng * @date 20230904 */ @Slf4j public class SqlConcatUtil { /** * 获取单个查询条件的值 * @param rule * @param field * @param value * @param isString * @return */ public static String getSingleSqlByRule(QueryRuleEnum rule,String field,Object value,boolean isString) { return getSingleSqlByRule(rule, field, value, isString, null); } /** * 报表获取查询条件 支持多数据源 * @param field * @param alias * @param value * @param isString * @param dataBaseType * @return */ public static String getSingleQueryConditionSql(String field,String alias,Object value,boolean isString, String dataBaseType) { if (value == null) { return ""; } field = alias+oConvertUtils.camelToUnderline(field); QueryRuleEnum rule = QueryGenerator.convert2Rule(value); return getSingleSqlByRule(rule, field, value, isString, dataBaseType); } /** * 获取单个查询条件的值 * @param rule * @param field * @param value * @param isString * @param dataBaseType * @return */ private static String getSingleSqlByRule(QueryRuleEnum rule,String field,Object value,boolean isString, String dataBaseType) { String res = ""; switch (rule) { case GT: res =field+rule.getValue()+getFieldConditionValue(value, isString, dataBaseType); break; case GE: res = field+rule.getValue()+getFieldConditionValue(value, isString, dataBaseType); break; case LT: res = field+rule.getValue()+getFieldConditionValue(value, isString, dataBaseType); break; case LE: res = field+rule.getValue()+getFieldConditionValue(value, isString, dataBaseType); break; case EQ: res = field+rule.getValue()+getFieldConditionValue(value, isString, dataBaseType); break; case EQ_WITH_ADD: res = field+" = "+getFieldConditionValue(value, isString, dataBaseType); break; case NE: res = field+" <> "+getFieldConditionValue(value, isString, dataBaseType); break; case IN: res = field + " in "+getInConditionValue(value, isString); break; case LIKE: res = field + " like "+getLikeConditionValue(value, QueryRuleEnum.LIKE); break; case LEFT_LIKE: res = field + " like "+getLikeConditionValue(value, QueryRuleEnum.LEFT_LIKE); break; case RIGHT_LIKE: res = field + " like "+getLikeConditionValue(value, QueryRuleEnum.RIGHT_LIKE); break; default: res = field+" = "+getFieldConditionValue(value, isString, dataBaseType); break; } return res; } /** * 获取查询条件的值 * @param value * @param isString * @param dataBaseType * @return */ private static String getFieldConditionValue(Object value,boolean isString, String dataBaseType) { String str = value.toString().trim(); if(str.startsWith(SymbolConstant.EXCLAMATORY_MARK)) { str = str.substring(1); }else if(str.startsWith(QueryRuleEnum.GE.getValue())) { str = str.substring(2); }else if(str.startsWith(QueryRuleEnum.LE.getValue())) { str = str.substring(2); }else if(str.startsWith(QueryRuleEnum.GT.getValue())) { str = str.substring(1); }else if(str.startsWith(QueryRuleEnum.LT.getValue())) { str = str.substring(1); }else if(str.indexOf(QueryGenerator.QUERY_COMMA_ESCAPE)>0) { str = str.replaceAll("\\+\\+", SymbolConstant.COMMA); } if(dataBaseType==null){ dataBaseType = getDbType(); } if(isString) { if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(dataBaseType)){ return " N'"+str+"' "; }else{ return " '"+str+"' "; } }else { // 如果不是字符串 有一种特殊情况 popup调用都走这个逻辑 参数传递的可能是“‘admin’”这种格式的 if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(dataBaseType) && str.endsWith(SymbolConstant.SINGLE_QUOTATION_MARK) && str.startsWith(SymbolConstant.SINGLE_QUOTATION_MARK)){ return " N"+str; } return value.toString(); } } private static String getInConditionValue(Object value,boolean isString) { // 代码逻辑说明: 查询条件如果输入,导致sql报错 String[] temp = value.toString().split(","); if(temp.length==0){ return "('')"; } if(isString) { List<String> res = new ArrayList<>(); for (String string : temp) { if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ res.add("N'"+string+"'"); }else{ res.add("'"+string+"'"); } } return "("+String.join("," ,res)+")"; }else { return "("+value.toString()+")"; } } /** * 先根据值判断 走左模糊还是右模糊 * 最后如果值不带任何标识(*或者%),则再根据ruleEnum判断 * @param value * @param ruleEnum * @return */ private static String getLikeConditionValue(Object value, QueryRuleEnum ruleEnum) { String str = value.toString().trim(); if(str.startsWith(SymbolConstant.ASTERISK) && str.endsWith(SymbolConstant.ASTERISK)) { if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ return "N'%"+str.substring(1,str.length()-1)+"%'"; }else{ return "'%"+str.substring(1,str.length()-1)+"%'"; } }else if(str.startsWith(SymbolConstant.ASTERISK)) { if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ return "N'%"+str.substring(1)+"'"; }else{ return "'%"+str.substring(1)+"'"; } }else if(str.endsWith(SymbolConstant.ASTERISK)) { if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ return "N'"+str.substring(0,str.length()-1)+"%'"; }else{ return "'"+str.substring(0,str.length()-1)+"%'"; } }else { if(str.indexOf(SymbolConstant.PERCENT_SIGN)>=0) { if(DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())){ if(str.startsWith(SymbolConstant.SINGLE_QUOTATION_MARK) && str.endsWith(SymbolConstant.SINGLE_QUOTATION_MARK)){ return "N"+str; }else{ return "N"+"'"+str+"'"; } }else{ if(str.startsWith(SymbolConstant.SINGLE_QUOTATION_MARK) && str.endsWith(SymbolConstant.SINGLE_QUOTATION_MARK)){ return str; }else{ return "'"+str+"'"; } } }else { // 走到这里说明 value不带有任何模糊查询的标识(*或者%) if (ruleEnum == QueryRuleEnum.LEFT_LIKE) { if (DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())) { return "N'%" + str + "'"; } else { return "'%" + str + "'"; } } else if (ruleEnum == QueryRuleEnum.RIGHT_LIKE) { if (DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())) { return "N'" + str + "%'"; } else { return "'" + str + "%'"; } } else { if (DataBaseConstant.DB_TYPE_SQLSERVER.equals(getDbType())) { return "N'%" + str + "%'"; } else { return "'%" + str + "%'"; } } } } } /** * 获取系统数据库类型 */ private static String getDbType() { return CommonUtils.getDatabaseType(); } /** * 获取前端传过来的 "多字段排序信息: sortInfoString" * @return */ public static List<OrderItem> getQueryConditionOrders(String column, String order, String queryInfoString){ List<OrderItem> list = new ArrayList<>(); if(oConvertUtils.isEmpty(queryInfoString)){ //默认以创建时间倒序查询 if(CommonConstant.ORDER_TYPE_DESC.equalsIgnoreCase(order)){ list.add(OrderItem.desc(column)); }else{ list.add(OrderItem.asc(column)); } }else{ // 【TV360X-967】URL解码(微服务下需要) if (queryInfoString.contains("%22column%22")) { log.info("queryInfoString 原生 = {}", queryInfoString); try { queryInfoString = URLDecoder.decode(queryInfoString, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new JeecgBootException(e); } log.info("queryInfoString 解码 = {}", queryInfoString); } JSONArray array = JSONArray.parseArray(queryInfoString); Iterator it = array.iterator(); while(it.hasNext()){ JSONObject json = (JSONObject)it.next(); String tempColumn = json.getString("column"); if(oConvertUtils.isNotEmpty(tempColumn)){ String tempOrder = json.getString("order"); if(CommonConstant.ORDER_TYPE_DESC.equalsIgnoreCase(tempOrder)){ list.add(OrderItem.desc(tempColumn)); }else{ list.add(OrderItem.asc(tempColumn)); } } } } return list; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JeecgDataAutorUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JeecgDataAutorUtils.java
package org.jeecg.common.system.util; import org.jeecg.common.system.vo.SysPermissionDataRuleModel; import org.jeecg.common.system.vo.SysUserCacheInfo; import org.jeecg.common.util.SpringContextUtils; import org.springframework.util.StringUtils; import jakarta.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; /** * @ClassName: JeecgDataAutorUtils * @Description: 数据权限查询规则容器工具类 * @Author: 张代浩 * @Date: 2012-12-15 下午11:27:39 * */ public class JeecgDataAutorUtils { public static final String MENU_DATA_AUTHOR_RULES = "MENU_DATA_AUTHOR_RULES"; public static final String MENU_DATA_AUTHOR_RULE_SQL = "MENU_DATA_AUTHOR_RULE_SQL"; public static final String SYS_USER_INFO = "SYS_USER_INFO"; /** * 往链接请求里面,传入数据查询条件 * * @param request * @param dataRules */ public static synchronized void installDataSearchConditon(HttpServletRequest request, List<SysPermissionDataRuleModel> dataRules) { @SuppressWarnings("unchecked") // 1.先从request获取MENU_DATA_AUTHOR_RULES,如果存则获取到LIST List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon(); if (list==null) { // 2.如果不存在,则new一个list list = new ArrayList<SysPermissionDataRuleModel>(); } for (SysPermissionDataRuleModel tsDataRule : dataRules) { list.add(tsDataRule); } // 3.往list里面增量存指 request.setAttribute(MENU_DATA_AUTHOR_RULES, list); } /** * 获取请求对应的数据权限规则 * * @return */ @SuppressWarnings("unchecked") public static synchronized List<SysPermissionDataRuleModel> loadDataSearchConditon() { return (List<SysPermissionDataRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES); } /** * 获取请求对应的数据权限SQL * * @return */ public static synchronized String loadDataSearchConditonSqlString() { return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL); } /** * 往链接请求里面,传入数据查询条件 * * @param request * @param sql */ public static synchronized void installDataSearchConditon(HttpServletRequest request, String sql) { String ruleSql = (String) loadDataSearchConditonSqlString(); if (!StringUtils.hasText(ruleSql)) { request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL,sql); } } /** * 将用户信息存到request * @param request * @param userinfo */ public static synchronized void installUserInfo(HttpServletRequest request, SysUserCacheInfo userinfo) { request.setAttribute(SYS_USER_INFO, userinfo); } /** * 将用户信息存到request * @param userinfo */ public static synchronized void installUserInfo(SysUserCacheInfo userinfo) { SpringContextUtils.getHttpServletRequest().setAttribute(SYS_USER_INFO, userinfo); } /** * 从request获取用户信息 * @return */ public static synchronized SysUserCacheInfo loadUserInfo() { return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JwtUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/util/JwtUtil.java
package org.jeecg.common.system.util; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.interfaces.DecodedJWT; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.Objects; import java.util.stream.Collectors; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.SecurityUtils; import org.jeecg.common.api.vo.Result; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.constant.TenantConstant; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.system.vo.SysUserCacheInfo; import org.jeecg.common.util.DateUtils; import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.oConvertUtils; /** * @Author Scott * @Date 2018-07-12 14:23 * @Desc JWT工具类 **/ @Slf4j public class JwtUtil { /**PC端,Token有效期为7天(Token在reids中缓存时间为两倍)*/ public static final long EXPIRE_TIME = (7 * 12) * 60 * 60 * 1000L; /**APP端,Token有效期为30天(Token在reids中缓存时间为两倍)*/ public static final long APP_EXPIRE_TIME = (30 * 12) * 60 * 60 * 1000L; static final String WELL_NUMBER = SymbolConstant.WELL_NUMBER + SymbolConstant.LEFT_CURLY_BRACKET; /** * * @param response * @param code * @param errorMsg */ public static void responseError(HttpServletResponse response, Integer code, String errorMsg) { try { Result jsonResult = new Result(code, errorMsg); jsonResult.setSuccess(false); // 设置响应头和内容类型 response.setStatus(code); response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setContentType("application/json;charset=UTF-8"); // 使用 ObjectMapper 序列化为 JSON 字符串 ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(jsonResult); response.getWriter().write(json); response.getWriter().flush(); } catch (IOException e) { log.error(e.getMessage(), e); } } /** * 校验token是否正确 * * @param token 密钥 * @param secret 用户的密码 * @return 是否正确 */ public static boolean verify(String token, String username, String secret) { try { // 根据密码生成JWT效验器 Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build(); // 效验TOKEN DecodedJWT jwt = verifier.verify(token); return true; } catch (Exception e) { log.warn("Token验证失败:" + e.getMessage(),e); return false; } } /** * 获得token中的信息无需secret解密也能获得 * * @return token中包含的用户名 */ public static String getUsername(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } catch (JWTDecodeException e) { log.error(e.getMessage(), e); return null; } } /** * 生成签名,5min后过期 * * @param username 用户名 * @param secret 用户的密码 * @return 加密的token * @deprecated 请使用sign(String username, String secret, String clientType)方法代替 */ @Deprecated public static String sign(String username, String secret) { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm); } /** * 生成签名,5min后过期 * * @param username 用户名 * @param secret 用户的密码 * @param expireTime 过期时间 * @return 加密的token * @deprecated 请使用sign(String username, String secret, String clientType)方法代替 */ @Deprecated public static String sign(String username, String secret, Long expireTime) { Date date = new Date(System.currentTimeMillis() + expireTime); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm); } /** * 生成签名,根据客户端类型自动选择过期时间 * for [JHHB-1030]【鉴权】移动端用户token到期后续期时间变成pc端时长 * * @param username 用户名 * @param secret 用户的密码 * @param clientType 客户端类型(PC或APP) * @return 加密的token */ public static String sign(String username, String secret, String clientType) { // 根据客户端类型选择对应的过期时间 long expireTime = CommonConstant.CLIENT_TYPE_APP.equalsIgnoreCase(clientType) ? APP_EXPIRE_TIME : EXPIRE_TIME; Date date = new Date(System.currentTimeMillis() + expireTime); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username和clientType信息 return JWT.create() .withClaim("username", username) .withClaim("clientType", clientType) .withExpiresAt(date) .sign(algorithm); } /** * 从token中获取客户端类型 * for [JHHB-1030]【鉴权】移动端用户token到期后续期时间变成pc端时长 * * @param token JWT token * @return 客户端类型,如果不存在则返回PC(兼容旧token) */ public static String getClientType(String token) { try { DecodedJWT jwt = JWT.decode(token); String clientType = jwt.getClaim("clientType").asString(); // 如果clientType为空,返回默认值PC(兼容旧token) return oConvertUtils.isNotEmpty(clientType) ? clientType : CommonConstant.CLIENT_TYPE_PC; } catch (JWTDecodeException e) { log.warn("解析token中的clientType失败,使用默认值PC:" + e.getMessage()); return CommonConstant.CLIENT_TYPE_PC; } } /** * 根据request中的token获取用户账号 * * @param request * @return * @throws JeecgBootException */ public static String getUserNameByToken(HttpServletRequest request) throws JeecgBootException { String accessToken = request.getHeader("X-Access-Token"); String username = getUsername(accessToken); if (oConvertUtils.isEmpty(username)) { throw new JeecgBootException("未获取到用户"); } return username; } /** * 从session中获取变量 * @param key * @return */ public static String getSessionData(String key) { //${myVar}% //得到${} 后面的值 String moshi = ""; String wellNumber = WELL_NUMBER; if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){ moshi = key.substring(key.indexOf("}")+1); } String returnValue = null; if (key.contains(wellNumber)) { key = key.substring(2,key.indexOf("}")); } if (oConvertUtils.isNotEmpty(key)) { HttpSession session = SpringContextUtils.getHttpServletRequest().getSession(); returnValue = (String) session.getAttribute(key); } //结果加上${} 后面的值 if(returnValue!=null){returnValue = returnValue + moshi;} return returnValue; } /** * 从当前用户中获取变量 * @param key * @param user * @return */ public static String getUserSystemData(String key, SysUserCacheInfo user) { //1.优先获取 SysUserCacheInfo if(user==null) { try { user = JeecgDataAutorUtils.loadUserInfo(); } catch (Exception e) { log.warn("获取用户信息异常:" + e.getMessage()); } } //2.通过shiro获取登录用户信息 LoginUser sysUser = null; try { sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); } catch (Exception e) { log.warn("SecurityUtils.getSubject() 获取用户信息异常:" + e.getMessage()); } //#{sys_user_code}% String moshi = ""; String wellNumber = WELL_NUMBER; if(key.indexOf(SymbolConstant.RIGHT_CURLY_BRACKET)!=-1){ moshi = key.substring(key.indexOf("}")+1); } String returnValue = null; //针对特殊标示处理#{sysOrgCode},判断替换 if (key.contains(wellNumber)) { key = key.substring(2,key.indexOf("}")); } else { key = key; } // 是否存在字符串标志 boolean multiStr; if(oConvertUtils.isNotEmpty(key) && key.trim().matches("^\\[\\w+]$")){ key = key.substring(1,key.length()-1); multiStr = true; } else { multiStr = false; } //替换为当前系统时间(年月日) if (key.equals(DataBaseConstant.SYS_DATE)|| key.toLowerCase().equals(DataBaseConstant.SYS_DATE_TABLE)) { returnValue = DateUtils.formatDate(); } //替换为当前系统时间(年月日时分秒) else if (key.equals(DataBaseConstant.SYS_TIME)|| key.toLowerCase().equals(DataBaseConstant.SYS_TIME_TABLE)) { returnValue = DateUtils.now(); } //流程状态默认值(默认未发起) else if (key.equals(DataBaseConstant.BPM_STATUS)|| key.toLowerCase().equals(DataBaseConstant.BPM_STATUS_TABLE)) { returnValue = "1"; } //后台任务获取用户信息异常,导致程序中断 if(sysUser==null && user==null){ return null; } //替换为系统登录用户帐号 if (key.equals(DataBaseConstant.SYS_USER_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_CODE_TABLE)) { if(user==null) { returnValue = sysUser.getUsername(); }else { returnValue = user.getSysUserCode(); } } // 替换为系统登录用户ID else if (key.equals(DataBaseConstant.SYS_USER_ID) || key.equalsIgnoreCase(DataBaseConstant.SYS_USER_ID_TABLE)) { if(user==null) { returnValue = sysUser.getId(); }else { returnValue = user.getSysUserId(); } } //替换为系统登录用户真实名字 else if (key.equals(DataBaseConstant.SYS_USER_NAME)|| key.toLowerCase().equals(DataBaseConstant.SYS_USER_NAME_TABLE)) { if(user==null) { returnValue = sysUser.getRealname(); }else { returnValue = user.getSysUserName(); } } //替换为系统用户登录所使用的机构编码 else if (key.equals(DataBaseConstant.SYS_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_ORG_CODE_TABLE)) { if(user==null) { returnValue = sysUser.getOrgCode(); }else { returnValue = user.getSysOrgCode(); } } // 替换为系统用户登录所使用的机构ID else if (key.equals(DataBaseConstant.SYS_ORG_ID) || key.equalsIgnoreCase(DataBaseConstant.SYS_ORG_ID_TABLE)) { if (user == null) { returnValue = sysUser.getOrgId(); } else { returnValue = user.getSysOrgId(); } } //替换为系统用户所拥有的所有机构编码 else if (key.equals(DataBaseConstant.SYS_MULTI_ORG_CODE)|| key.toLowerCase().equals(DataBaseConstant.SYS_MULTI_ORG_CODE_TABLE)) { if(user==null){ //TODO 暂时使用用户登录部门,存在逻辑缺陷,不是用户所拥有的部门 returnValue = sysUser.getOrgCode(); // 代码逻辑说明: [QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------ returnValue = multiStr ? "'" + returnValue + "'" : returnValue; }else{ if(user.isOneDepart()) { returnValue = user.getSysMultiOrgCode().get(0); // 代码逻辑说明: [QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------ returnValue = multiStr ? "'" + returnValue + "'" : returnValue; }else { // 代码逻辑说明: [QQYUN-10785]数据权限,查看自己拥有部门的权限中存在问题 #7288------------ returnValue = user.getSysMultiOrgCode().stream() .filter(Objects::nonNull) .map(orgCode -> { if (multiStr) { return "'" + orgCode + "'"; } else { return orgCode; } }) .collect(Collectors.joining(", ")); } } } // 替换为当前登录用户的角色code(多个逗号分割) else if (key.equals(DataBaseConstant.SYS_ROLE_CODE) || key.equalsIgnoreCase(DataBaseConstant.SYS_ROLE_CODE_TABLE)) { if (user == null) { returnValue = sysUser.getRoleCode(); } else { returnValue = user.getSysRoleCode(); } } // 代码逻辑说明: 多租户ID作为系统变量 else if (key.equals(TenantConstant.TENANT_ID) || key.toLowerCase().equals(TenantConstant.TENANT_ID_TABLE)){ try { returnValue = SpringContextUtils.getHttpServletRequest().getHeader(CommonConstant.TENANT_ID); } catch (Exception e) { log.warn("获取系统租户异常:" + e.getMessage()); } } if(returnValue!=null){returnValue = returnValue + moshi;} return returnValue; } // public static void main(String[] args) { // String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjUzMzY1MTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.xjhud_tWCNYBOg_aRlMgOdlZoWFFKB_givNElHNw3X0"; // System.out.println(JwtUtil.getUsername(token)); // } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/QueryRuleEnum.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/QueryRuleEnum.java
package org.jeecg.common.system.query; import org.jeecg.common.util.oConvertUtils; /** * Query 规则 常量 * @Author Scott * @Date 2019年02月14日 */ public enum QueryRuleEnum { /**查询规则 大于*/ GT(">","gt","大于"), /**查询规则 大于等于*/ GE(">=","ge","大于等于"), /**查询规则 小于*/ LT("<","lt","小于"), /**查询规则 小于等于*/ LE("<=","le","小于等于"), /**查询规则 等于*/ EQ("=","eq","等于"), /**查询规则 不等于*/ NE("!=","ne","不等于"), /**查询规则 包含*/ IN("IN","in","包含"), /**查询规则 全模糊*/ LIKE("LIKE","like","全模糊"), /**查询规则 不模糊包含*/ NOT_LIKE("NOT_LIKE","not_like","不模糊包含"), /**查询规则 左模糊*/ LEFT_LIKE("LEFT_LIKE","left_like","左模糊"), /**查询规则 右模糊*/ RIGHT_LIKE("RIGHT_LIKE","right_like","右模糊"), /**查询规则 带加号等于*/ EQ_WITH_ADD("EQWITHADD","eq_with_add","带加号等于"), /**查询规则 多词模糊匹配(and)*/ LIKE_WITH_AND("LIKEWITHAND","like_with_and","多词模糊匹配————暂时未用上"), /**查询规则 多词模糊匹配(or)*/ LIKE_WITH_OR("LIKEWITHOR","like_with_or","多词模糊匹配(or)"), /**查询规则 自定义SQL片段*/ SQL_RULES("USE_SQL_RULES","ext","自定义SQL片段"), /** 查询工作表 */ LINKAGE("LINKAGE","linkage","查询工作表"), // ------- 当前表单设计器内专用 ------- /**查询规则 不以…结尾*/ NOT_LEFT_LIKE("NOT_LEFT_LIKE","not_left_like","不以…结尾"), /**查询规则 不以…开头*/ NOT_RIGHT_LIKE("NOT_RIGHT_LIKE","not_right_like","不以…开头"), /** 值为空 */ EMPTY("EMPTY","empty","值为空"), /** 值不为空 */ NOT_EMPTY("NOT_EMPTY","not_empty","值不为空"), /**查询规则 不包含*/ NOT_IN("NOT_IN","not_in","不包含"), /**查询规则 多词精确匹配*/ ELE_MATCH("ELE_MATCH","elemMatch","多词匹配"), /**查询规则 多词精确不匹配*/ ELE_NOT_MATCH("ELE_NOT_MATCH","elemNotMatch","多词精确不匹配"), /**查询规则 范围查询*/ RANGE("RANGE","range","范围查询"), /**查询规则 不在范围内查询*/ NOT_RANGE("NOT_RANGE","not_range","不在范围查询"), /** 自定义mongodb查询语句 */ CUSTOM_MONGODB("CUSTOM_MONGODB","custom_mongodb","自定义mongodb查询语句"); // ------- 当前表单设计器内专用 ------- private String value; private String condition; private String msg; QueryRuleEnum(String value, String condition, String msg){ this.value = value; this.condition = condition; this.msg = msg; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCondition() { return condition; } public void setCondition(String condition) { this.condition = condition; } public static QueryRuleEnum getByValue(String value){ if(oConvertUtils.isEmpty(value)) { return null; } for(QueryRuleEnum val :values()){ if (val.getValue().equals(value) || val.getCondition().equalsIgnoreCase(value)){ return val; } } return null; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/MatchTypeEnum.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/MatchTypeEnum.java
package org.jeecg.common.system.query; import org.jeecg.common.util.oConvertUtils; /** * 查询链接规则 * * @Author Sunjianlei */ public enum MatchTypeEnum { /**查询链接规则 AND*/ AND("AND"), /**查询链接规则 OR*/ OR("OR"); private String value; MatchTypeEnum(String value) { this.value = value; } public String getValue() { return value; } public static MatchTypeEnum getByValue(Object value) { if (oConvertUtils.isEmpty(value)) { return null; } return getByValue(value.toString()); } public static MatchTypeEnum getByValue(String value) { if (oConvertUtils.isEmpty(value)) { return null; } for (MatchTypeEnum val : values()) { if (val.getValue().toLowerCase().equals(value.toLowerCase())) { return val; } } return null; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/QueryGenerator.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/QueryGenerator.java
package org.jeecg.common.system.query; import java.beans.PropertyDescriptor; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import com.baomidou.mybatisplus.core.metadata.OrderItem; import org.apache.commons.beanutils.PropertyUtils; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.system.util.JeecgDataAutorUtils; import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.util.SqlConcatUtil; import org.jeecg.common.system.vo.SysPermissionDataRuleModel; import org.jeecg.common.util.*; import org.springframework.util.NumberUtils; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.extern.slf4j.Slf4j; /** * @Description: 查询生成器 * @author: jeecg-boot */ @Slf4j public class QueryGenerator { public static final String SQL_RULES_COLUMN = "SQL_RULES_COLUMN"; private static final String BEGIN = "_begin"; private static final String END = "_end"; /** * 数字类型字段,拼接此后缀 接受多值参数 */ private static final String MULTI = "_MultiString"; private static final String STAR = "*"; private static final String COMMA = ","; /** * 查询 逗号转义符 相当于一个逗号【作废】 */ public static final String QUERY_COMMA_ESCAPE = "++"; private static final String NOT_EQUAL = "!"; /**页面带有规则值查询,空格作为分隔符*/ private static final String QUERY_SEPARATE_KEYWORD = " "; /**高级查询前端传来的参数名*/ private static final String SUPER_QUERY_PARAMS = "superQueryParams"; /** 高级查询前端传来的拼接方式参数名 */ private static final String SUPER_QUERY_MATCH_TYPE = "superQueryMatchType"; /** 单引号 */ public static final String SQL_SQ = "'"; /**排序列*/ private static final String ORDER_COLUMN = "column"; /**排序方式*/ private static final String ORDER_TYPE = "order"; private static final String ORDER_TYPE_ASC = "ASC"; /**mysql 模糊查询之特殊字符下划线 (_、\)*/ public static final String LIKE_MYSQL_SPECIAL_STRS = "_,%"; /**日期格式化yyyy-MM-dd*/ public static final String YYYY_MM_DD = "yyyy-MM-dd"; /**to_date*/ public static final String TO_DATE = "to_date"; /**时间格式化 */ private static final ThreadLocal<SimpleDateFormat> LOCAL = new ThreadLocal<SimpleDateFormat>(); private static SimpleDateFormat getTime(){ SimpleDateFormat time = LOCAL.get(); if(time == null){ time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); LOCAL.set(time); } return time; } /** * 获取查询条件构造器QueryWrapper实例 通用查询条件已被封装完成 * @param searchObj 查询实体 * @param parameterMap request.getParameterMap() * @return QueryWrapper实例 */ public static <T> QueryWrapper<T> initQueryWrapper(T searchObj,Map<String, String[]> parameterMap){ long start = System.currentTimeMillis(); QueryWrapper<T> queryWrapper = new QueryWrapper<T>(); installMplus(queryWrapper, searchObj, parameterMap, null); log.debug("---查询条件构造器初始化完成,耗时:"+(System.currentTimeMillis()-start)+"毫秒----"); return queryWrapper; } /** * 获取查询条件构造器QueryWrapper实例 通用查询条件已被封装完成 * @param searchObj 查询实体 * @param parameterMap request.getParameterMap() * @param customRuleMap 自定义字段查询规则 {field:QueryRuleEnum} * @return QueryWrapper实例 */ public static <T> QueryWrapper<T> initQueryWrapper(T searchObj,Map<String, String[]> parameterMap, Map<String, QueryRuleEnum> customRuleMap){ long start = System.currentTimeMillis(); QueryWrapper<T> queryWrapper = new QueryWrapper<T>(); installMplus(queryWrapper, searchObj, parameterMap, customRuleMap); log.debug("---查询条件构造器初始化完成,耗时:"+(System.currentTimeMillis()-start)+"毫秒----"); return queryWrapper; } /** * 组装Mybatis Plus 查询条件 * <p>使用此方法 需要有如下几点注意: * <br>1.使用QueryWrapper 而非LambdaQueryWrapper; * <br>2.实例化QueryWrapper时不可将实体传入参数 * <br>错误示例:如QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>(jeecgDemo); * <br>正确示例:QueryWrapper<JeecgDemo> queryWrapper = new QueryWrapper<JeecgDemo>(); * <br>3.也可以不使用这个方法直接调用 {@link #initQueryWrapper}直接获取实例 */ private static void installMplus(QueryWrapper<?> queryWrapper, Object searchObj, Map<String, String[]> parameterMap, Map<String, QueryRuleEnum> customRuleMap) { /* * 注意:权限查询由前端配置数据规则 当一个人有多个所属部门时候 可以在规则配置包含条件 orgCode 包含 #{sys_org_code} 但是不支持在自定义SQL中写orgCode in #{sys_org_code} 当一个人只有一个部门 就直接配置等于条件: orgCode 等于 #{sys_org_code} 或者配置自定义SQL: orgCode = '#{sys_org_code}' */ //区间条件组装 模糊查询 高级查询组装 简单排序 权限查询 PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(searchObj); Map<String,SysPermissionDataRuleModel> ruleMap = getRuleMap(); //权限规则自定义SQL表达式 for (String c : ruleMap.keySet()) { if(oConvertUtils.isNotEmpty(c) && c.startsWith(SQL_RULES_COLUMN)){ queryWrapper.and(i ->i.apply(getSqlRuleValue(ruleMap.get(c).getRuleValue()))); } } String name, type, column; //定义实体字段和数据库字段名称的映射 高级查询中 只能获取实体字段 如果设置TableField注解 那么查询条件会出问题 Map<String,String> fieldColumnMap = new HashMap<>(5); for (int i = 0; i < origDescriptors.length; i++) { //aliasName = origDescriptors[i].getName(); mybatis 不存在实体属性 不用处理别名的情况 name = origDescriptors[i].getName(); type = origDescriptors[i].getPropertyType().toString(); try { if (judgedIsUselessField(name)|| !PropertyUtils.isReadable(searchObj, name)) { continue; } Object value = PropertyUtils.getSimpleProperty(searchObj, name); column = ReflectHelper.getTableFieldName(searchObj.getClass(), name); if(column==null){ //column为null只有一种情况 那就是 添加了注解@TableField(exist = false) 后续都不用处理了 continue; } fieldColumnMap.put(name,column); //数据权限查询 if(ruleMap.containsKey(name)) { addRuleToQueryWrapper(ruleMap.get(name), column, origDescriptors[i].getPropertyType(), queryWrapper); } //区间查询 doIntervalQuery(queryWrapper, parameterMap, type, name, column); //判断单值 参数带不同标识字符串 走不同的查询 //TODO 这种前后带逗号的支持分割后模糊查询(多选字段查询生效) 示例:,1,3, if (null != value && value.toString().startsWith(COMMA) && value.toString().endsWith(COMMA)) { String multiLikeval = value.toString().replace(",,", COMMA); String[] vals = multiLikeval.substring(1, multiLikeval.length()).split(COMMA); final String field = oConvertUtils.camelToUnderline(column); if(vals.length>1) { queryWrapper.and(j -> { log.info("---查询过滤器,Query规则---field:{}, rule:{}, value:{}", field, "like", vals[0]); j = j.like(field,vals[0]); for (int k=1;k<vals.length;k++) { j = j.or().like(field,vals[k]); log.info("---查询过滤器,Query规则 .or()---field:{}, rule:{}, value:{}", field, "like", vals[k]); } //return j; }); }else { log.info("---查询过滤器,Query规则---field:{}, rule:{}, value:{}", field, "like", vals[0]); queryWrapper.and(j -> j.like(field,vals[0])); } }else { // 代码逻辑说明: [TV360X-378]增加自定义字段查询规则功能------------ QueryRuleEnum rule; if(null != customRuleMap && customRuleMap.containsKey(name)) { // 有自定义规则,使用自定义规则. rule = customRuleMap.get(name); }else { //根据参数值带什么关键字符串判断走什么类型的查询 rule = convert2Rule(value); } value = replaceValue(rule,value); // add -begin 添加判断为字符串时设为全模糊查询 //if( (rule==null || QueryRuleEnum.EQ.equals(rule)) && "class java.lang.String".equals(type)) { // 可以设置左右模糊或全模糊,因人而异 //rule = QueryRuleEnum.LIKE; //} // add -end 添加判断为字符串时设为全模糊查询 addEasyQuery(queryWrapper, column, rule, value); } } catch (Exception e) { log.error(e.getMessage(), e); } } // 排序逻辑 处理 doMultiFieldsOrder(queryWrapper, parameterMap, fieldColumnMap); //高级查询 doSuperQuery(queryWrapper, parameterMap, fieldColumnMap); } /** * 区间查询 * @param queryWrapper query对象 * @param parameterMap 参数map * @param type 字段类型 * @param filedName 字段名称 * @param columnName 列名称 */ private static void doIntervalQuery(QueryWrapper<?> queryWrapper, Map<String, String[]> parameterMap, String type, String filedName, String columnName) throws ParseException { // 添加 判断是否有区间值 String endValue = null,beginValue = null; if (parameterMap != null && parameterMap.containsKey(filedName + BEGIN)) { beginValue = parameterMap.get(filedName + BEGIN)[0].trim(); addQueryByRule(queryWrapper, columnName, type, beginValue, QueryRuleEnum.GE); } if (parameterMap != null && parameterMap.containsKey(filedName + END)) { endValue = parameterMap.get(filedName + END)[0].trim(); addQueryByRule(queryWrapper, columnName, type, endValue, QueryRuleEnum.LE); } //多值查询 if (parameterMap != null && parameterMap.containsKey(filedName + MULTI)) { endValue = parameterMap.get(filedName + MULTI)[0].trim(); addQueryByRule(queryWrapper, columnName.replace(MULTI,""), type, endValue, QueryRuleEnum.IN); } } private static void doMultiFieldsOrder(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap, Map<String,String> fieldColumnMap) { Set<String> allFields = fieldColumnMap.keySet(); String column=null,order=null; if(parameterMap!=null&& parameterMap.containsKey(ORDER_COLUMN)) { column = parameterMap.get(ORDER_COLUMN)[0]; } if(parameterMap!=null&& parameterMap.containsKey(ORDER_TYPE)) { order = parameterMap.get(ORDER_TYPE)[0]; } if(oConvertUtils.isNotEmpty(column)){ log.debug("单字段排序规则>> column:" + column + ",排序方式:" + order); } // 1. 列表多字段排序优先 if(parameterMap!=null&& parameterMap.containsKey("sortInfoString")) { // 多字段排序 String sortInfoString = parameterMap.get("sortInfoString")[0]; log.debug("多字段排序规则>> sortInfoString:" + sortInfoString); List<OrderItem> orderItemList = SqlConcatUtil.getQueryConditionOrders(column, order, sortInfoString); log.debug(orderItemList.toString()); if (orderItemList != null && !orderItemList.isEmpty()) { for (OrderItem item : orderItemList) { // 一、获取排序数据库字段 String columnName = item.getColumn(); // 1.字典字段,去掉字典翻译文本后缀 if(columnName.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) { columnName = columnName.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX)); } // 2.实体驼峰字段转为数据库字段 columnName = SqlInjectionUtil.getSqlInjectSortField(columnName); // 二、设置字段排序规则 if (item.isAsc()) { queryWrapper.orderByAsc(columnName); } else { queryWrapper.orderByDesc(columnName); } } } return; } // 2. 列表单字段默认排序 if(oConvertUtils.isEmpty(column) && parameterMap!=null&& parameterMap.containsKey("defSortString")) { // 多字段排序 String sortInfoString = parameterMap.get("defSortString")[0]; log.info("默认多字段排序规则>> defSortString:" + sortInfoString); List<OrderItem> orderItemList = SqlConcatUtil.getQueryConditionOrders(column, order, sortInfoString); log.info(orderItemList.toString()); if (orderItemList != null && !orderItemList.isEmpty()) { for (OrderItem item : orderItemList) { // 一、获取排序数据库字段 String columnName = item.getColumn(); // 1.字典字段,去掉字典翻译文本后缀 if(columnName.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) { columnName = columnName.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX)); } // 2.实体驼峰字段转为数据库字段 columnName = SqlInjectionUtil.getSqlInjectSortField(columnName); // 二、设置字段排序规则 if (item.isAsc()) { queryWrapper.orderByAsc(columnName); } else { queryWrapper.orderByDesc(columnName); } } } return; } //TODO 避免用户自定义表无默认字段创建时间,导致排序报错 if(DataBaseConstant.CREATE_TIME.equals(column) && !fieldColumnMap.containsKey(DataBaseConstant.CREATE_TIME)){ column = "id"; log.warn("检测到实体里没有字段createTime,改成采用ID排序!"); } if (oConvertUtils.isNotEmpty(column) && oConvertUtils.isNotEmpty(order)) { //字典字段,去掉字典翻译文本后缀 if(column.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) { column = column.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX)); } //判断column是不是当前实体的 log.debug("当前字段有:"+ allFields); if (!allColumnExist(column, allFields)) { throw new JeecgBootException("请注意,将要排序的列字段不存在:" + column); } //多字段排序方法没有读取 MybatisPlus 注解 @TableField 里 value 的值 if (column.contains(",")) { List<String> columnList = Arrays.asList(column.split(",")); String columnStrNew = columnList.stream().map(c -> fieldColumnMap.get(c)).collect(Collectors.joining(",")); if (oConvertUtils.isNotEmpty(columnStrNew)) { column = columnStrNew; } }else{ column = fieldColumnMap.get(column); } //SQL注入check SqlInjectionUtil.filterContentMulti(column); // 排序规则修改 // 将现有排序 _ 前端传递排序条件{....,column: 'column1,column2',order: 'desc'} 翻译成sql "column1,column2 desc" // 修改为 _ 前端传递排序条件{....,column: 'column1,column2',order: 'desc'} 翻译成sql "column1 desc,column2 desc" if (order.toUpperCase().indexOf(ORDER_TYPE_ASC)>=0) { queryWrapper.orderByAsc(SqlInjectionUtil.getSqlInjectSortFields(column.split(","))); } else { queryWrapper.orderByDesc(SqlInjectionUtil.getSqlInjectSortFields(column.split(","))); } } } /** * 多字段排序 判断所传字段是否存在 * @return */ private static boolean allColumnExist(String columnStr, Set<String> allFields){ boolean exist = true; if(columnStr.indexOf(COMMA)>=0){ String[] arr = columnStr.split(COMMA); for(String column: arr){ if(!allFields.contains(column)){ exist = false; break; } } }else{ exist = allFields.contains(columnStr); } return exist; } /** * 高级查询 * @param queryWrapper 查询对象 * @param parameterMap 参数对象 * @param fieldColumnMap 实体字段和数据库列对应的map */ private static void doSuperQuery(QueryWrapper<?> queryWrapper,Map<String, String[]> parameterMap, Map<String,String> fieldColumnMap) { if(parameterMap!=null&& parameterMap.containsKey(SUPER_QUERY_PARAMS)){ String superQueryParams = parameterMap.get(SUPER_QUERY_PARAMS)[0]; String superQueryMatchType = parameterMap.get(SUPER_QUERY_MATCH_TYPE) != null ? parameterMap.get(SUPER_QUERY_MATCH_TYPE)[0] : MatchTypeEnum.AND.getValue(); MatchTypeEnum matchType = MatchTypeEnum.getByValue(superQueryMatchType); // 代码逻辑说明: 高级查询的条件要用括号括起来,防止和用户的其他条件冲突 ------- try { superQueryParams = URLDecoder.decode(superQueryParams, "UTF-8"); List<QueryCondition> conditions = JSON.parseArray(superQueryParams, QueryCondition.class); if (conditions == null || conditions.size() == 0) { return; } // 代码逻辑说明: 【JTC-573】 过滤空条件查询,防止 sql 拼接多余的 and List<QueryCondition> filterConditions = conditions.stream().filter( rule -> (oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal()) ) || "empty".equals(rule.getRule()) ).collect(Collectors.toList()); if (filterConditions.size() == 0) { return; } log.debug("---高级查询参数-->" + filterConditions); queryWrapper.and(andWrapper -> { for (int i = 0; i < filterConditions.size(); i++) { QueryCondition rule = filterConditions.get(i); if ( ( oConvertUtils.isNotEmpty(rule.getField()) && oConvertUtils.isNotEmpty(rule.getRule()) && oConvertUtils.isNotEmpty(rule.getVal()) ) || "empty".equals(rule.getRule()) ) { log.debug("SuperQuery ==> " + rule.toString()); // 代码逻辑说明: 【高级查询】 oracle 日期等于查询报错 Object queryValue = rule.getVal(); if("date".equals(rule.getType())){ queryValue = DateUtils.str2Date(rule.getVal(),DateUtils.date_sdf.get()); }else if("datetime".equals(rule.getType())){ queryValue = DateUtils.str2Date(rule.getVal(), DateUtils.datetimeFormat.get()); } // 代码逻辑说明: 【/issues/I3VR8E】高级查询没有类型转换,查询参数都是字符串类型 ---- String dbType = rule.getDbType(); if (oConvertUtils.isNotEmpty(dbType)) { try { String valueStr = String.valueOf(queryValue); switch (dbType.toLowerCase().trim()) { case "int": queryValue = Integer.parseInt(valueStr); break; case "bigdecimal": queryValue = new BigDecimal(valueStr); break; case "short": queryValue = Short.parseShort(valueStr); break; case "long": queryValue = Long.parseLong(valueStr); break; case "float": queryValue = Float.parseFloat(valueStr); break; case "double": queryValue = Double.parseDouble(valueStr); break; case "boolean": queryValue = Boolean.parseBoolean(valueStr); break; default: } } catch (Exception e) { log.error("高级查询值转换失败:", e); } } // 代码逻辑说明: 【/issues/I3VR8E】高级查询没有类型转换,查询参数都是字符串类型 ---- addEasyQuery(andWrapper, fieldColumnMap.get(rule.getField()), QueryRuleEnum.getByValue(rule.getRule()), queryValue); // 如果拼接方式是OR,就拼接OR if (MatchTypeEnum.OR == matchType && i < (filterConditions.size() - 1)) { andWrapper.or(); } } } //return andWrapper; }); } catch (UnsupportedEncodingException e) { log.error("--高级查询参数转码失败:" + superQueryParams, e); } catch (Exception e) { log.error("--高级查询拼接失败:" + e.getMessage()); e.printStackTrace(); } } //log.info(" superQuery getCustomSqlSegment: "+ queryWrapper.getCustomSqlSegment()); } /** * 根据所传的值 转化成对应的比较方式 * 支持><= like in ! * @param value * @return */ public static QueryRuleEnum convert2Rule(Object value) { // 避免空数据 // 代码逻辑说明: 查询条件输入空格导致return null后续判断导致抛出null异常 if (value == null) { return QueryRuleEnum.EQ; } String val = (value + "").toString().trim(); if (val.length() == 0) { return QueryRuleEnum.EQ; } QueryRuleEnum rule =null; //TODO 此处规则,只适用于 le lt ge gt // step 2 .>= =< int length2 = 2; int length3 = 3; if (rule == null && val.length() >= length3) { if(QUERY_SEPARATE_KEYWORD.equals(val.substring(length2, length3))){ rule = QueryRuleEnum.getByValue(val.substring(0, 2)); } } // step 1 .> < if (rule == null && val.length() >= length2) { if(QUERY_SEPARATE_KEYWORD.equals(val.substring(1, length2))){ rule = QueryRuleEnum.getByValue(val.substring(0, 1)); } } // step 3 like // 代码逻辑说明: /issues/3382 默认带*就走模糊,但是如果只有一个*,那么走等于查询 if(rule == null && val.equals(STAR)){ rule = QueryRuleEnum.EQ; } if (rule == null && val.contains(STAR)) { if (val.startsWith(STAR) && val.endsWith(STAR)) { rule = QueryRuleEnum.LIKE; } else if (val.startsWith(STAR)) { rule = QueryRuleEnum.LEFT_LIKE; } else if(val.endsWith(STAR)){ rule = QueryRuleEnum.RIGHT_LIKE; } } // step 4 in if (rule == null && val.contains(COMMA)) { //TODO in 查询这里应该有个bug 如果一字段本身就是多选 此时用in查询 未必能查询出来 rule = QueryRuleEnum.IN; } // step 5 != if(rule == null && val.startsWith(NOT_EQUAL)){ rule = QueryRuleEnum.NE; } // step 6 xx+xx+xx 这种情况适用于如果想要用逗号作精确查询 但是系统默认逗号走in 所以可以用++替换【此逻辑作废】 if(rule == null && val.indexOf(QUERY_COMMA_ESCAPE)>0){ rule = QueryRuleEnum.EQ_WITH_ADD; } //特殊处理:Oracle的表达式to_date('xxx','yyyy-MM-dd')含有逗号,会被识别为in查询,转为等于查询 if(rule == QueryRuleEnum.IN && val.indexOf(YYYY_MM_DD)>=0 && val.indexOf(TO_DATE)>=0){ rule = QueryRuleEnum.EQ; } return rule != null ? rule : QueryRuleEnum.EQ; } /** * 替换掉关键字字符 * * @param rule * @param value * @return */ private static Object replaceValue(QueryRuleEnum rule, Object value) { if (rule == null) { return null; } if (! (value instanceof String)){ return value; } String val = (value + "").toString().trim(); // 代码逻辑说明: 查询条件的值为等号(=)bug #3443 if(QueryRuleEnum.EQ.getValue().equals(val)){ return val; } if (rule == QueryRuleEnum.LIKE) { value = val.substring(1, val.length() - 1); //mysql 模糊查询之特殊字符下划线 (_、\) value = specialStrConvert(value.toString()); } else if (rule == QueryRuleEnum.LEFT_LIKE || rule == QueryRuleEnum.NE) { value = val.substring(1); //mysql 模糊查询之特殊字符下划线 (_、\) value = specialStrConvert(value.toString()); } else if (rule == QueryRuleEnum.RIGHT_LIKE) { value = val.substring(0, val.length() - 1); //mysql 模糊查询之特殊字符下划线 (_、\) value = specialStrConvert(value.toString()); } else if (rule == QueryRuleEnum.IN) { value = val.split(","); } else if (rule == QueryRuleEnum.EQ_WITH_ADD) { value = val.replaceAll("\\+\\+", COMMA); }else { // 代码逻辑说明: initQueryWrapper组装sql查询条件错误 #284------------------- if(val.startsWith(rule.getValue())){ //TODO 此处逻辑应该注释掉-> 如果查询内容中带有查询匹配规则符号,就会被截取的(比如:>=您好) value = val.replaceFirst(rule.getValue(),""); }else if(val.startsWith(rule.getCondition()+QUERY_SEPARATE_KEYWORD)){ value = val.replaceFirst(rule.getCondition()+QUERY_SEPARATE_KEYWORD,"").trim(); } } return value; } private static void addQueryByRule(QueryWrapper<?> queryWrapper,String name,String type,String value,QueryRuleEnum rule) throws ParseException { if(oConvertUtils.isNotEmpty(value)) { // 针对数字类型字段,多值查询 if(value.contains(COMMA)){ Object[] temp = Arrays.stream(value.split(COMMA)).map(v -> { try { return QueryGenerator.parseByType(v, type, rule); } catch (ParseException e) { e.printStackTrace(); return v; } }).toArray(); addEasyQuery(queryWrapper, name, rule, temp); return; } Object temp = QueryGenerator.parseByType(value, type, rule); addEasyQuery(queryWrapper, name, rule, temp); } } /** * 根据类型转换给定的值 * @param value * @param type * @param rule * @return * @throws ParseException */ private static Object parseByType(String value, String type, QueryRuleEnum rule) throws ParseException { Object temp; switch (type) { case "class java.lang.Integer": temp = Integer.parseInt(value); break; case "class java.math.BigDecimal": temp = new BigDecimal(value); break; case "class java.lang.Short": temp = Short.parseShort(value); break; case "class java.lang.Long": temp = Long.parseLong(value); break; case "class java.lang.Float": temp = Float.parseFloat(value); break; case "class java.lang.Double": temp = Double.parseDouble(value); break; case "class java.util.Date": temp = getDateQueryByRule(value, rule); break; default: temp = value; break; } return temp; } /** * 获取日期类型的值 * @param value * @param rule * @return * @throws ParseException */ private static Date getDateQueryByRule(String value,QueryRuleEnum rule) throws ParseException { Date date = null; int length = 10; if(value.length()==length) { if(rule==QueryRuleEnum.GE) { //比较大于 date = getTime().parse(value + " 00:00:00"); }else if(rule==QueryRuleEnum.LE) { //比较小于 date = getTime().parse(value + " 23:59:59"); } //TODO 日期类型比较特殊 可能oracle下不一定好使 } if(date==null) { date = getTime().parse(value); } return date; } /** * 根据规则走不同的查询 * @param queryWrapper QueryWrapper * @param name 字段名字 * @param rule 查询规则 * @param value 查询条件值 */ public static void addEasyQuery(QueryWrapper<?> queryWrapper, String name, QueryRuleEnum rule, Object value) { if ( ( name==null || value == null || rule == null || oConvertUtils.isEmpty(value) ) && !QueryRuleEnum.EMPTY.equals(rule)) { return; } name = oConvertUtils.camelToUnderline(name); log.debug("---高级查询 Query规则---field:{} , rule:{} , value:{}",name,rule.getValue(),value); switch (rule) { case GT: queryWrapper.gt(name, value); break; case GE: queryWrapper.ge(name, value); break; case EMPTY: queryWrapper.isNull(name); break; case LT: queryWrapper.lt(name, value); break; case LE: queryWrapper.le(name, value); break; case EQ: case EQ_WITH_ADD: queryWrapper.eq(name, value); break; case NE: queryWrapper.ne(name, value); break; case IN: if(value instanceof String) { queryWrapper.in(name, (Object[])value.toString().split(COMMA)); }else if(value instanceof String[]) { queryWrapper.in(name, (Object[]) value); } // 代码逻辑说明: 【bug】in 类型多值查询 不适配postgresql #1671 else if(value.getClass().isArray()) { queryWrapper.in(name, (Object[])value); }else { queryWrapper.in(name, value); } break; case LIKE: queryWrapper.like(name, value); break; case LEFT_LIKE: queryWrapper.likeLeft(name, value); break; case NOT_LEFT_LIKE: queryWrapper.notLikeLeft(name, value); break; case RIGHT_LIKE: queryWrapper.likeRight(name, value); break; case NOT_RIGHT_LIKE: queryWrapper.notLikeRight(name, value); break; // 代码逻辑说明: [TV360X-378]下拉多框根据条件查询不出来:增加自定义字段查询规则功能------------ case LIKE_WITH_OR: final String nameFinal = name; Object[] vals; if (value instanceof String) { vals = value.toString().split(COMMA); } else if (value instanceof String[]) { vals = (Object[]) value; } // 代码逻辑说明: 【bug】in 类型多值查询 不适配postgresql #1671 else if (value.getClass().isArray()) { vals = (Object[]) value; } else { vals = new Object[]{value}; } queryWrapper.and(j -> { log.info("---查询过滤器,Query规则---field:{}, rule:{}, value:{}", nameFinal, "like", vals[0]); j = j.like(nameFinal, vals[0]); for (int k = 1; k < vals.length; k++) { j = j.or().like(nameFinal, vals[k]); log.info("---查询过滤器,Query规则 .or()---field:{}, rule:{}, value:{}", nameFinal, "like", vals[k]); } }); break; default: log.info("--查询规则未匹配到---"); break; } } /** * * @param name * @return */ private static boolean judgedIsUselessField(String name) { return "class".equals(name) || "ids".equals(name) || "page".equals(name) || "rows".equals(name) //// https://github.com/jeecgboot/JeecgBoot/issues/6937 // || "sort".equals(name) || "order".equals(name) ; } /** * 获取请求对应的数据权限规则 TODO 相同列权限多个 有问题 * @return */ public static Map<String, SysPermissionDataRuleModel> getRuleMap() { Map<String, SysPermissionDataRuleModel> ruleMap = new HashMap<>(5); List<SysPermissionDataRuleModel> list = null; // 代码逻辑说明: QQYUN-5441 【简流】获取多个用户/部门/角色 设置部门查询 报错 try { list = JeecgDataAutorUtils.loadDataSearchConditon(); }catch (Exception e){ log.error("根据request对象获取权限数据失败,可能是定时任务中执行的。", e); } if(list != null&&list.size()>0){ if(list.get(0)==null){ return ruleMap; } for (SysPermissionDataRuleModel rule : list) { String column = rule.getRuleColumn(); if(QueryRuleEnum.SQL_RULES.getValue().equals(rule.getRuleConditions())) { column = SQL_RULES_COLUMN+rule.getId(); } ruleMap.put(column, rule); } } return ruleMap; } private static void addRuleToQueryWrapper(SysPermissionDataRuleModel dataRule, String name, Class propertyType, QueryWrapper<?> queryWrapper) { QueryRuleEnum rule = QueryRuleEnum.getByValue(dataRule.getRuleConditions()); if(rule.equals(QueryRuleEnum.IN) && ! propertyType.equals(String.class)) { String[] values = dataRule.getRuleValue().split(","); Object[] objs = new Object[values.length]; for (int i = 0; i < values.length; i++) { objs[i] = NumberUtils.parseNumber(values[i], propertyType); } addEasyQuery(queryWrapper, name, rule, objs); }else { if (propertyType.equals(String.class)) { addEasyQuery(queryWrapper, name, rule, converRuleValue(dataRule.getRuleValue())); }else if (propertyType.equals(Date.class)) { String dateStr =converRuleValue(dataRule.getRuleValue()); int length = 10; if(dateStr.length()==length){ addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.date_sdf.get())); }else{ addEasyQuery(queryWrapper, name, rule, DateUtils.str2Date(dateStr,DateUtils.datetimeFormat.get())); } }else { // 代码逻辑说明: [issues/7481]多租户模式下 数据权限使用变量:#{tenant_id} 报错------------ addEasyQuery(queryWrapper, name, rule, NumberUtils.parseNumber(converRuleValue(dataRule.getRuleValue()), propertyType)); } } } public static String converRuleValue(String ruleValue) { String value = JwtUtil.getUserSystemData(ruleValue,null); return value!= null ? value : ruleValue; } /** * @author: scott * @Description: 去掉值前后单引号 * @date: 2020/3/19 21:26 * @param ruleValue: * @Return: java.lang.String */ public static String trimSingleQuote(String ruleValue) { if (oConvertUtils.isEmpty(ruleValue)) { return ""; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
true
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/QueryCondition.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/query/QueryCondition.java
package org.jeecg.common.system.query; import java.io.Serializable; /** * @Description: QueryCondition * @author: jeecg-boot */ public class QueryCondition implements Serializable { private static final long serialVersionUID = 4740166316629191651L; private String field; /** 组件的类型(例如:input、select、radio) */ private String type; /** * 对应的数据库字段的类型 * 支持:int、bigDecimal、short、long、float、double、boolean */ private String dbType; private String rule; private String val; public QueryCondition(String field, String type, String dbType, String rule, String val) { this.field = field; this.type = type; this.dbType = dbType; this.rule = rule; this.val = val; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDbType() { return dbType; } public void setDbType(String dbType) { this.dbType = dbType; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } @Override public String toString(){ StringBuffer sb =new StringBuffer(); if(field == null || "".equals(field)){ return ""; } sb.append(this.field).append(" ").append(this.rule).append(" ").append(this.type).append(" ").append(this.dbType).append(" ").append(this.val); return sb.toString(); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/controller/JeecgController.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/controller/JeecgController.java
package org.jeecg.common.system.base.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.beanutils.PropertyUtils; import org.apache.shiro.SecurityUtils; import org.jeecg.common.api.vo.Result; import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.system.vo.LoginUser; import org.jeecg.common.util.oConvertUtils; import org.jeecg.config.JeecgBaseConfig; import org.jeecgframework.poi.excel.ExcelImportUtil; import org.jeecgframework.poi.excel.def.NormalExcelConstants; import org.jeecgframework.poi.excel.entity.ExportParams; import org.jeecgframework.poi.excel.entity.ImportParams; import org.jeecgframework.poi.excel.entity.enmus.ExcelType; import org.jeecgframework.poi.excel.view.JeecgEntityExcelView; import org.jeecgframework.poi.handler.inter.IExcelExportServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import jakarta.annotation.Resource; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; /** * @Description: Controller基类 * @Author: dangzhenghui@163.com * @Date: 2019-4-21 8:13 * @Version: 1.0 */ @Slf4j public class JeecgController<T, S extends IService<T>> { /**issues/2933 JeecgController注入service时改用protected修饰,能避免重复引用service*/ @Autowired protected S service; @Resource private JeecgBaseConfig jeecgBaseConfig; /** * 导出excel * * @param request */ protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title) { // Step.1 组装查询条件 QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap()); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); // 过滤选中数据 String selections = request.getParameter("selections"); if (oConvertUtils.isNotEmpty(selections)) { List<String> selectionList = Arrays.asList(selections.split(",")); queryWrapper.in("id",selectionList); } // Step.2 获取导出数据 List<T> exportList = service.list(queryWrapper); // Step.3 AutoPoi 导出Excel ModelAndView mv = new ModelAndView(new JeecgEntityExcelView()); //此处设置的filename无效 ,前端会重更新设置一下 mv.addObject(NormalExcelConstants.FILE_NAME, title); mv.addObject(NormalExcelConstants.CLASS, clazz); // 代码逻辑说明: 【QQYUN-13930】统一改成导出xlsx格式--- ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title, ExcelType.XSSF); exportParams.setImageBasePath(jeecgBaseConfig.getPath().getUpload()); mv.addObject(NormalExcelConstants.PARAMS,exportParams); mv.addObject(NormalExcelConstants.DATA_LIST, exportList); // 代码逻辑说明: 【issues/9052】BasicTable列表页导出excel可以指定列--- String exportFields = request.getParameter(NormalExcelConstants.EXPORT_FIELDS); if(oConvertUtils.isNotEmpty(exportFields)){ mv.addObject(NormalExcelConstants.EXPORT_FIELDS, exportFields); } return mv; } /** * 根据每页sheet数量导出多sheet * * @param request * @param object 实体类 * @param clazz 实体类class * @param title 标题 * @param exportFields 导出字段自定义 * @param pageNum 每个sheet的数据条数 * @param request */ protected ModelAndView exportXlsSheet(HttpServletRequest request, T object, Class<T> clazz, String title,String exportFields,Integer pageNum) { // Step.1 组装查询条件 QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap()); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); // Step.2 计算分页sheet数据 double total = service.count(); int count = (int)Math.ceil(total/pageNum); // Step.3 过滤选中数据 String selections = request.getParameter("selections"); if (oConvertUtils.isNotEmpty(selections)) { List<String> selectionList = Arrays.asList(selections.split(",")); queryWrapper.in("id",selectionList); } // Step.4 多sheet处理 List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>(); for (int i = 1; i <=count ; i++) { Page<T> page = new Page<T>(i, pageNum); IPage<T> pageList = service.page(page, queryWrapper); List<T> exportList = pageList.getRecords(); Map<String, Object> map = new HashMap<>(5); ExportParams exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title+i,jeecgBaseConfig.getPath().getUpload()); exportParams.setType(ExcelType.XSSF); //map.put("title",exportParams); //表格Title map.put(NormalExcelConstants.PARAMS,exportParams); //表格对应实体 map.put(NormalExcelConstants.CLASS,clazz); //数据集合 map.put(NormalExcelConstants.DATA_LIST, exportList); listMap.add(map); } // Step.4 AutoPoi 导出Excel ModelAndView mv = new ModelAndView(new JeecgEntityExcelView()); //此处设置的filename无效 ,前端会重更新设置一下 mv.addObject(NormalExcelConstants.FILE_NAME, title); mv.addObject(NormalExcelConstants.MAP_LIST, listMap); return mv; } /** * 大数据导出 * @param request * @param object * @param clazz * @param title * @param pageSize 每次查询的数据量 * @return * @author chenrui * @date 2025/8/11 16:11 */ protected ModelAndView exportXlsForBigData(HttpServletRequest request, T object, Class<T> clazz, String title,Integer pageSize) { // 组装查询条件 QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap()); LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal(); // 计算分页数 double total = service.count(); int count = (int) Math.ceil(total / pageSize); // 过滤选中数据 String selections = request.getParameter("selections"); if (oConvertUtils.isNotEmpty(selections)) { List<String> selectionList = Arrays.asList(selections.split(",")); queryWrapper.in("id", selectionList); } // 定义IExcelExportServer IExcelExportServer excelExportServer = (queryParams, pageNum) -> { if (pageNum > count) { return null; } Page<T> page = new Page<T>(pageNum, pageSize); IPage<T> pageList = service.page(page, (QueryWrapper<T>) queryParams); return new ArrayList<>(pageList.getRecords()); }; // AutoPoi 导出Excel ModelAndView mv = new ModelAndView(new JeecgEntityExcelView()); //此处设置的filename无效 ,前端会重更新设置一下 mv.addObject(NormalExcelConstants.FILE_NAME, title); mv.addObject(NormalExcelConstants.CLASS, clazz); ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title, jeecgBaseConfig.getPath().getUpload()); mv.addObject(NormalExcelConstants.PARAMS, exportParams); mv.addObject(NormalExcelConstants.EXPORT_SERVER, excelExportServer); mv.addObject(NormalExcelConstants.QUERY_PARAMS, queryWrapper); return mv; } /** * 根据权限导出excel,传入导出字段参数 * * @param request */ protected ModelAndView exportXls(HttpServletRequest request, T object, Class<T> clazz, String title,String exportFields) { ModelAndView mv = this.exportXls(request,object,clazz,title); mv.addObject(NormalExcelConstants.EXPORT_FIELDS,exportFields); return mv; } /** * 获取对象ID * * @return */ private String getId(T item) { try { return PropertyUtils.getProperty(item, "id").toString(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 通过excel导入数据 * * @param request * @param response * @return */ protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { // 获取上传文件对象 MultipartFile file = entity.getValue(); ImportParams params = new ImportParams(); params.setTitleRows(2); params.setHeadRows(1); params.setNeedSave(true); try { List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params); // 代码逻辑说明: 批量插入数据 long start = System.currentTimeMillis(); service.saveBatch(list); //400条 saveBatch消耗时间1592毫秒 循环插入消耗时间1947毫秒 //1200条 saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒"); return Result.ok("文件导入成功!数据行数:" + list.size()); } catch (Exception e) { // 代码逻辑说明: 导入数据重复增加提示 String msg = e.getMessage(); log.error(msg, e); if(msg!=null && msg.indexOf("Duplicate entry")>=0){ return Result.error("文件导入失败:有重复数据!"); }else{ return Result.error("文件导入失败:" + e.getMessage()); } } finally { try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } } return Result.error("文件导入失败!"); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/service/JeecgService.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/service/JeecgService.java
package org.jeecg.common.system.base.service; import com.baomidou.mybatisplus.extension.service.IService; /** * @Description: Service基类 * @Author: dangzhenghui@163.com * @Date: 2019-4-21 8:13 * @Version: 1.0 */ public interface JeecgService<T> extends IService<T> { }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/service/impl/JeecgServiceImpl.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/service/impl/JeecgServiceImpl.java
package org.jeecg.common.system.base.service.impl; import org.jeecg.common.system.base.entity.JeecgEntity; import org.jeecg.common.system.base.service.JeecgService; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; /** * @Description: ServiceImpl基类 * @Author: dangzhenghui@163.com * @Date: 2019-4-21 8:13 * @Version: 1.0 */ @Slf4j public class JeecgServiceImpl<M extends BaseMapper<T>, T extends JeecgEntity> extends ServiceImpl<M, T> implements JeecgService<T> { }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/entity/JeecgEntity.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/base/entity/JeecgEntity.java
package org.jeecg.common.system.base.entity; import java.io.Serializable; import org.jeecgframework.poi.excel.annotation.Excel; import org.springframework.format.annotation.DateTimeFormat; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * @Description: Entity基类 * @Author: dangzhenghui@163.com * @Date: 2019-4-28 * @Version: 1.1 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class JeecgEntity implements Serializable { private static final long serialVersionUID = 1L; /** * ID */ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "ID") private java.lang.String id; /** * 创建人 */ @Schema(description = "创建人") @Excel(name = "创建人", width = 15) private java.lang.String createBy; /** * 创建时间 */ @Schema(description = "创建时间") @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private java.util.Date createTime; /** * 更新人 */ @Schema(description = "更新人") @Excel(name = "更新人", width = 15) private java.lang.String updateBy; /** * 更新时间 */ @Schema(description = "更新时间") @Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private java.util.Date updateTime; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/enhance/UserFilterEnhance.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/enhance/UserFilterEnhance.java
package org.jeecg.common.system.enhance; import java.util.List; /** * 用户增强 */ public interface UserFilterEnhance { /** * 获取用户id * @param loginUserId 当前登录的用户id * * @return List<String> 返回多个用户id */ default List<String> getUserIds(String loginUserId) { return null; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/annotation/EnumDict.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/annotation/EnumDict.java
package org.jeecg.common.system.annotation; import java.lang.annotation.*; /** * 将枚举类转化成字典数据 * * <<使用说明>> * 1. 枚举类需以 `Enum` 结尾,并且在类上添加 `@EnumDict` 注解。 * 2. 需要手动将枚举类所在包路径** 添加到 `org.jeecg.common.system.util.ResourceUtil.BASE_SCAN_PACKAGES` 配置数组中。 * * @Author taoYan * @Date 2022/7/8 10:34 **/ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface EnumDict { /** * 作为字典数据的唯一编码 */ String value() default ""; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SelectTreeModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SelectTreeModel.java
package org.jeecg.common.system.vo; import lombok.Data; import java.io.Serializable; import java.util.List; /** * 下拉树 model * * @author jeecg-boot */ @Data public class SelectTreeModel implements Serializable { private String key; private String title; private String value; /** * 父Id */ private String parentId; /** * 是否是叶节点 */ private boolean isLeaf; /** * 子节点 */ private List<SelectTreeModel> children; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysUserCacheInfo.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysUserCacheInfo.java
package org.jeecg.common.system.vo; import java.util.List; import org.jeecg.common.util.DateUtils; /** * @Description: 用户缓存信息 * @author: jeecg-boot */ public class SysUserCacheInfo { private String sysUserId; private String sysUserCode; private String sysUserName; private String sysOrgCode; /** * 当前用户部门ID */ private String sysOrgId; private List<String> sysMultiOrgCode; private boolean oneDepart; /** * 当前用户角色code(多个逗号分割) */ private String sysRoleCode; public boolean isOneDepart() { return oneDepart; } public void setOneDepart(boolean oneDepart) { this.oneDepart = oneDepart; } public String getSysDate() { return DateUtils.formatDate(); } public String getSysTime() { return DateUtils.now(); } public String getSysUserCode() { return sysUserCode; } public void setSysUserCode(String sysUserCode) { this.sysUserCode = sysUserCode; } public String getSysUserName() { return sysUserName; } public void setSysUserName(String sysUserName) { this.sysUserName = sysUserName; } public String getSysOrgCode() { return sysOrgCode; } public void setSysOrgCode(String sysOrgCode) { this.sysOrgCode = sysOrgCode; } public List<String> getSysMultiOrgCode() { return sysMultiOrgCode; } public void setSysMultiOrgCode(List<String> sysMultiOrgCode) { this.sysMultiOrgCode = sysMultiOrgCode; } public String getSysUserId() { return sysUserId; } public void setSysUserId(String sysUserId) { this.sysUserId = sysUserId; } public String getSysOrgId() { return sysOrgId; } public void setSysOrgId(String sysOrgId) { this.sysOrgId = sysOrgId; } public String getSysRoleCode() { return sysRoleCode; } public void setSysRoleCode(String sysRoleCode) { this.sysRoleCode = sysRoleCode; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysPermissionDataRuleModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysPermissionDataRuleModel.java
package org.jeecg.common.system.vo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Date; /** * <p> * 菜单权限规则表 * </p> * * @Author huangzhilin * @since 2019-03-29 */ public class SysPermissionDataRuleModel { /** * id */ private String id; /** * 对应的菜单id */ private String permissionId; /** * 规则名称 */ private String ruleName; /** * 字段 */ private String ruleColumn; /** * 条件 */ private String ruleConditions; /** * 规则值 */ private String ruleValue; /** * 创建时间 */ private Date createTime; /** * 创建人 */ private String createBy; /** * 修改时间 */ private Date updateTime; /** * 修改人 */ private String updateBy; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPermissionId() { return permissionId; } public void setPermissionId(String permissionId) { this.permissionId = permissionId; } public String getRuleName() { return ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName; } public String getRuleColumn() { return ruleColumn; } public void setRuleColumn(String ruleColumn) { this.ruleColumn = ruleColumn; } public String getRuleConditions() { return ruleConditions; } public void setRuleConditions(String ruleConditions) { this.ruleConditions = ruleConditions; } public String getRuleValue() { return ruleValue; } public void setRuleValue(String ruleValue) { this.ruleValue = ruleValue; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysFilesModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysFilesModel.java
package org.jeecg.common.system.vo; /** * @Description: 系统文件实体类 * @author: wangshuai * @date: 2022年08月11日 9:48 */ public class SysFilesModel { /**主键id*/ private String id; /**文件名称*/ private String fileName; /**文件地址*/ private String url; /**文档类型(folder:文件夹 excel:excel doc:word pp:ppt image:图片 archive:其他文档 video:视频)*/ private String fileType; /**文件上传类型(temp/本地上传(临时文件) manage/知识库)*/ private String storeType; /**文件大小(kb)*/ private Double fileSize; /**租户id*/ private String tenantId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getStoreType() { return storeType; } public void setStoreType(String storeType) { this.storeType = storeType; } public Double getFileSize() { return fileSize; } public void setFileSize(Double fileSize) { this.fileSize = fileSize; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DynamicDataSourceModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DynamicDataSourceModel.java
package org.jeecg.common.system.vo; import lombok.Data; import org.springframework.beans.BeanUtils; /** * @Description: 数据源 * @author: jeecg-boot */ @Data public class DynamicDataSourceModel { public DynamicDataSourceModel() { } public DynamicDataSourceModel(Object dbSource) { if (dbSource != null) { BeanUtils.copyProperties(dbSource, this); } } /** * id */ private java.lang.String id; /** * 数据源编码 */ private java.lang.String code; /** * 数据库类型 */ private java.lang.String dbType; /** * 驱动类 */ private java.lang.String dbDriver; /** * 数据源地址 */ private java.lang.String dbUrl; // /** // * 数据库名称 // */ // private java.lang.String dbName; /** * 用户名 */ private java.lang.String dbUsername; /** * 密码 */ private java.lang.String dbPassword; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/LoginUser.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/LoginUser.java
package org.jeecg.common.system.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.jeecg.common.desensitization.annotation.SensitiveField; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * <p> * 在线用户信息 * </p> * * @Author scott * @since 2018-12-20 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class LoginUser { /** * 登录人id */ @SensitiveField private String id; /** * 登录人账号 */ @SensitiveField private String username; /** * 登录人名字 */ @SensitiveField private String realname; /** * 登录人密码 */ @SensitiveField private String password; /** * 当前登录部门code */ @SensitiveField private String orgCode; /** * 当前登录部门id */ @SensitiveField private String orgId; /** * 当前登录角色code(多个逗号分割) */ @SensitiveField private String roleCode; /** * 头像 */ @SensitiveField private String avatar; /** * 工号 */ @SensitiveField private String workNo; /** * 生日 */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd") @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; /** * 性别(1:男 2:女) */ private Integer sex; /** * 电子邮件 */ @SensitiveField private String email; /** * 电话 */ @SensitiveField private String phone; /** * 状态(1:正常 2:冻结 ) */ private Integer status; private Integer delFlag; /** * 同步工作流引擎1同步0不同步 */ private Integer activitiSync; /** * 创建时间 */ private Date createTime; /** * 身份(1 普通员工 2 上级) */ private Integer userIdentity; /** * 管理部门ids */ @SensitiveField private String departIds; /** * 职务,关联职务表 */ @SensitiveField private String post; /** * 座机号 */ @SensitiveField private String telephone; /** 多租户ids临时用,不持久化数据库(数据库字段不存在) */ @SensitiveField private String relTenantIds; /**设备id uniapp推送用*/ private String clientId; /** * 主岗位 */ private String mainDepPostId; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictModel.java
package org.jeecg.common.system.vo; import java.io.Serializable; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * @Description: 字典类 * @author: jeecg-boot */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class DictModel implements Serializable{ private static final long serialVersionUID = 1L; public DictModel() { } public DictModel(String value, String text) { this.value = value; this.text = text; } public DictModel(String value, String text, String color) { this.value = value; this.text = text; this.color = color; } /** * 字典value */ private String value; /** * 字典文本 */ private String text; /** * 字典颜色 */ private String color; /** * 特殊用途: JgEditableTable * @return */ public String getTitle() { return this.text; } /** * 特殊用途: vue3 Select组件 */ public String getLabel() { return this.text; } /** * 用于表单设计器 关联记录表数据存储 * QQYUN-5595【表单设计器】他表字段 导入没有翻译 */ private JSONObject jsonObject; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/UserAccountInfo.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/UserAccountInfo.java
package org.jeecg.common.system.vo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.jeecg.common.desensitization.annotation.SensitiveField; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; /** * <p> * 在线用户信息 * </p> * * @Author scott * @since 2023-08-16 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class UserAccountInfo { /** * 登录人id */ private String id; /** * 登录人账号 */ private String username; /** * 登录人名字 */ private String realname; /** * 电子邮件 */ private String email; /** * 头像 */ @SensitiveField private String avatar; /** * 同步工作流引擎1同步0不同步 */ private Integer activitiSync; /** * 电话 */ @SensitiveField private String phone; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysCategoryModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysCategoryModel.java
package org.jeecg.common.system.vo; import org.jeecgframework.poi.excel.annotation.Excel; /** * @Author qinfeng * @Date 2020/2/19 12:01 * @Description: * @Version 1.0 */ public class SysCategoryModel { /**主键*/ private java.lang.String id; /**父级节点*/ private java.lang.String pid; /**类型名称*/ private java.lang.String name; /**类型编码*/ private java.lang.String code; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictModelMany.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictModelMany.java
package org.jeecg.common.system.vo; import lombok.Data; import lombok.EqualsAndHashCode; /** * 查询多个字典时用到 * @author: jeecg-boot */ @Data @EqualsAndHashCode(callSuper = true) public class DictModelMany extends DictModel { /** * 字典code,根据多个字段code查询时才用到,用于区分不同的字典选项 */ private String dictCode; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysDepartModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/SysDepartModel.java
package org.jeecg.common.system.vo; /** * 部门机构model * @author: lvdandan */ public class SysDepartModel { /**ID*/ private String id; /**父机构ID*/ private String parentId; /**机构/部门名称*/ private String departName; /**英文名*/ private String departNameEn; /**缩写*/ private String departNameAbbr; /**排序*/ private Integer departOrder; /**描述*/ private String description; /**机构类别 1组织机构,2岗位*/ private String orgCategory; /**机构类型*/ private String orgType; /**机构编码*/ private String orgCode; /**手机号*/ private String mobile; /**传真*/ private String fax; /**地址*/ private String address; /**备注*/ private String memo; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getDepartName() { return departName; } public void setDepartName(String departName) { this.departName = departName; } public String getDepartNameEn() { return departNameEn; } public void setDepartNameEn(String departNameEn) { this.departNameEn = departNameEn; } public String getDepartNameAbbr() { return departNameAbbr; } public void setDepartNameAbbr(String departNameAbbr) { this.departNameAbbr = departNameAbbr; } public Integer getDepartOrder() { return departOrder; } public void setDepartOrder(Integer departOrder) { this.departOrder = departOrder; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOrgCategory() { return orgCategory; } public void setOrgCategory(String orgCategory) { this.orgCategory = orgCategory; } public String getOrgType() { return orgType; } public void setOrgType(String orgType) { this.orgType = orgType; } public String getOrgCode() { return orgCode; } public void setOrgCode(String orgCode) { this.orgCode = orgCode; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/ComboModel.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/ComboModel.java
package org.jeecg.common.system.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * @Description: 文档管理 * @author: jeecg-boot */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @JsonIgnoreProperties(ignoreUnknown = true) public class ComboModel implements Serializable { private String id; private String title; /**文档管理 表单table默认选中*/ private boolean checked; /**文档管理 表单table 用户账号*/ private String username; /**文档管理 表单table 用户邮箱*/ private String email; /**文档管理 表单table 角色编码*/ private String roleCode; public ComboModel(){ }; public ComboModel(String id,String title,boolean checked,String username){ this.id = id; this.title = title; this.checked = false; this.username = username; }; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictQuery.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/system/vo/DictQuery.java
package org.jeecg.common.system.vo; import lombok.Data; /** * 字典查询参数实体 * @author: jeecg-boot */ @Data public class DictQuery { /** * 表名 */ private String table; /** * 存储列 */ private String code; /** * 显示列 */ private String text; /** * 关键字查询 */ private String keyword; /** * 存储列的值 用于回显查询 */ private String codeValue; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/PasswordUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/PasswordUtil.java
package org.jeecg.common.util; import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; /** * @Description: 密码工具类 * @author: jeecg-boot */ public class PasswordUtil { /** * JAVA6支持以下任意一种算法 PBEWITHMD5ANDDES PBEWITHMD5ANDTRIPLEDES * PBEWITHSHAANDDESEDE PBEWITHSHA1ANDRC2_40 PBKDF2WITHHMACSHA1 * */ /** * 定义使用的算法为:PBEWITHMD5andDES算法 * 加密算法 */ public static final String ALGORITHM = "PBEWithMD5AndDES"; /** * 定义使用的算法为:PBEWITHMD5andDES算法 * 密钥 */ public static final String SALT = "63293188"; /** * 定义迭代次数为1000次 */ private static final int ITERATIONCOUNT = 1000; /** * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节 * * @return byte[] 盐值 * */ public static byte[] getSalt() throws Exception { // 实例化安全随机数 SecureRandom random = new SecureRandom(); // 产出盐 return random.generateSeed(8); } public static byte[] getStaticSalt() { // 产出盐 return SALT.getBytes(); } /** * 根据PBE密码生成一把密钥 * * @param password * 生成密钥时所使用的密码 * @return Key PBE算法密钥 * */ private static Key getPbeKey(String password) { // 实例化使用的算法 SecretKeyFactory keyFactory; SecretKey secretKey = null; try { keyFactory = SecretKeyFactory.getInstance(ALGORITHM); // 设置PBE密钥参数 PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); // 生成密钥 secretKey = keyFactory.generateSecret(keySpec); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return secretKey; } /** * 加密明文字符串 * * @param plaintext * 待加密的明文字符串 * @param password * 生成密钥时所使用的密码 * @param salt * 盐值 * @return 加密后的密文字符串 * @throws Exception */ public static String encrypt(String plaintext, String password, String salt) { Key key = getPbeKey(password); byte[] encipheredData = null; PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec); // 代码逻辑说明: 中文作为用户名时,加密的密码windows和linux会得到不同的结果 gitee/issues/IZUD7 encipheredData = cipher.doFinal(plaintext.getBytes("utf-8")); } catch (Exception e) { } return bytesToHexString(encipheredData); } /** * 解密密文字符串 * * @param ciphertext * 待解密的密文字符串 * @param password * 生成密钥时所使用的密码(如需解密,该参数需要与加密时使用的一致) * @param salt * 盐值(如需解密,该参数需要与加密时使用的一致) * @return 解密后的明文字符串 * @throws Exception */ public static String decrypt(String ciphertext, String password, String salt) { Key key = getPbeKey(password); byte[] passDec = null; PBEParameterSpec parameterSpec = new PBEParameterSpec(salt.getBytes(), ITERATIONCOUNT); try { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec); passDec = cipher.doFinal(hexStringToBytes(ciphertext)); } catch (Exception e) { // TODO: handle exception } return new String(passDec); } /** * 将字节数组转换为十六进制字符串 * * @param src * 字节数组 * @return */ public static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } /** * 将十六进制字符串转换为字节数组 * * @param hexString * 十六进制字符串 * @return */ public static byte[] hexStringToBytes(String hexString) { if (hexString == null || "".equals(hexString)) { return null; } hexString = hexString.toUpperCase(); int length = hexString.length() / 2; char[] hexChars = hexString.toCharArray(); byte[] d = new byte[length]; for (int i = 0; i < length; i++) { int pos = i * 2; d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return d; } private static byte charToByte(char c) { return (byte) "0123456789ABCDEF".indexOf(c); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/TencentSms.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/TencentSms.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSONObject; import com.tencentcloudapi.common.Credential; import com.tencentcloudapi.common.exception.TencentCloudSDKException; import com.tencentcloudapi.common.profile.ClientProfile; import com.tencentcloudapi.common.profile.HttpProfile; import com.tencentcloudapi.sms.v20210111.SmsClient; import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest; import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse; import com.tencentcloudapi.sms.v20210111.models.SendStatus; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.constant.enums.DySmsEnum; import org.jeecg.config.JeecgSmsTemplateConfig; import org.jeecg.config.tencent.JeecgTencent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @Description: 腾讯发送短信 * @author: wangshuai * @date: 2025/11/4 19:27 */ public class TencentSms { private final static Logger logger = LoggerFactory.getLogger(TencentSms.class); /** * 发送腾讯短信 * * @param phone * @param templateParamJson * @param tencent * @param dySmsEnum * @return */ public static boolean sendTencentSms(String phone, JSONObject templateParamJson, JeecgTencent tencent, DySmsEnum dySmsEnum) { //获取客户端链接 SmsClient client = getSmsClient(tencent); //构建腾讯云短信发送请求 SendSmsRequest req = buildSendSmsRequest(phone, templateParamJson, dySmsEnum, tencent); try { //发送短信 SendSmsResponse resp = client.SendSms(req); // 处理响应 SendStatus[] statusSet = resp.getSendStatusSet(); if (statusSet != null && statusSet.length > 0) { SendStatus status = statusSet[0]; if ("Ok".equals(status.getCode())) { logger.info("短信发送成功,手机号:{}", phone); return true; } else { logger.error("短信发送失败,手机号:{},错误码:{},错误信息:{}", phone, status.getCode(), status.getMessage()); } } } catch (TencentCloudSDKException e) { logger.error("短信发送失败{}", e.getMessage()); } return false; } /** * 获取sms客户端 * * @param tencent 腾讯云配置 * @return SmsClient对象 */ private static SmsClient getSmsClient(JeecgTencent tencent) { Credential cred = new Credential(tencent.getSecretId(), tencent.getSecretKey()); // 实例化一个http选项,可选的,没有特殊需求可以跳过 HttpProfile httpProfile = new HttpProfile(); //指定接入地域域名*/ httpProfile.setEndpoint(tencent.getEndpoint()); //实例化一个客户端配置对象 ClientProfile clientProfile = new ClientProfile(); clientProfile.setHttpProfile(httpProfile); //实例化要请求产品的client对象,第二个参数是地域信息 return new SmsClient(cred, tencent.getRegion(), clientProfile); } /** * 构建腾讯云短信发送请求 * * @param phone 手机号码 * @param templateParamJson 模板参数JSON对象 * @param dySmsEnum 短信枚举配置 * @param tencent 腾讯云配置 * @return 构建好的SendSmsRequest对象 */ private static SendSmsRequest buildSendSmsRequest( String phone, JSONObject templateParamJson, DySmsEnum dySmsEnum, JeecgTencent tencent) { SendSmsRequest req = new SendSmsRequest(); // 1. 设置短信应用ID String sdkAppId = tencent.getSdkAppId(); req.setSmsSdkAppId(sdkAppId); // 2. 设置短信签名 String signName = getSmsSignName(dySmsEnum); req.setSignName(signName); // 3. 设置模板ID String templateId = getSmsTemplateId(dySmsEnum); req.setTemplateId(templateId); // 4. 设置模板参数 String[] templateParams = extractTemplateParams(templateParamJson); req.setTemplateParamSet(templateParams); // 5. 设置手机号码 String[] phoneNumberSet = { phone }; req.setPhoneNumberSet(phoneNumberSet); logger.debug("构建短信请求完成 - 应用ID: {}, 签名: {}, 模板ID: {}, 手机号: {}", sdkAppId, signName, templateId, phone); return req; } /** * 获取短信签名名称 * * @param dySmsEnum 腾讯云对象 */ private static String getSmsSignName(DySmsEnum dySmsEnum) { JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class); String signName = dySmsEnum.getSignName(); if (StringUtils.isNotEmpty(baseConfig.getSignature())) { logger.debug("yml中读取签名名称: {}", baseConfig.getSignature()); signName = baseConfig.getSignature(); } return signName; } /** * 获取短信模板ID * * @param dySmsEnum 腾讯云对象 */ private static String getSmsTemplateId(DySmsEnum dySmsEnum) { JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class); String templateCode = dySmsEnum.getTemplateCode(); if (StringUtils.isNotEmpty(baseConfig.getSignature())) { Map<String, String> smsTemplate = baseConfig.getTemplateCode(); if (smsTemplate.containsKey(templateCode) && StringUtils.isNotEmpty(smsTemplate.get(templateCode))) { templateCode = smsTemplate.get(templateCode); logger.debug("yml中读取短信模板ID: {}", templateCode); } } return templateCode; } /** * 从JSONObject中提取模板参数(按原始顺序) * * @param templateParamJson 模板参数 */ private static String[] extractTemplateParams(JSONObject templateParamJson) { if (templateParamJson == null || templateParamJson.isEmpty()) { return new String[0]; } List<String> params = new ArrayList<>(); for (String key : templateParamJson.keySet()) { Object value = templateParamJson.get(key); if (value != null) { params.add(value.toString()); } else { // 处理null值 params.add(""); } } logger.debug("提取模板参数: {}", params); return params.toArray(new String[0]); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DySmsHelper.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DySmsHelper.java
package org.jeecg.common.util; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.enums.DySmsEnum; import org.jeecg.config.JeecgBaseConfig; import org.jeecg.config.JeecgSmsTemplateConfig; import org.jeecg.config.StaticConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /** * Created on 17/6/7. * 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) * 工程依赖了2个jar包(存放在工程的libs目录下) * 1:aliyun-java-sdk-core.jar * 2:aliyun-java-sdk-dysmsapi.jar * * 备注:Demo工程编码采用UTF-8 * 国际短信发送请勿参照此DEMO * @author: jeecg-boot */ public class DySmsHelper { private final static Logger logger=LoggerFactory.getLogger(DySmsHelper.class); /**产品名称:云通信短信API产品,开发者无需替换*/ static final String PRODUCT = "Dysmsapi"; /**产品域名,开发者无需替换*/ static final String DOMAIN = "dysmsapi.aliyuncs.com"; /**TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)*/ static String accessKeyId; static String accessKeySecret; public static void setAccessKeyId(String accessKeyId) { DySmsHelper.accessKeyId = accessKeyId; } public static void setAccessKeySecret(String accessKeySecret) { DySmsHelper.accessKeySecret = accessKeySecret; } public static String getAccessKeyId() { return accessKeyId; } public static String getAccessKeySecret() { return accessKeySecret; } public static boolean sendSms(String phone, JSONObject templateParamJson, DySmsEnum dySmsEnum) throws ClientException { JeecgBaseConfig config = SpringContextUtils.getBean(JeecgBaseConfig.class); String smsSendType = config.getSmsSendType(); if(oConvertUtils.isNotEmpty(smsSendType) && CommonConstant.SMS_SEND_TYPE_TENCENT.equals(smsSendType)){ return TencentSms.sendTencentSms(phone, templateParamJson, config.getTencent(), dySmsEnum); } //可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // 代码逻辑说明: 配置类数据获取 StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class); //logger.info("阿里大鱼短信秘钥 accessKeyId:" + staticConfig.getAccessKeyId()); //logger.info("阿里大鱼短信秘钥 accessKeySecret:"+ staticConfig.getAccessKeySecret()); setAccessKeyId(staticConfig.getAccessKeyId()); setAccessKeySecret(staticConfig.getAccessKeySecret()); //初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", PRODUCT, DOMAIN); IAcsClient acsClient = new DefaultAcsClient(profile); //验证json参数 validateParam(templateParamJson,dySmsEnum); // 代码逻辑说明: 【QQYUN-9422】短信模板管理,阿里云--- String templateCode = dySmsEnum.getTemplateCode(); JeecgSmsTemplateConfig baseConfig = SpringContextUtils.getBean(JeecgSmsTemplateConfig.class); if(baseConfig != null && CollectionUtil.isNotEmpty(baseConfig.getTemplateCode())){ Map<String, String> smsTemplate = baseConfig.getTemplateCode(); if(smsTemplate.containsKey(templateCode) && StringUtils.isNotEmpty(smsTemplate.get(templateCode))){ templateCode = smsTemplate.get(templateCode); logger.info("yml中读取短信code{}",templateCode); } } //签名名称 String signName = dySmsEnum.getSignName(); if(baseConfig != null && StringUtils.isNotEmpty(baseConfig.getSignature())){ logger.info("yml中读取签名名称{}",baseConfig.getSignature()); signName = baseConfig.getSignature(); } //组装请求对象-具体描述见控制台-文档部分内容 SendSmsRequest request = new SendSmsRequest(); //必填:待发送手机号 request.setPhoneNumbers(phone); //必填:短信签名-可在短信控制台中找到 request.setSignName(signName); //必填:短信模板-可在短信控制台中找到 request.setTemplateCode(templateCode); //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam(templateParamJson.toJSONString()); //选填-上行短信扩展码(无特殊需求用户请忽略此字段) //request.setSmsUpExtendCode("90997"); //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 //request.setOutId("yourOutId"); boolean result = false; //hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); logger.info("短信接口返回的数据----------------"); logger.info("{Code:" + sendSmsResponse.getCode()+",Message:" + sendSmsResponse.getMessage()+",RequestId:"+ sendSmsResponse.getRequestId()+",BizId:"+sendSmsResponse.getBizId()+"}"); String ok = "OK"; if (ok.equals(sendSmsResponse.getCode())) { result = true; } return result; } private static void validateParam(JSONObject templateParamJson,DySmsEnum dySmsEnum) { String keys = dySmsEnum.getKeys(); String [] keyArr = keys.split(","); for(String item :keyArr) { if(!templateParamJson.containsKey(item)) { throw new RuntimeException("模板缺少参数:"+item); } } } // public static void main(String[] args) throws ClientException, InterruptedException { // JSONObject obj = new JSONObject(); // obj.put("code", "1234"); // sendSms("13800138000", obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE); // } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/SqlInjectionUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/SqlInjectionUtil.java
package org.jeecg.common.util; import cn.hutool.core.util.ReUtil; import lombok.extern.slf4j.Slf4j; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.exception.JeecgSqlInjectionException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * sql注入处理工具类 * * @author zhoujf */ @Slf4j public class SqlInjectionUtil { /** * sql注入黑名单数据库名 */ public final static String XSS_STR_TABLE = "peformance_schema|information_schema"; /** * 默认—sql注入关键词 */ private final static String XSS_STR = "and |exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|or |+|--"; /** * online报表专用—sql注入关键词 */ private static String specialReportXssStr = "exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |alter |delete |grant |update |drop |master |truncate |declare |--"; /** * 字典专用—sql注入关键词 */ private static String specialDictSqlXssStr = "exec |peformance_schema|information_schema|extractvalue|updatexml|geohash|gtid_subset|gtid_subtract|insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |;|+|--"; /** * 完整匹配的key,不需要考虑前空格 */ private static List<String> FULL_MATCHING_KEYWRODS = new ArrayList<>(); static { FULL_MATCHING_KEYWRODS.add(";"); FULL_MATCHING_KEYWRODS.add("+"); FULL_MATCHING_KEYWRODS.add("--"); } /** * sql注入风险的 正则关键字 * * 函数匹配,需要用正则模式 */ private final static String[] XSS_REGULAR_STR_ARRAY = new String[]{ "chr\\s*\\(", "mid\\s*\\(", " char\\s*\\(", "sleep\\s*\\(", "user\\s*\\(", "show\\s+tables", "user[\\s]*\\([\\s]*\\)", "show\\s+databases", "sleep\\(\\d*\\)", "sleep\\(.*\\)", }; /** * sql注释的正则 */ private final static Pattern SQL_ANNOTATION = Pattern.compile("/\\*[\\s\\S]*\\*/"); private final static String SQL_ANNOTATION2 = "--"; /** * sql注入提示语 */ private final static String SQL_INJECTION_KEYWORD_TIP = "请注意,存在SQL注入关键词---> {}"; private final static String SQL_INJECTION_TIP = "请注意,值可能存在SQL注入风险!--->"; private final static String SQL_INJECTION_TIP_VARIABLE = "请注意,值可能存在SQL注入风险!---> {}"; /** * sql注入过滤处理,遇到注入关键字抛异常 * @param values */ public static void filterContentMulti(String... values) { filterContent(values, null); } /** * 校验比较严格 * * sql注入过滤处理,遇到注入关键字抛异常 * * @param value * @return */ public static void filterContent(String value, String customXssString) { if (value == null || "".equals(value)) { return; } // 一、校验sql注释 不允许有sql注释 checkSqlAnnotation(value); // 转为小写进行后续比较 value = value.toLowerCase().trim(); // 二、SQL注入检测存在绕过风险 (普通文本校验) //https://gitee.com/jeecg/jeecg-boot/issues/I4NZGE String[] xssArr = XSS_STR.split("\\|"); for (int i = 0; i < xssArr.length; i++) { if (value.indexOf(xssArr[i]) > -1) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr[i]); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } // 三、SQL注入检测存在绕过风险 (自定义传入普通文本校验) if (customXssString != null) { String[] xssArr2 = customXssString.split("\\|"); for (int i = 0; i < xssArr2.length; i++) { if (value.indexOf(xssArr2[i]) > -1) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr2[i]); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } } // 四、SQL注入检测存在绕过风险 (正则校验) for (String regularOriginal : XSS_REGULAR_STR_ARRAY) { String regular = ".*" + regularOriginal + ".*"; if (Pattern.matches(regular, value)) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, regularOriginal); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } return; } /** * 判断是否存在SQL注入关键词字符串 * * @param keyword * @return */ @SuppressWarnings("AlibabaUndefineMagicConstant") private static boolean isExistSqlInjectKeyword(String sql, String keyword) { if (sql.startsWith(keyword.trim())) { return true; } else if (sql.contains(keyword)) { // 需要匹配的,sql注入关键词 String matchingText = " " + keyword; if(FULL_MATCHING_KEYWRODS.contains(keyword)){ matchingText = keyword; } if (sql.contains(matchingText)) { return true; } else { String regularStr = "\\s+\\S+" + keyword; List<String> resultFindAll = ReUtil.findAll(regularStr, sql, 0, new ArrayList<String>()); for (String res : resultFindAll) { log.info("isExistSqlInjectKeyword —- 匹配到的SQL注入关键词:{}", res); /** * SQL注入中可以替换空格的字符(%09 %0A %0D +都可以替代空格) * http://blog.chinaunix.net/uid-12501104-id-2932639.html * https://www.cnblogs.com/Vinson404/p/7253255.html * */ if (res.contains("%") || res.contains("+") || res.contains("#") || res.contains("/") || res.contains(")")) { return true; } } } } return false; } /** * 判断是否存在SQL注入关键词字符串 * * @param keyword * @return */ @SuppressWarnings("AlibabaUndefineMagicConstant") private static boolean isExistSqlInjectTableKeyword(String sql, String keyword) { // 需要匹配的,sql注入关键词 String[] matchingTexts = new String[]{"`" + keyword, "(" + keyword, "(`" + keyword}; for (String matchingText : matchingTexts) { String[] checkTexts = new String[]{" " + matchingText, "from" + matchingText}; for (String checkText : checkTexts) { if (sql.contains(checkText)) { return true; } } } return false; } /** * sql注入过滤处理,遇到注入关键字抛异常 * * @param values * @return */ public static void filterContent(String[] values, String customXssString) { for (String val : values) { if (oConvertUtils.isEmpty(val)) { return; } filterContent(val, customXssString); } return; } /** * 【提醒:不通用】 * 仅用于字典条件SQL参数,注入过滤 * * @param value * @return */ public static void specialFilterContentForDictSql(String value) { String[] xssArr = specialDictSqlXssStr.split("\\|"); if (value == null || "".equals(value)) { return; } // 一、校验sql注释 不允许有sql注释 checkSqlAnnotation(value); value = value.toLowerCase().trim(); // 二、SQL注入检测存在绕过风险 (普通文本校验) for (int i = 0; i < xssArr.length; i++) { if (isExistSqlInjectKeyword(value, xssArr[i])) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr[i]); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } String[] xssTableArr = XSS_STR_TABLE.split("\\|"); for (String xssTableStr : xssTableArr) { if (isExistSqlInjectTableKeyword(value, xssTableStr)) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssTableStr); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } // 三、SQL注入检测存在绕过风险 (正则校验) for (String regularOriginal : XSS_REGULAR_STR_ARRAY) { String regular = ".*" + regularOriginal + ".*"; if (Pattern.matches(regular, value)) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, regularOriginal); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } return; } /** * 【提醒:不通用】 * 仅用于Online报表SQL解析,注入过滤 * @param value * @return */ public static void specialFilterContentForOnlineReport(String value) { String[] xssArr = specialReportXssStr.split("\\|"); if (value == null || "".equals(value)) { return; } // 一、校验sql注释 不允许有sql注释 checkSqlAnnotation(value); value = value.toLowerCase().trim(); // 二、SQL注入检测存在绕过风险 (普通文本校验) for (int i = 0; i < xssArr.length; i++) { if (isExistSqlInjectKeyword(value, xssArr[i])) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssArr[i]); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } String[] xssTableArr = XSS_STR_TABLE.split("\\|"); for (String xssTableStr : xssTableArr) { if (isExistSqlInjectTableKeyword(value, xssTableStr)) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, xssTableStr); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } // 三、SQL注入检测存在绕过风险 (正则校验) for (String regularOriginal : XSS_REGULAR_STR_ARRAY) { String regular = ".*" + regularOriginal + ".*"; if (Pattern.matches(regular, value)) { log.error(SqlInjectionUtil.SQL_INJECTION_KEYWORD_TIP, regularOriginal); log.error(SqlInjectionUtil.SQL_INJECTION_TIP_VARIABLE, value); throw new JeecgSqlInjectionException(SqlInjectionUtil.SQL_INJECTION_TIP + value); } } return; } /** * 校验是否有sql注释 * @return */ public static void checkSqlAnnotation(String str){ if(str.contains(SQL_ANNOTATION2)){ String error = "请注意,SQL中不允许含注释,有安全风险!"; log.error(error); throw new RuntimeException(error); } Matcher matcher = SQL_ANNOTATION.matcher(str); if(matcher.find()){ String error = "请注意,值可能存在SQL注入风险---> \\*.*\\"; log.error(error); throw new JeecgSqlInjectionException(error); } } /** * 返回查询表名 * <p> * sql注入过滤处理,遇到注入关键字抛异常 * * @param table */ private static Pattern tableNamePattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_\\$]{0,63}$"); public static String getSqlInjectTableName(String table) { if(oConvertUtils.isEmpty(table)){ return table; } // 代码逻辑说明: 表单设计器列表翻译存在表名带条件,导致翻译出问题---- int index = table.toLowerCase().indexOf(" where "); if (index != -1) { table = table.substring(0, index); log.info("截掉where之后的新表名:" + table); } table = table.trim(); /** * 检验表名是否合法 * * 表名只能由字母、数字和下划线组成。 * 表名必须以字母开头。 * 表名长度通常有限制,例如最多为 64 个字符。 */ boolean isValidTableName = tableNamePattern.matcher(table).matches(); if (!isValidTableName) { String errorMsg = "表名不合法,存在SQL注入风险!--->" + table; log.error(errorMsg); throw new JeecgSqlInjectionException(errorMsg); } //进一步验证是否存在SQL注入风险 filterContentMulti(table); return table; } /** * 返回查询字段 * <p> * sql注入过滤处理,遇到注入关键字抛异常 * * @param field */ static final Pattern fieldPattern = Pattern.compile("^[a-zA-Z0-9_]+$"); public static String getSqlInjectField(String field) { if(oConvertUtils.isEmpty(field)){ return field; } field = field.trim(); if (field.contains(SymbolConstant.COMMA)) { return getSqlInjectField(field.split(SymbolConstant.COMMA)); } /** * 校验表字段是否有效 * * 字段定义只能是是字母 数字 下划线的组合(不允许有空格、转义字符串等) */ boolean isValidField = fieldPattern.matcher(field).matches(); if (!isValidField) { String errorMsg = "字段不合法,存在SQL注入风险!--->" + field; log.error(errorMsg); throw new JeecgSqlInjectionException(errorMsg); } //进一步验证是否存在SQL注入风险 filterContentMulti(field); return field; } /** * 获取多个字段 * 返回: 逗号拼接 * * @param fields * @return */ public static String getSqlInjectField(String... fields) { for (String s : fields) { getSqlInjectField(s); } return String.join(SymbolConstant.COMMA, fields); } /** * 获取排序字段 * 返回:字符串 * * 1.将驼峰命名转化成下划线 * 2.限制sql注入 * @param sortField 排序字段 * @return */ public static String getSqlInjectSortField(String sortField) { String field = SqlInjectionUtil.getSqlInjectField(oConvertUtils.camelToUnderline(sortField)); return field; } /** * 获取多个排序字段 * 返回:数组 * * 1.将驼峰命名转化成下划线 * 2.限制sql注入 * @param sortFields 多个排序字段 * @return */ public static List getSqlInjectSortFields(String... sortFields) { List list = new ArrayList<String>(); for (String sortField : sortFields) { list.add(getSqlInjectSortField(sortField)); } return list; } /** * 获取 orderBy type * 返回:字符串 * <p> * 1.检测是否为 asc 或 desc 其中的一个 * 2.限制sql注入 * * @param orderType * @return */ public static String getSqlInjectOrderType(String orderType) { if (orderType == null) { return null; } orderType = orderType.trim(); if (CommonConstant.ORDER_TYPE_ASC.equalsIgnoreCase(orderType)) { return CommonConstant.ORDER_TYPE_ASC; } else { return CommonConstant.ORDER_TYPE_DESC; } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/UUIDGenerator.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/UUIDGenerator.java
package org.jeecg.common.util; import java.net.InetAddress; /** * * @Author 张代浩 * */ public class UUIDGenerator { /** * 产生一个32位的UUID * * @return */ public static String generate() { return new StringBuilder(32).append(format(getIp())).append( format(getJvm())).append(format(getHiTime())).append( format(getLoTime())).append(format(getCount())).toString(); } private static final int IP; static { int ipadd; try { ipadd = toInt(InetAddress.getLocalHost().getAddress()); } catch (Exception e) { ipadd = 0; } IP = ipadd; } private static short counter = (short) 0; private static final int JVM = (int) (System.currentTimeMillis() >>> 8); private final static String format(int intval) { String formatted = Integer.toHexString(intval); StringBuilder buf = new StringBuilder("00000000"); buf.replace(8 - formatted.length(), 8, formatted); return buf.toString(); } private final static String format(short shortval) { String formatted = Integer.toHexString(shortval); StringBuilder buf = new StringBuilder("0000"); buf.replace(4 - formatted.length(), 4, formatted); return buf.toString(); } private final static int getJvm() { return JVM; } private final static short getCount() { synchronized (UUIDGenerator.class) { if (counter < 0) { counter = 0; } return counter++; } } /** * Unique in a local network */ private final static int getIp() { return IP; } /** * Unique down to millisecond */ private final static short getHiTime() { return (short) (System.currentTimeMillis() >>> 32); } private final static int getLoTime() { return (int) System.currentTimeMillis(); } private final static int toInt(byte[] bytes) { int result = 0; int length = 4; for (int i = 0; i < length; i++) { result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i]; } return result; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/BrowserType.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/BrowserType.java
package org.jeecg.common.util; /** * * @Author 张代浩 * */ public enum BrowserType { /** * 浏览类型 IE11,IE10,IE9,IE8,IE7,IE6,Firefox,Safari,Chrome,Opera,Camino,Gecko */ IE11,IE10,IE9,IE8,IE7,IE6,Firefox,Safari,Chrome,Opera,Camino,Gecko }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/AssertUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/AssertUtils.java
package org.jeecg.common.util; import org.jeecg.common.exception.JeecgBootAssertException; /** * 断言检查工具 * for for [QQYUN-10990]AIRAG * @author chenrui * @date 2017-06-22 10:05:56 */ public class AssertUtils { /** * 确保对象为空,如果不为空抛出异常 * * @param msg * @param obj * @throws JeecgBootAssertException * @author chenrui * @date 2017-06-22 10:05:56 */ public static void assertEmpty(String msg, Object obj) { if (oConvertUtils.isObjectNotEmpty(obj)) { throw new JeecgBootAssertException(msg); } } /** * 确保对象不为空,如果为空抛出异常 * * @param msg * @param obj * @throws JeecgBootAssertException * @author chenrui * @date 2017-06-22 10:05:56 */ public static void assertNotEmpty(String msg, Object obj) { if (oConvertUtils.isObjectEmpty(obj)) { throw new JeecgBootAssertException(msg); } } /** * 验证对象是否相同 * * @param message * @param expected * @param actual * @author chenrui * @date 2018/9/12 15:45 */ public static void assertEquals(String message, Object expected, Object actual) { if (oConvertUtils.isEqual(expected, actual)) { return; } throw new JeecgBootAssertException(message); } /** * 验证不相同 * * @param message * @param expected * @param actual * @author chenrui * @date 2018/9/12 15:45 */ public static void assertNotEquals(String message, Object expected, Object actual) { if (oConvertUtils.isEqual(expected, actual)) { throw new JeecgBootAssertException(message); } } /** * 验证是否相等 * * @param message * @param expected * @param actual * @author chenrui * @date 2018/9/12 15:45 */ public static void assertSame(String message, Object expected, Object actual) { if (expected == actual) { return; } throw new JeecgBootAssertException(message); } /** * 验证不相等 * * @param message * @param unexpected * @param actual * @author chenrui * @date 2018/9/12 15:45 */ public static void assertNotSame(String message, Object unexpected, Object actual) { if (unexpected == actual) { throw new JeecgBootAssertException(message); } } /** * 验证是否为真 * * @param message * @param condition */ public static void assertTrue(String message, boolean condition) { if (!condition) { throw new JeecgBootAssertException(message); } } /** * 验证 condition是否为false * * @param message * @param condition */ public static void assertFalse(String message, boolean condition) { assertTrue(message, !condition); } /** * 验证是否存在 * * @param message * @param obj * @param objs * @param <T> * @throws JeecgBootAssertException * @author chenrui * @date 2018/1/31 22:14 */ public static <T> void assertIn(String message, T obj, T... objs) { assertNotEmpty(message, obj); assertNotEmpty(message, objs); if (!oConvertUtils.isIn(obj, objs)) { throw new JeecgBootAssertException(message); } } /** * 验证是否不存在 * * @param message * @param obj * @param objs * @param <T> * @throws JeecgBootAssertException * @author chenrui * @date 2018/1/31 22:14 */ public static <T> void assertNotIn(String message, T obj, T... objs) { assertNotEmpty(message, obj); assertNotEmpty(message, objs); if (oConvertUtils.isIn(obj, objs)) { throw new JeecgBootAssertException(message); } } /** * 确保src大于des * * @param message * @param src * @param des * @author chenrui * @date 2018/9/19 15:30 */ public static void assertGt(String message, Number src, Number des) { if (oConvertUtils.isGt(src, des)) { return; } throw new JeecgBootAssertException(message); } /** * 确保src大于等于des * * @param message * @param src * @param des * @author chenrui * @date 2018/9/19 15:30 */ public static void assertGe(String message, Number src, Number des) { if (oConvertUtils.isGe(src, des)) { return; } throw new JeecgBootAssertException(message); } /** * 确保src小于des * * @param message * @param src * @param des * @author chenrui * @date 2018/9/19 15:30 */ public static void assertLt(String message, Number src, Number des) { if (oConvertUtils.isGe(src, des)) { throw new JeecgBootAssertException(message); } } /** * 确保src小于等于des * * @param message * @param src * @param des * @author chenrui * @date 2018/9/19 15:30 */ public static void assertLe(String message, Number src, Number des) { if (oConvertUtils.isGt(src, des)) { throw new JeecgBootAssertException(message); } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MyCommonsMultipartFile.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MyCommonsMultipartFile.java
package org.jeecg.common.util; import org.apache.commons.fileupload.FileItem; import org.springframework.web.multipart.MultipartFile; import java.io.*; /** * @date 2025-09-04 * @author scott * * 升级springboot3 无法使用 CommonsMultipartFile * 自定义 MultipartFile 实现类,支持从 FileItem 构造 */ public class MyCommonsMultipartFile implements MultipartFile { private final byte[] fileContent; private final String fileName; private final String contentType; // 新增构造方法,支持 FileItem 参数 public MyCommonsMultipartFile(FileItem fileItem) throws IOException { this.fileName = fileItem.getName(); this.contentType = fileItem.getContentType(); try (InputStream inputStream = fileItem.getInputStream()) { this.fileContent = inputStream.readAllBytes(); } } // 现有构造方法 public MyCommonsMultipartFile(InputStream inputStream, String fileName, String contentType) throws IOException { this.fileName = fileName; this.contentType = contentType; this.fileContent = inputStream.readAllBytes(); } @Override public String getName() { return fileName; } @Override public String getOriginalFilename() { return fileName; } @Override public String getContentType() { return contentType; } @Override public boolean isEmpty() { return fileContent.length == 0; } @Override public long getSize() { return fileContent.length; } @Override public byte[] getBytes() { return fileContent; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(fileContent); } @Override public void transferTo(File dest) throws IOException { try (OutputStream os = new FileOutputStream(dest)) { os.write(fileContent); } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/CommonUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/CommonUtils.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSONObject; import com.baomidou.dynamic.datasource.creator.DataSourceProperty; import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.ServiceNameConstants; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.util.filter.SsrfFileTypeFilter; import org.jeecg.common.util.oss.OssBootUtil; import org.jeecgframework.poi.util.PoiPublicUtil; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.util.FileCopyUtils; import org.springframework.web.multipart.MultipartFile; import jakarta.servlet.http.HttpServletRequest; import javax.sql.DataSource; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Description: 通用工具 * @author: jeecg-boot */ @Slf4j public class CommonUtils { /** * 中文正则 */ private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]"); /** * 文件名 正则字符串 * 文件名支持的字符串:字母数字中文.-_()() 除此之外的字符将被删除 */ private static String FILE_NAME_REGEX = "[^A-Za-z\\.\\(\\)\\-()\\_0-9\\u4e00-\\u9fa5]"; public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){ String dbPath = null; String fileName = "image" + Math.round(Math.random() * 100000000000L); fileName += "." + PoiPublicUtil.getFileExtendName(data); try { if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){ File file = new File(basePath + File.separator + bizPath + File.separator ); if (!file.exists()) { file.mkdirs();// 创建文件根目录 } String savePath = file.getPath() + File.separator + fileName; File savefile = new File(savePath); FileCopyUtils.copy(data, savefile); dbPath = bizPath + File.separator + fileName; }else { InputStream in = new ByteArrayInputStream(data); String relativePath = bizPath+"/"+fileName; if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){ dbPath = MinioUtil.upload(in,relativePath); }else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){ dbPath = OssBootUtil.upload(in,relativePath); } } } catch (Exception e) { e.printStackTrace(); } return dbPath; } /** * 判断文件名是否带盘符,重新处理 * @param fileName * @return */ public static String getFileName(String fileName){ //判断是否带有盘符信息 // Check for Unix-style path int unixSep = fileName.lastIndexOf('/'); // Check for Windows-style path int winSep = fileName.lastIndexOf('\\'); // Cut off at latest possible point int pos = (winSep > unixSep ? winSep : unixSep); if (pos != -1) { // Any sort of path separator found... fileName = fileName.substring(pos + 1); } //替换上传文件名字的特殊字符 fileName = fileName.replace("=","").replace(",","").replace("&","") .replace("#", "").replace("“", "").replace("”", ""); //替换上传文件名字中的空格 fileName=fileName.replaceAll("\\s",""); //update-beign-author:taoyan date:20220302 for: /issues/3381 online 在线表单 使用文件组件时,上传文件名中含%,下载异常 fileName = fileName.replaceAll(FILE_NAME_REGEX, ""); //update-end-author:taoyan date:20220302 for: /issues/3381 online 在线表单 使用文件组件时,上传文件名中含%,下载异常 return fileName; } /** * java 判断字符串里是否包含中文字符 * @param str * @return */ public static boolean ifContainChinese(String str) { if(str.getBytes().length == str.length()){ return false; }else{ Matcher m = ZHONGWEN_PATTERN.matcher(str); if (m.find()) { return true; } return false; } } /** * 统一全局上传 * @Return: java.lang.String */ public static String upload(MultipartFile file, String bizPath, String uploadType) { String url = ""; try { if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) { url = MinioUtil.upload(file, bizPath); } else { url = OssBootUtil.upload(file, bizPath); } } catch (Exception e) { log.error(e.getMessage(), e); throw new JeecgBootException(e.getMessage()); } return url; } /** * 本地文件上传 * @param mf 文件 * @param bizPath 自定义路径 * @return */ public static String uploadLocal(MultipartFile mf,String bizPath,String uploadpath){ try { // 文件安全校验,防止上传漏洞文件 SsrfFileTypeFilter.checkUploadFileType(mf, bizPath); String fileName = null; File file = new File(uploadpath + File.separator + bizPath + File.separator ); if (!file.exists()) { // 创建文件根目录 file.mkdirs(); } // 获取文件名 String orgName = mf.getOriginalFilename(); // 无中文情况下进行转码 if (orgName != null && !CommonUtils.ifContainChinese(orgName)) { orgName = new String(orgName.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); } orgName = CommonUtils.getFileName(orgName); if(orgName.indexOf(SymbolConstant.SPOT)!=-1){ fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf(".")); }else{ fileName = orgName+ "_" + System.currentTimeMillis(); } String savePath = file.getPath() + File.separator + fileName; File savefile = new File(savePath); FileCopyUtils.copy(mf.getBytes(), savefile); String dbpath = null; if(oConvertUtils.isNotEmpty(bizPath)){ dbpath = bizPath + File.separator + fileName; }else{ dbpath = fileName; } if (dbpath.contains(SymbolConstant.DOUBLE_BACKSLASH)) { dbpath = dbpath.replace("\\", "/"); } return dbpath; } catch (IOException e) { log.error(e.getMessage(), e); }catch (Exception e) { log.error(e.getMessage(), e); } return ""; } /** * 统一全局上传 带桶 * @Return: java.lang.String */ public static String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) { String url = ""; try { if (CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)) { url = MinioUtil.upload(file, bizPath, customBucket); } else { url = OssBootUtil.upload(file, bizPath, customBucket); } } catch (Exception e) { log.error(e.getMessage(),e); } return url; } /** 当前系统数据库类型 */ private static String DB_TYPE = ""; private static DbType dbTypeEnum = null; /** * 全局获取平台数据库类型(作废了) * @return */ @Deprecated public static String getDatabaseType() { if(oConvertUtils.isNotEmpty(DB_TYPE)){ return DB_TYPE; } DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class); try { return getDatabaseTypeByDataSource(dataSource); } catch (SQLException e) { //e.printStackTrace(); log.warn(e.getMessage(),e); return ""; } } /** * 全局获取平台数据库类型(对应mybaisPlus枚举) * @return */ public static DbType getDatabaseTypeEnum() { if (oConvertUtils.isNotEmpty(dbTypeEnum)) { return dbTypeEnum; } try { DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class); dbTypeEnum = JdbcUtils.getDbType(dataSource.getConnection().getMetaData().getURL()); //【采用SQL_SERVER2005引擎】QQYUN-13298 解决升级mybatisPlus后SqlServer分页使用OFFSET,无排序字段报错问题 if (dbTypeEnum == DbType.SQL_SERVER) { dbTypeEnum = DbType.SQL_SERVER2005; } return dbTypeEnum; } catch (SQLException e) { log.warn(e.getMessage(), e); return null; } } /** * 根据数据源key获取DataSourceProperty * @param sourceKey * @return */ public static DataSourceProperty getDataSourceProperty(String sourceKey){ DynamicDataSourceProperties prop = SpringContextUtils.getApplicationContext().getBean(DynamicDataSourceProperties.class); Map<String, DataSourceProperty> map = prop.getDatasource(); DataSourceProperty db = (DataSourceProperty)map.get(sourceKey); return db; } /** * 根据sourceKey 获取数据源连接 * @param sourceKey * @return * @throws SQLException */ public static Connection getDataSourceConnect(String sourceKey) throws SQLException { if (oConvertUtils.isEmpty(sourceKey)) { sourceKey = "master"; } DynamicDataSourceProperties prop = SpringContextUtils.getApplicationContext().getBean(DynamicDataSourceProperties.class); Map<String, DataSourceProperty> map = prop.getDatasource(); DataSourceProperty db = (DataSourceProperty)map.get(sourceKey); if(db==null){ return null; } DriverManagerDataSource ds = new DriverManagerDataSource (); ds.setDriverClassName(db.getDriverClassName()); ds.setUrl(db.getUrl()); ds.setUsername(db.getUsername()); ds.setPassword(db.getPassword()); return ds.getConnection(); } /** * 获取数据库类型 * @param dataSource * @return * @throws SQLException */ private static String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{ if("".equals(DB_TYPE)) { Connection connection = dataSource.getConnection(); try { DatabaseMetaData md = connection.getMetaData(); String dbType = md.getDatabaseProductName().toUpperCase(); String sqlserver= "SQL SERVER"; if(dbType.indexOf(DataBaseConstant.DB_TYPE_MYSQL)>=0) { DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL; }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_ORACLE)>=0 ||dbType.indexOf(DataBaseConstant.DB_TYPE_DM)>=0) { DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE; }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_SQLSERVER)>=0||dbType.indexOf(sqlserver)>=0) { DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER; }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_POSTGRESQL)>=0 || dbType.indexOf(DataBaseConstant.DB_TYPE_KINGBASEES)>=0) { DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL; }else if(dbType.indexOf(DataBaseConstant.DB_TYPE_MARIADB)>=0) { DB_TYPE = DataBaseConstant.DB_TYPE_MARIADB; }else { log.error("数据库类型:[" + dbType + "]不识别!"); //throw new JeecgBootException("数据库类型:["+dbType+"]不识别!"); } } catch (Exception e) { log.error(e.getMessage(), e); }finally { connection.close(); } } return DB_TYPE; } /** * 获取服务器地址 * * @param request * @return */ public static String getBaseUrl(HttpServletRequest request) { //1.【兼容】兼容微服务下的 base path------- String xGatewayBasePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH); if(oConvertUtils.isNotEmpty(xGatewayBasePath)){ log.info("x_gateway_base_path = "+ xGatewayBasePath); return xGatewayBasePath; } //2.【兼容】SSL认证之后,request.getScheme()获取不到https的问题 // https://blog.csdn.net/weixin_34376986/article/details/89767950 String scheme = request.getHeader(CommonConstant.X_FORWARDED_SCHEME); if(oConvertUtils.isEmpty(scheme)){ scheme = request.getScheme(); } //3.常规操作 String serverName = request.getServerName(); int serverPort = request.getServerPort(); String contextPath = request.getContextPath(); //返回 host domain String baseDomainPath = null; //update-begin---author:wangshuai---date:2024-03-15---for:【QQYUN-8561】企业微信登陆请求接口设置上下文不一致,导致接口404--- int httpPort = 80; int httpsPort = 443; if(httpPort == serverPort || httpsPort == serverPort){ //update-end---author:wangshuai---date:2024-03-15---for:【QQYUN-8561】企业微信登陆请求接口设置上下文不一致,导致接口404---~ baseDomainPath = scheme + "://" + serverName + contextPath ; }else{ baseDomainPath = scheme + "://" + serverName + ":" + serverPort + contextPath ; } log.debug("-----Common getBaseUrl----- : " + baseDomainPath); return baseDomainPath; } /** * 递归合并 fastJSON 对象 * * @param target 目标对象 * @param sources 来源对象,允许多个,优先级从左到右,最右侧的优先级最高 */ public static JSONObject mergeJSON(JSONObject target, JSONObject... sources) { for (JSONObject source : sources) { CommonUtils.mergeJSON(target, source); } return target; } /** * 递归合并 fastJSON 对象 * * @param target 目标对象 * @param source 来源对象 */ public static JSONObject mergeJSON(JSONObject target, JSONObject source) { for (String key : source.keySet()) { Object sourceItem = source.get(key); // 是否是 JSONObject if (sourceItem instanceof Map) { // target中存在此key if (target.containsKey(key)) { // 两个都是 JSONObject,继续合并 if (target.get(key) instanceof Map) { CommonUtils.mergeJSON(target.getJSONObject(key), source.getJSONObject(key)); continue; } } } // target不存在此key,或不是 JSONObject,则覆盖 target.put(key, sourceItem); } return target; } /** * 将list集合以分割符的方式进行分割 * @param list String类型的集合文本 * @param separator 分隔符 * @return */ public static String getSplitText(List<String> list, String separator) { if (null != list && list.size() > 0) { return StringUtils.join(list, separator); } return ""; } /** * 通过table的条件SQL * * @param tableSql sys_user where name = '1212' * @return name = '1212' */ public static String getFilterSqlByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); if (arr != null && oConvertUtils.isNotEmpty(arr[1])) { return arr[1]; } } return ""; } /** * 通过table获取表名 * * @param tableSql sys_user where name = '1212' * @return sys_user */ public static String getTableNameByTableSql(String tableSql) { if(oConvertUtils.isEmpty(tableSql)){ return null; } if (tableSql.toLowerCase().indexOf(DataBaseConstant.SQL_WHERE) > 0) { String[] arr = tableSql.split(" (?i)where "); return arr[0].trim(); } else { return tableSql; } } /** * 判断两个数组是否存在交集 * @param set1 * @param arr2 * @return */ public static boolean hasIntersection(Set<String> set1, String[] arr2) { if (set1 == null) { return false; } if(set1.size()>0){ for (String str : arr2) { if (set1.contains(str)) { return true; } } } return false; } /** * 输出info日志,会捕获异常,防止因为日志问题导致程序异常 * * @param msg * @param objects */ public static void logInfo(String msg, Object... objects) { try { log.info(msg, objects); } catch (Exception e) { log.warn("{} —— {}", msg, e.getMessage()); } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DateRangeUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DateRangeUtils.java
package org.jeecg.common.util; import cn.hutool.core.date.DateUtil; import org.jeecg.common.constant.enums.DateRangeEnum; import java.util.Calendar; import java.util.Date; /** * 日期范围工具类 * * @author scott * @date 20230801 */ public class DateRangeUtils { /** * 根据日期范围枚举获取日期范围 * * @param rangeEnum * @return Date[] */ public static Date[] getDateRangeByEnum(DateRangeEnum rangeEnum) { if (rangeEnum == null) { return null; } Date[] ranges = new Date[2]; switch (rangeEnum) { case TODAY: ranges[0] = getTodayStartTime(); ranges[1] = getTodayEndTime(); break; case YESTERDAY: ranges[0] = getYesterdayStartTime(); ranges[1] = getYesterdayEndTime(); break; case TOMORROW: ranges[0] = getTomorrowStartTime(); ranges[1] = getTomorrowEndTime(); break; case THIS_WEEK: ranges[0] = getThisWeekStartDay(); ranges[1] = getThisWeekEndDay(); break; case LAST_WEEK: ranges[0] = getLastWeekStartDay(); ranges[1] = getLastWeekEndDay(); break; case NEXT_WEEK: ranges[0] = getNextWeekStartDay(); ranges[1] = getNextWeekEndDay(); break; case LAST_7_DAYS: ranges[0] = getLast7DaysStartTime(); ranges[1] = getLast7DaysEndTime(); break; case THIS_MONTH: ranges[0] = getThisMonthStartDay(); ranges[1] = getThisMonthEndDay(); break; case LAST_MONTH: ranges[0] = getLastMonthStartDay(); ranges[1] = getLastMonthEndDay(); break; case NEXT_MONTH: ranges[0] = getNextMonthStartDay(); ranges[1] = getNextMonthEndDay(); break; default: return null; } return ranges; } /** * 获得下月第一天 周日 00:00:00 */ public static Date getNextMonthStartDay() { return DateUtil.beginOfMonth(DateUtil.nextMonth()); } /** * 获得下月最后一天 23:59:59 */ public static Date getNextMonthEndDay() { return DateUtil.endOfMonth(DateUtil.nextMonth()); } /** * 获得本月第一天 周日 00:00:00 */ public static Date getThisMonthStartDay() { return DateUtil.beginOfMonth(DateUtil.date()); } /** * 获得本月最后一天 23:59:59 */ public static Date getThisMonthEndDay() { return DateUtil.endOfMonth(DateUtil.date()); } /** * 获得上月第一天 周日 00:00:00 */ public static Date getLastMonthStartDay() { return DateUtil.beginOfMonth(DateUtil.lastMonth()); } /** * 获得上月最后一天 23:59:59 */ public static Date getLastMonthEndDay() { return DateUtil.endOfMonth(DateUtil.lastMonth()); } /** * 获得上周第一天 周一 00:00:00 */ public static Date getLastWeekStartDay() { return DateUtil.beginOfWeek(DateUtil.lastWeek()); } /** * 获得上周最后一天 周日 23:59:59 */ public static Date getLastWeekEndDay() { return DateUtil.endOfWeek(DateUtil.lastWeek()); } /** * 获得本周第一天 周一 00:00:00 */ public static Date getThisWeekStartDay() { Date today = new Date(); return DateUtil.beginOfWeek(today); } /** * 获得本周最后一天 周日 23:59:59 */ public static Date getThisWeekEndDay() { Date today = new Date(); return DateUtil.endOfWeek(today); } /** * 获得下周第一天 周一 00:00:00 */ public static Date getNextWeekStartDay() { return DateUtil.beginOfWeek(DateUtil.nextWeek()); } /** * 获得下周最后一天 周日 23:59:59 */ public static Date getNextWeekEndDay() { return DateUtil.endOfWeek(DateUtil.nextWeek()); } /** * 过去七天开始时间(不含今天) * * @return */ public static Date getLast7DaysStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -7); return DateUtil.beginOfDay(calendar.getTime()); } /** * 过去七天结束时间(不含今天) * * @return */ public static Date getLast7DaysEndTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(getLast7DaysStartTime()); calendar.add(Calendar.DATE, 6); return DateUtil.endOfDay(calendar.getTime()); } /** * 昨天开始时间 * * @return */ public static Date getYesterdayStartTime() { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -1); return DateUtil.beginOfDay(calendar.getTime()); } /** * 昨天结束时间 * * @return */ public static Date getYesterdayEndTime() { return DateUtil.endOfDay(getYesterdayStartTime()); } /** * 明天开始时间 * * @return */ public static Date getTomorrowStartTime() { return DateUtil.beginOfDay(DateUtil.tomorrow()); } /** * 明天结束时间 * * @return */ public static Date getTomorrowEndTime() { return DateUtil.endOfDay(DateUtil.tomorrow()); } /** * 今天开始时间 * * @return */ public static Date getTodayStartTime() { return DateUtil.beginOfDay(new Date()); } /** * 今天结束时间 * * @return */ public static Date getTodayEndTime() { return DateUtil.endOfDay(new Date()); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/BrowserUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/BrowserUtils.java
package org.jeecg.common.util; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.servlet.http.HttpServletRequest; /** * * @Author 张代浩 * */ public class BrowserUtils { /** * 判断是否是IE * @param request * @return */ public static boolean isIe(HttpServletRequest request) { return (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request .getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0) ? true : false; } /** * 获取IE版本 * * @param request * @return */ public static Double getIeVersion(HttpServletRequest request) { Double version = 0.0; if (getBrowserType(request, IE11)) { version = 11.0; } else if (getBrowserType(request, IE10)) { version = 10.0; } else if (getBrowserType(request, IE9)) { version = 9.0; } else if (getBrowserType(request, IE8)) { version = 8.0; } else if (getBrowserType(request, IE7)) { version = 7.0; } else if (getBrowserType(request, IE6)) { version = 6.0; } return version; } /** * 获取浏览器类型 * * @param request * @return */ public static BrowserType getBrowserType(HttpServletRequest request) { BrowserType browserType = null; if (getBrowserType(request, IE11)) { browserType = BrowserType.IE11; } if (getBrowserType(request, IE10)) { browserType = BrowserType.IE10; } if (getBrowserType(request, IE9)) { browserType = BrowserType.IE9; } if (getBrowserType(request, IE8)) { browserType = BrowserType.IE8; } if (getBrowserType(request, IE7)) { browserType = BrowserType.IE7; } if (getBrowserType(request, IE6)) { browserType = BrowserType.IE6; } if (getBrowserType(request, FIREFOX)) { browserType = BrowserType.Firefox; } if (getBrowserType(request, SAFARI)) { browserType = BrowserType.Safari; } if (getBrowserType(request, CHROME)) { browserType = BrowserType.Chrome; } if (getBrowserType(request, OPERA)) { browserType = BrowserType.Opera; } if (getBrowserType(request, CAMINO)) { browserType = BrowserType.Camino; } return browserType; } private static boolean getBrowserType(HttpServletRequest request, String brosertype) { return request.getHeader("USER-AGENT").toLowerCase() .indexOf(brosertype) > 0 ? true : false; } private final static String IE11 = "rv:11.0"; private final static String IE10 = "MSIE 10.0"; private final static String IE9 = "MSIE 9.0"; private final static String IE8 = "MSIE 8.0"; private final static String IE7 = "MSIE 7.0"; private final static String IE6 = "MSIE 6.0"; private final static String MAXTHON = "Maxthon"; private final static String QQ = "QQBrowser"; private final static String GREEN = "GreenBrowser"; private final static String SE360 = "360SE"; private final static String FIREFOX = "Firefox"; private final static String OPERA = "Opera"; private final static String CHROME = "Chrome"; private final static String SAFARI = "Safari"; private final static String OTHER = "其它"; private final static String CAMINO = "Camino"; public static String checkBrowse(HttpServletRequest request) { String userAgent = request.getHeader("USER-AGENT"); if (regex(OPERA, userAgent)) { return OPERA; } if (regex(CHROME, userAgent)) { return CHROME; } if (regex(FIREFOX, userAgent)) { return FIREFOX; } if (regex(SAFARI, userAgent)) { return SAFARI; } if (regex(SE360, userAgent)) { return SE360; } if (regex(GREEN, userAgent)) { return GREEN; } if (regex(QQ, userAgent)) { return QQ; } if (regex(MAXTHON, userAgent)) { return MAXTHON; } if (regex(IE11, userAgent)) { return IE11; } if (regex(IE10, userAgent)) { return IE10; } if (regex(IE9, userAgent)) { return IE9; } if (regex(IE8, userAgent)) { return IE8; } if (regex(IE7, userAgent)) { return IE7; } if (regex(IE6, userAgent)) { return IE6; } return OTHER; } public static boolean regex(String regex, String str) { Pattern p = Pattern.compile(regex, Pattern.MULTILINE); Matcher m = p.matcher(str); return m.find(); } private static Map<String, String> langMap = new HashMap<String, String>(); private final static String ZH = "zh"; private final static String ZH_CN = "zh-cn"; private final static String EN = "en"; private final static String EN_US = "en"; static { langMap.put(ZH, ZH_CN); langMap.put(EN, EN_US); } public static String getBrowserLanguage(HttpServletRequest request) { String browserLang = request.getLocale().getLanguage(); String browserLangCode = (String)langMap.get(browserLang); if(browserLangCode == null) { browserLangCode = EN_US; } return browserLangCode; } /** 判断请求是否来自电脑端 */ public static boolean isDesktop(HttpServletRequest request) { return !isMobile(request); } /** 判断请求是否来自移动端 */ public static boolean isMobile(HttpServletRequest request) { String ua = request.getHeader("User-Agent").toLowerCase(); String type = "(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone)"; Pattern pattern = Pattern.compile(type); return pattern.matcher(ua).find(); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/TokenUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/TokenUtils.java
package org.jeecg.common.util; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.api.CommonAPI; import org.jeecg.common.constant.CacheConstant; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.TenantConstant; import org.jeecg.common.desensitization.util.SensitiveInfoUtil; import org.jeecg.common.exception.JeecgBoot401Exception; import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.vo.LoginUser; import jakarta.servlet.http.HttpServletRequest; /** * @Author scott * @Date 2019/9/23 14:12 * @Description: 编程校验token有效性 */ @Slf4j public class TokenUtils { /** * 获取 request 里传递的 token * * @param request * @return */ public static String getTokenByRequest(HttpServletRequest request) { if (request == null) { return null; } String token = request.getParameter("token"); if (token == null) { token = request.getHeader("X-Access-Token"); } return token; } /** * 获取 request 里传递的 token * @return */ public static String getTokenByRequest() { String token = null; try { HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); token = TokenUtils.getTokenByRequest(request); } catch (Exception e) { //e.printStackTrace(); } return token; } /** * 获取 request 里传递的 tenantId (租户ID) * * @param request * @return */ public static String getTenantIdByRequest(HttpServletRequest request) { String tenantId = request.getParameter(TenantConstant.TENANT_ID); if (tenantId == null) { tenantId = oConvertUtils.getString(request.getHeader(CommonConstant.TENANT_ID)); } if (oConvertUtils.isNotEmpty(tenantId) && "undefined".equals(tenantId)) { return null; } return tenantId; } /** * 获取 request 里传递的 lowAppId (低代码应用ID) * * @param request * @return */ public static String getLowAppIdByRequest(HttpServletRequest request) { String lowAppId = request.getParameter(TenantConstant.FIELD_LOW_APP_ID); if (lowAppId == null) { lowAppId = oConvertUtils.getString(request.getHeader(TenantConstant.X_LOW_APP_ID)); } return lowAppId; } /** * 验证Token */ public static boolean verifyToken(HttpServletRequest request, CommonAPI commonApi, RedisUtil redisUtil) { log.debug(" -- url --" + request.getRequestURL()); String token = getTokenByRequest(request); return TokenUtils.verifyToken(token, commonApi, redisUtil); } /** * 验证Token */ public static boolean verifyToken(String token, CommonAPI commonApi, RedisUtil redisUtil) { if (StringUtils.isBlank(token)) { throw new JeecgBoot401Exception("token不能为空!"); } // 解密获得username,用于和数据库进行对比 String username = JwtUtil.getUsername(token); if (username == null) { throw new JeecgBoot401Exception("token非法无效!"); } // 查询用户信息 LoginUser user = TokenUtils.getLoginUser(username, commonApi, redisUtil); //LoginUser user = commonApi.getUserByName(username); if (user == null) { throw new JeecgBoot401Exception("用户不存在!"); } // 判断用户状态 if (user.getStatus() != 1) { throw new JeecgBoot401Exception("账号已被锁定,请联系管理员!"); } // 校验token是否超时失效 & 或者账号密码是否错误 if (!jwtTokenRefresh(token, username, user.getPassword(), redisUtil)) { // 用户登录Token过期提示信息 String userLoginTokenErrorMsg = oConvertUtils.getString(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN_ERROR_MSG + token)); throw new JeecgBoot401Exception(oConvertUtils.isEmpty(userLoginTokenErrorMsg)? CommonConstant.TOKEN_IS_INVALID_MSG: userLoginTokenErrorMsg); } return true; } /** * 刷新token(保证用户在线操作不掉线) * @param token * @param userName * @param passWord * @param redisUtil * @return */ private static boolean jwtTokenRefresh(String token, String userName, String passWord, RedisUtil redisUtil) { String cacheToken = oConvertUtils.getString(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token)); if (oConvertUtils.isNotEmpty(cacheToken)) { // 校验token有效性 if (!JwtUtil.verify(cacheToken, userName, passWord)) { // 从token中解析客户端类型,保持续期时使用相同的客户端类型 String clientType = JwtUtil.getClientType(token); String newAuthorization = JwtUtil.sign(userName, passWord, clientType); // 根据客户端类型设置对应的缓存有效时间 long expireTime = CommonConstant.CLIENT_TYPE_APP.equalsIgnoreCase(clientType) ? JwtUtil.APP_EXPIRE_TIME * 2 / 1000 : JwtUtil.EXPIRE_TIME * 2 / 1000; redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization); redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, expireTime); } return true; } return false; } /** * 获取登录用户 * * @param commonApi * @param username * @return */ public static LoginUser getLoginUser(String username, CommonAPI commonApi, RedisUtil redisUtil) { LoginUser loginUser = null; String loginUserKey = CacheConstant.SYS_USERS_CACHE + "::" + username; //【重要】此处通过redis原生获取缓存用户,是为了解决微服务下system服务挂了,其他服务互调不通问题--- if (redisUtil.hasKey(loginUserKey)) { try { loginUser = (LoginUser) redisUtil.get(loginUserKey); //解密用户 SensitiveInfoUtil.handlerObject(loginUser, false); } catch (IllegalAccessException e) { e.printStackTrace(); } } else { // 查询用户信息 loginUser = commonApi.getUserByName(username); } return loginUser; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DateUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DateUtils.java
package org.jeecg.common.util; import org.jeecg.common.constant.SymbolConstant; import org.springframework.util.StringUtils; import java.beans.PropertyEditorSupport; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * 类描述:时间操作定义类 * * @Author: 张代浩 * @Date:2012-12-8 12:15:03 * @Version 1.0 */ public class DateUtils extends PropertyEditorSupport { public static ThreadLocal<SimpleDateFormat> date_sdf = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); } }; public static ThreadLocal<SimpleDateFormat> yyyyMMdd = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMdd"); } }; public static ThreadLocal<SimpleDateFormat> date_sdf_wz = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy年MM月dd日"); } }; public static ThreadLocal<SimpleDateFormat> time_sdf = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm"); } }; public static ThreadLocal<SimpleDateFormat> yyyymmddhhmmss = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMddHHmmss"); } }; public static ThreadLocal<SimpleDateFormat> short_time_sdf = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("HH:mm"); } }; public static ThreadLocal<SimpleDateFormat> datetimeFormat = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; /** * 以毫秒表示的时间 */ private static final long DAY_IN_MILLIS = 24 * 3600 * 1000; private static final long HOUR_IN_MILLIS = 3600 * 1000; private static final long MINUTE_IN_MILLIS = 60 * 1000; private static final long SECOND_IN_MILLIS = 1000; /** * 指定模式的时间格式 * @param pattern * @return */ private static SimpleDateFormat getSdFormat(String pattern) { return new SimpleDateFormat(pattern); } /** * 当前日历,这里用中国时间表示 * * @return 以当地时区表示的系统当前日历 */ public static Calendar getCalendar() { return Calendar.getInstance(); } /** * 指定毫秒数表示的日历 * * @param millis 毫秒数 * @return 指定毫秒数表示的日历 */ public static Calendar getCalendar(long millis) { Calendar cal = Calendar.getInstance(); // --------------------cal.setTimeInMillis(millis); cal.setTime(new Date(millis)); return cal; } // //////////////////////////////////////////////////////////////////////////// // getDate // 各种方式获取的Date // //////////////////////////////////////////////////////////////////////////// /** * 当前日期 * * @return 系统当前时间 */ public static Date getDate() { return new Date(); } /** * 当前日期 * * @return 系统当前日期(不带时分秒) */ public static LocalDate getLocalDate() { LocalDate today = LocalDate.now(); return today; } /** * 指定毫秒数表示的日期 * * @param millis 毫秒数 * @return 指定毫秒数表示的日期 */ public static Date getDate(long millis) { return new Date(millis); } /** * 时间戳转换为字符串 * * @param time * @return */ public static String timestamptoStr(Timestamp time) { Date date = null; if (null != time) { date = new Date(time.getTime()); } return date2Str(date_sdf.get()); } /** * 字符串转换时间戳 * * @param str * @return */ public static Timestamp str2Timestamp(String str) { Date date = str2Date(str, date_sdf.get()); return new Timestamp(date.getTime()); } /** * 字符串转换成日期 * * @param str * @param sdf * @return */ public static Date str2Date(String str, SimpleDateFormat sdf) { if (null == str || "".equals(str)) { return null; } Date date = null; try { date = sdf.parse(str); return date; } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 日期转换为字符串 * * @param dateSdf 日期格式 * @return 字符串 */ public static String date2Str(SimpleDateFormat dateSdf) { synchronized (dateSdf) { Date date = getDate(); if (null == date) { return null; } return dateSdf.format(date); } } /** * 格式化时间 * * @param date * @param format * @return */ public static String dateformat(String date, String format) { SimpleDateFormat sformat = new SimpleDateFormat(format); Date nowDate = null; try { nowDate = sformat.parse(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sformat.format(nowDate); } /** * 日期转换为字符串 * * @param date 日期 * @param dateSdf 日期格式 * @return 字符串 */ public static String date2Str(Date date, SimpleDateFormat dateSdf) { synchronized (dateSdf) { if (null == date) { return null; } return dateSdf.format(date); } } /** * 日期转换为字符串 * * @param format 日期格式 * @return 字符串 */ public static String getDate(String format) { Date date = new Date(); if (null == date) { return null; } SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); } /** * 指定毫秒数的时间戳 * * @param millis 毫秒数 * @return 指定毫秒数的时间戳 */ public static Timestamp getTimestamp(long millis) { return new Timestamp(millis); } /** * 以字符形式表示的时间戳 * * @param time 毫秒数 * @return 以字符形式表示的时间戳 */ public static Timestamp getTimestamp(String time) { return new Timestamp(Long.parseLong(time)); } /** * 系统当前的时间戳 * * @return 系统当前的时间戳 */ public static Timestamp getTimestamp() { return new Timestamp(System.currentTimeMillis()); } /** * 当前时间,格式 yyyy-MM-dd HH:mm:ss * * @return 当前时间的标准形式字符串 */ public static String now() { return datetimeFormat.get().format(getCalendar().getTime()); } /** * 指定日期的时间戳 * * @param date 指定日期 * @return 指定日期的时间戳 */ public static Timestamp getTimestamp(Date date) { return new Timestamp(date.getTime()); } /** * 指定日历的时间戳 * * @param cal 指定日历 * @return 指定日历的时间戳 */ public static Timestamp getCalendarTimestamp(Calendar cal) { // ---------------------return new Timestamp(cal.getTimeInMillis()); return new Timestamp(cal.getTime().getTime()); } public static Timestamp gettimestamp() { Date dt = new Date(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowTime = df.format(dt); java.sql.Timestamp buydate = java.sql.Timestamp.valueOf(nowTime); return buydate; } // //////////////////////////////////////////////////////////////////////////// // getMillis // 各种方式获取的Millis // //////////////////////////////////////////////////////////////////////////// /** * 系统时间的毫秒数 * * @return 系统时间的毫秒数 */ public static long getMillis() { return System.currentTimeMillis(); } /** * 指定日历的毫秒数 * * @param cal 指定日历 * @return 指定日历的毫秒数 */ public static long getMillis(Calendar cal) { // --------------------return cal.getTimeInMillis(); return cal.getTime().getTime(); } /** * 指定日期的毫秒数 * * @param date 指定日期 * @return 指定日期的毫秒数 */ public static long getMillis(Date date) { return date.getTime(); } /** * 指定时间戳的毫秒数 * * @param ts 指定时间戳 * @return 指定时间戳的毫秒数 */ public static long getMillis(Timestamp ts) { return ts.getTime(); } // //////////////////////////////////////////////////////////////////////////// // formatDate // 将日期按照一定的格式转化为字符串 // //////////////////////////////////////////////////////////////////////////// /** * 默认方式表示的系统当前日期,具体格式:年-月-日 * * @return 默认日期按“年-月-日“格式显示 */ public static String formatDate() { return date_sdf.get().format(getCalendar().getTime()); } /** * 默认方式表示的系统当前日期,具体格式:yyyy-MM-dd HH:mm:ss * * @return 默认日期按“yyyy-MM-dd HH:mm:ss“格式显示 */ public static String formatDateTime() { return datetimeFormat.get().format(getCalendar().getTime()); } /** * 获取时间字符串 */ public static String getDataString(SimpleDateFormat formatstr) { synchronized (formatstr) { return formatstr.format(getCalendar().getTime()); } } /** * 指定日期的默认显示,具体格式:年-月-日 * * @param cal 指定的日期 * @return 指定日期按“年-月-日“格式显示 */ public static String formatDate(Calendar cal) { return date_sdf.get().format(cal.getTime()); } /** * 指定日期的默认显示,具体格式:年-月-日 * * @param date 指定的日期 * @return 指定日期按“年-月-日“格式显示 */ public static String formatDate(Date date) { return date_sdf.get().format(date); } /** * 指定毫秒数表示日期的默认显示,具体格式:年-月-日 * * @param millis 指定的毫秒数 * @return 指定毫秒数表示日期按“年-月-日“格式显示 */ public static String formatDate(long millis) { return date_sdf.get().format(new Date(millis)); } /** * 默认日期按指定格式显示 * * @param pattern 指定的格式 * @return 默认日期按指定格式显示 */ public static String formatDate(String pattern) { return getSdFormat(pattern).format(getCalendar().getTime()); } /** * 指定日期按指定格式显示 * * @param cal 指定的日期 * @param pattern 指定的格式 * @return 指定日期按指定格式显示 */ public static String formatDate(Calendar cal, String pattern) { return getSdFormat(pattern).format(cal.getTime()); } /** * 指定日期按指定格式显示 * * @param date 指定的日期 * @param pattern 指定的格式 * @return 指定日期按指定格式显示 */ public static String formatDate(Date date, String pattern) { return getSdFormat(pattern).format(date); } // //////////////////////////////////////////////////////////////////////////// // formatTime // 将日期按照一定的格式转化为字符串 // //////////////////////////////////////////////////////////////////////////// /** * 默认方式表示的系统当前日期,具体格式:年-月-日 时:分 * * @return 默认日期按“年-月-日 时:分“格式显示 */ public static String formatTime() { return time_sdf.get().format(getCalendar().getTime()); } /** * 指定毫秒数表示日期的默认显示,具体格式:年-月-日 时:分 * * @param millis 指定的毫秒数 * @return 指定毫秒数表示日期按“年-月-日 时:分“格式显示 */ public static String formatTime(long millis) { return time_sdf.get().format(new Date(millis)); } /** * 指定日期的默认显示,具体格式:年-月-日 时:分 * * @param cal 指定的日期 * @return 指定日期按“年-月-日 时:分“格式显示 */ public static String formatTime(Calendar cal) { return time_sdf.get().format(cal.getTime()); } /** * 指定日期的默认显示,具体格式:年-月-日 时:分 * * @param date 指定的日期 * @return 指定日期按“年-月-日 时:分“格式显示 */ public static String formatTime(Date date) { return time_sdf.get().format(date); } // //////////////////////////////////////////////////////////////////////////// // formatShortTime // 将日期按照一定的格式转化为字符串 // //////////////////////////////////////////////////////////////////////////// /** * 默认方式表示的系统当前日期,具体格式:时:分 * * @return 默认日期按“时:分“格式显示 */ public static String formatShortTime() { return short_time_sdf.get().format(getCalendar().getTime()); } /** * 指定毫秒数表示日期的默认显示,具体格式:时:分 * * @param millis 指定的毫秒数 * @return 指定毫秒数表示日期按“时:分“格式显示 */ public static String formatShortTime(long millis) { return short_time_sdf.get().format(new Date(millis)); } /** * 指定日期的默认显示,具体格式:时:分 * * @param cal 指定的日期 * @return 指定日期按“时:分“格式显示 */ public static String formatShortTime(Calendar cal) { return short_time_sdf.get().format(cal.getTime()); } /** * 指定日期的默认显示,具体格式:时:分 * * @param date 指定的日期 * @return 指定日期按“时:分“格式显示 */ public static String formatShortTime(Date date) { return short_time_sdf.get().format(date); } // //////////////////////////////////////////////////////////////////////////// // parseDate // parseCalendar // parseTimestamp // 将字符串按照一定的格式转化为日期或时间 // //////////////////////////////////////////////////////////////////////////// /** * 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间 * * @param src 将要转换的原始字符窜 * @param pattern 转换的匹配格式 * @return 如果转换成功则返回转换后的日期 * @throws ParseException */ public static Date parseDate(String src, String pattern) throws ParseException { return getSdFormat(pattern).parse(src); } /** * 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间 * * @param src 将要转换的原始字符窜 * @param pattern 转换的匹配格式 * @return 如果转换成功则返回转换后的日期 * @throws ParseException */ public static Calendar parseCalendar(String src, String pattern) throws ParseException { Date date = parseDate(src, pattern); Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } public static String formatAddDate(String src, String pattern, int amount) throws ParseException { Calendar cal; cal = parseCalendar(src, pattern); cal.add(Calendar.DATE, amount); return formatDate(cal); } /** * 根据指定的格式将字符串转换成Date 如输入:2003-11-19 11:20:20将按照这个转成时间 * * @param src 将要转换的原始字符窜 * @param pattern 转换的匹配格式 * @return 如果转换成功则返回转换后的时间戳 * @throws ParseException */ public static Timestamp parseTimestamp(String src, String pattern) throws ParseException { Date date = parseDate(src, pattern); return new Timestamp(date.getTime()); } // //////////////////////////////////////////////////////////////////////////// // dateDiff // 计算两个日期之间的差值 // //////////////////////////////////////////////////////////////////////////// /** * 计算两个时间之间的差值,根据标志的不同而不同 * * @param flag 计算标志,表示按照年/月/日/时/分/秒等计算 * @param calSrc 减数 * @param calDes 被减数 * @return 两个日期之间的差值 */ public static int dateDiff(char flag, Calendar calSrc, Calendar calDes) { long millisDiff = getMillis(calSrc) - getMillis(calDes); char year = 'y'; char day = 'd'; char hour = 'h'; char minute = 'm'; char second = 's'; if (flag == year) { return (calSrc.get(Calendar.YEAR) - calDes.get(Calendar.YEAR)); } if (flag == day) { return (int) (millisDiff / DAY_IN_MILLIS); } if (flag == hour) { return (int) (millisDiff / HOUR_IN_MILLIS); } if (flag == minute) { return (int) (millisDiff / MINUTE_IN_MILLIS); } if (flag == second) { return (int) (millisDiff / SECOND_IN_MILLIS); } return 0; } public static Long getCurrentTimestamp() { return Long.valueOf(DateUtils.yyyymmddhhmmss.get().format(new Date())); } /** * String类型 转换为Date, 如果参数长度为10 转换格式”yyyy-MM-dd“ 如果参数长度为19 转换格式”yyyy-MM-dd * HH:mm:ss“ * @param text String类型的时间值 */ @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.hasText(text)) { try { int length10 = 10; int length19 = 19; if (text.indexOf(SymbolConstant.COLON) == -1 && text.length() == length10) { setValue(DateUtils.date_sdf.get().parse(text)); } else if (text.indexOf(SymbolConstant.COLON) > 0 && text.length() == length19) { setValue(DateUtils.datetimeFormat.get().parse(text)); } else { throw new IllegalArgumentException("Could not parse date, date format is error "); } } catch (ParseException ex) { IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage()); iae.initCause(ex); throw iae; } } else { setValue(null); } } public static int getYear() { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(getDate()); return calendar.get(Calendar.YEAR); } /** * 将字符串转成时间 * @param str * @return */ public static Date parseDatetime(String str){ try { return datetimeFormat.get().parse(str); }catch (Exception e){ } return null; } /** * 判断两个时间是否是同一天 * * @param date1 * @param date2 * @return */ public static boolean isSameDay(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); boolean isSameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); boolean isSameMonth = isSameYear && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH); return isSameMonth && calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); } /** * 计算与当前日期的时间差 * * @param targetDate * @return */ public static long calculateTimeDifference(Date targetDate) { // 获取当前时间 LocalDateTime currentTime = LocalDateTime.now(); // 将java.util.Date转换为java.time.LocalDateTime LocalDateTime convertedTargetDate = targetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); // 计算时间差 Duration duration = Duration.between(currentTime, convertedTargetDate); // 获取时间差的毫秒数 long timeDifferenceInMillis = duration.toMillis(); return timeDifferenceInMillis; } /** * 计算与当前日期的日期天数差 * * @param targetDate * @return */ public static long calculateDaysDifference(Date targetDate) { // 获取当前日期 LocalDate currentDate = LocalDate.now(); // 将java.util.Date转换为java.time.LocalDate LocalDate convertedTargetDate = targetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // 计算日期差 long daysDifference = ChronoUnit.DAYS.between(currentDate, convertedTargetDate); return daysDifference; } /** * 判断两个时间是否是同一周 * * @param date1 * @param date2 * @return */ public static boolean isSameWeek(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); boolean isSameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); return isSameYear && calendar1.get(Calendar.WEEK_OF_YEAR) == calendar2.get(Calendar.WEEK_OF_YEAR); } /** * 判断两个时间是否是同一月 * * @param date1 * @param date2 * @return */ public static boolean isSameMonth(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); boolean isSameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); return isSameYear && calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH); } /** * 判断两个时间是否是同一年 * * @param date1 * @param date2 * @return */ public static boolean isSameYear(Date date1, Date date2) { if (date1 == null || date2 == null) { return false; } Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(date1); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(date2); return calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); } /** * 获取两个日期之间的所有日期列表,包含开始和结束日期 * * @param begin * @param end * @return */ public static List<Date> getDateRangeList(Date begin, Date end) { List<Date> dateList = new ArrayList<>(); if (begin == null || end == null) { return dateList; } // 清除时间部分,只比较日期 Calendar beginCal = Calendar.getInstance(); beginCal.setTime(begin); beginCal.set(Calendar.HOUR_OF_DAY, 0); beginCal.set(Calendar.MINUTE, 0); beginCal.set(Calendar.SECOND, 0); beginCal.set(Calendar.MILLISECOND, 0); Calendar endCal = Calendar.getInstance(); endCal.setTime(end); endCal.set(Calendar.HOUR_OF_DAY, 0); endCal.set(Calendar.MINUTE, 0); endCal.set(Calendar.SECOND, 0); endCal.set(Calendar.MILLISECOND, 0); if (endCal.before(beginCal)) { return dateList; } dateList.add(beginCal.getTime()); while (beginCal.before(endCal)) { beginCal.add(Calendar.DAY_OF_YEAR, 1); dateList.add(beginCal.getTime()); } return dateList; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MinioUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MinioUtil.java
package org.jeecg.common.util; import io.minio.*; import io.minio.http.Method; import lombok.extern.slf4j.Slf4j; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.util.filter.SsrfFileTypeFilter; import org.jeecg.common.util.filter.StrAttackFilter; import org.springframework.web.multipart.MultipartFile; import java.io.InputStream; import java.net.URLDecoder; /** * minio文件上传工具类 * @author: jeecg-boot */ @Slf4j public class MinioUtil { private static String minioUrl; private static String minioName; private static String minioPass; private static String bucketName; public static void setMinioUrl(String minioUrl) { MinioUtil.minioUrl = minioUrl; } public static void setMinioName(String minioName) { MinioUtil.minioName = minioName; } public static void setMinioPass(String minioPass) { MinioUtil.minioPass = minioPass; } public static void setBucketName(String bucketName) { MinioUtil.bucketName = bucketName; } public static String getMinioUrl() { return minioUrl; } public static String getBucketName() { return bucketName; } private static MinioClient minioClient = null; /** * 上传文件 * @param file * @return */ public static String upload(MultipartFile file, String bizPath, String customBucket) throws Exception { String fileUrl = ""; // 业务路径过滤,防止攻击 bizPath = StrAttackFilter.filter(bizPath); // 文件安全校验,防止上传漏洞文件 SsrfFileTypeFilter.checkUploadFileType(file, bizPath); String newBucket = bucketName; if(oConvertUtils.isNotEmpty(customBucket)){ newBucket = customBucket; } try { initMinio(minioUrl, minioName,minioPass); // 检查存储桶是否已经存在 if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) { log.info("Bucket already exists."); } else { // 创建一个名为ota的存储桶 minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build()); log.info("create a new bucket."); } InputStream stream = file.getInputStream(); // 获取文件名 String orgName = file.getOriginalFilename(); if("".equals(orgName)){ orgName=file.getName(); } orgName = CommonUtils.getFileName(orgName); String objectName = bizPath+"/" +( orgName.indexOf(".")==-1 ?orgName + "_" + System.currentTimeMillis() :orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf(".")) ); // 使用putObject上传一个本地文件到存储桶中。 if(objectName.startsWith(SymbolConstant.SINGLE_SLASH)){ objectName = objectName.substring(1); } PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName) .bucket(newBucket) .contentType("application/octet-stream") .stream(stream,stream.available(),-1).build(); minioClient.putObject(objectArgs); stream.close(); fileUrl = minioUrl+newBucket+"/"+objectName; }catch (Exception e){ log.error(e.getMessage(), e); } return fileUrl; } /** * 文件上传 * @param file * @param bizPath * @return */ public static String upload(MultipartFile file, String bizPath) throws Exception { return upload(file,bizPath,null); } /** * 获取文件流 * @param bucketName * @param objectName * @return */ public static InputStream getMinioFile(String bucketName,String objectName){ InputStream inputStream = null; try { initMinio(minioUrl, minioName, minioPass); GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName) .bucket(bucketName).build(); inputStream = minioClient.getObject(objectArgs); } catch (Exception e) { log.info("文件获取失败" + e.getMessage()); } return inputStream; } /** * 删除文件 * @param bucketName * @param objectName * @throws Exception */ public static void removeObject(String bucketName, String objectName) { try { initMinio(minioUrl, minioName,minioPass); RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName) .bucket(bucketName).build(); minioClient.removeObject(objectArgs); }catch (Exception e){ log.info("文件删除失败" + e.getMessage()); } } /** * 获取文件外链 * @param bucketName * @param objectName * @param expires * @return */ public static String getObjectUrl(String bucketName, String objectName, Integer expires) { initMinio(minioUrl, minioName,minioPass); try{ // 代码逻辑说明: 获取文件外链报错提示method不能为空,导致文件下载和预览失败---- GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName) .bucket(bucketName) .expiry(expires).method(Method.GET).build(); String url = minioClient.getPresignedObjectUrl(objectArgs); return URLDecoder.decode(url,"UTF-8"); }catch (Exception e){ log.info("文件路径获取失败" + e.getMessage()); } return null; } /** * 初始化客户端 * @param minioUrl * @param minioName * @param minioPass * @return */ private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) { if (minioClient == null) { try { minioClient = MinioClient.builder() .endpoint(minioUrl) .credentials(minioName, minioPass) .build(); } catch (Exception e) { e.printStackTrace(); } } return minioClient; } /** * 上传文件到minio * @param stream * @param relativePath * @return */ public static String upload(InputStream stream,String relativePath) throws Exception { initMinio(minioUrl, minioName,minioPass); if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) { log.info("Bucket already exists."); } else { // 创建一个名为ota的存储桶 minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build()); log.info("create a new bucket."); } PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath) .bucket(bucketName) .contentType("application/octet-stream") .stream(stream,stream.available(),-1).build(); minioClient.putObject(objectArgs); stream.close(); return minioUrl+bucketName+"/"+relativePath; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/Md5Util.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/Md5Util.java
package org.jeecg.common.util; import java.security.MessageDigest; /** * @Description: 加密工具 * @author: jeecg-boot */ public class Md5Util { private static final String[] HEXDIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; public static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++){ resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) { n += 256; } int d1 = n / 16; int d2 = n % 16; return HEXDIGITS[d1] + HEXDIGITS[d2]; } public static String md5Encode(String origin, String charsetname) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); if (charsetname == null || "".equals(charsetname)) { resultString = byteArrayToHexString(md.digest(resultString.getBytes())); } else { resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname))); } } catch (Exception exception) { } return resultString; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MyClassLoader.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/MyClassLoader.java
package org.jeecg.common.util; import org.jeecg.common.constant.SymbolConstant; /** * @Author 张代浩 */ public class MyClassLoader extends ClassLoader { public static Class getClassByScn(String className) { Class myclass = null; try { myclass = Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(className+" not found!"); } return myclass; } /** * 获得类的全名,包括包名 * @param object * @return */ public static String getPackPath(Object object) { // 检查用户传入的参数是否为空 if (object == null) { throw new java.lang.IllegalArgumentException("参数不能为空!"); } // 获得类的全名,包括包名 String clsName = object.getClass().getName(); return clsName; } public static String getAppPath(Class cls) { // 检查用户传入的参数是否为空 if (cls == null) { throw new java.lang.IllegalArgumentException("参数不能为空!"); } ClassLoader loader = cls.getClassLoader(); // 获得类的全名,包括包名 String clsName = cls.getName() + ".class"; // 获得传入参数所在的包 Package pack = cls.getPackage(); String path = ""; // 如果不是匿名包,将包名转化为路径 if (pack != null) { String packName = pack.getName(); String javaSpot="java."; String javaxSpot="javax."; // 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库 if (packName.startsWith(javaSpot) || packName.startsWith(javaxSpot)) { throw new java.lang.IllegalArgumentException("不要传送系统类!"); } // 在类的名称中,去掉包名的部分,获得类的文件名 clsName = clsName.substring(packName.length() + 1); // 判定包名是否是简单包名,如果是,则直接将包名转换为路径, if (packName.indexOf(SymbolConstant.SPOT) < 0) { path = packName + "/"; } else { // 否则按照包名的组成部分,将包名转换为路径 int start = 0, end = 0; end = packName.indexOf("."); StringBuilder pathBuilder = new StringBuilder(); while (end != -1) { pathBuilder.append(packName, start, end).append("/"); start = end + 1; end = packName.indexOf(".", start); } if(oConvertUtils.isNotEmpty(pathBuilder.toString())){ path = pathBuilder.toString(); } path = path + packName.substring(start) + "/"; } } // 调用ClassLoader的getResource方法,传入包含路径信息的类文件名 java.net.URL url = loader.getResource(path + clsName); // 从URL对象中获取路径信息 String realPath = url.getPath(); // 去掉路径信息中的协议名"file:" int pos = realPath.indexOf("file:"); if (pos > -1) { realPath = realPath.substring(pos + 5); } // 去掉路径信息最后包含类文件信息的部分,得到类所在的路径 pos = realPath.indexOf(path + clsName); realPath = realPath.substring(0, pos - 1); // 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名 if (realPath.endsWith(SymbolConstant.EXCLAMATORY_MARK)) { realPath = realPath.substring(0, realPath.lastIndexOf("/")); } /*------------------------------------------------------------ ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径 中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要 的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的 中文及空格路径 -------------------------------------------------------------*/ try { realPath = java.net.URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } return realPath; }// getAppPath定义结束 }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/SpringContextUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/SpringContextUtils.java
package org.jeecg.common.util; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.ServiceNameConstants; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; /** * @Description: spring上下文工具类 * @author: jeecg-boot */ @Lazy(false) @Component public class SpringContextUtils implements ApplicationContextAware { /** * 上下文对象实例 */ private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtils.applicationContext = applicationContext; } /** * 获取applicationContext * * @return */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取HttpServletRequest */ public static HttpServletRequest getHttpServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } /** * 获取HttpServletResponse */ public static HttpServletResponse getHttpServletResponse() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); } /** * 获取项目根路径 basePath */ public static String getDomain(){ HttpServletRequest request = getHttpServletRequest(); StringBuffer url = request.getRequestURL(); //1.微服务情况下,获取gateway的basePath String basePath = request.getHeader(ServiceNameConstants.X_GATEWAY_BASE_PATH); if(oConvertUtils.isNotEmpty(basePath)){ return basePath; }else{ String domain = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); //2.【兼容】SSL认证之后,request.getScheme()获取不到https的问题 // https://blog.csdn.net/weixin_34376986/article/details/89767950 String scheme = request.getHeader(CommonConstant.X_FORWARDED_SCHEME); if(scheme!=null && !request.getScheme().equals(scheme)){ domain = domain.replace(request.getScheme(),scheme); } return domain; } } public static String getOrigin(){ HttpServletRequest request = getHttpServletRequest(); return request.getHeader("Origin"); } /** * 通过name获取 Bean. * * @param name * @return */ public static Object getBean(String name) { return getApplicationContext().getBean(name); } /** * 通过class获取Bean. * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } /** * 通过name,以及Clazz返回指定的Bean * * @param name * @param clazz * @param <T> * @return */ public static <T> T getBean(String name, Class<T> clazz) { return getApplicationContext().getBean(name, clazz); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/FillRuleUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/FillRuleUtil.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.common.handler.IFillRuleHandler; import org.jeecg.common.system.query.QueryGenerator; /** * 规则值自动生成工具类 * * @author qinfeng * @举例: 自动生成订单号;自动生成当前日期 */ @Slf4j public class FillRuleUtil { /** * @param ruleCode ruleCode * @return */ @SuppressWarnings("unchecked") public static Object executeRule(String ruleCode, JSONObject formData) { if (!StringUtils.isEmpty(ruleCode)) { try { // 获取 Service ServiceImpl impl = (ServiceImpl) SpringContextUtils.getBean("sysFillRuleServiceImpl"); // 根据 ruleCode 查询出实体 QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("rule_code", ruleCode); JSONObject entity = JSON.parseObject(JSON.toJSONString(impl.getOne(queryWrapper))); if (entity == null) { log.warn("填值规则:" + ruleCode + " 不存在"); return null; } // 获取必要的参数 String ruleClass = entity.getString("ruleClass"); JSONObject params = entity.getJSONObject("ruleParams"); if (params == null) { params = new JSONObject(); } HttpServletRequest request = SpringContextUtils.getHttpServletRequest(); // 解析 params 中的变量 // 优先级:queryString > 系统变量 > 默认值 for (String key : params.keySet()) { // 1. 判断 queryString 中是否有该参数,如果有就优先取值 //noinspection ConstantValue if (request != null) { String parameter = request.getParameter(key); if (oConvertUtils.isNotEmpty(parameter)) { params.put(key, parameter); continue; } } String value = params.getString(key); // 2. 用于替换 系统变量的值 #{sys_user_code} if (value != null && value.contains(SymbolConstant.SYS_VAR_PREFIX)) { value = QueryGenerator.getSqlRuleValue(value); params.put(key, value); } } if (formData == null) { formData = new JSONObject(); } // 通过反射执行配置的类里的方法 IFillRuleHandler ruleHandler = (IFillRuleHandler) Class.forName(ruleClass).newInstance(); return ruleHandler.execute(params, formData); } catch (Exception e) { e.printStackTrace(); } } return null; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/HTMLUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/HTMLUtils.java
package org.jeecg.common.util; import org.apache.commons.lang3.StringUtils; import org.commonmark.node.Node; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; import org.springframework.web.util.HtmlUtils; /** * HTML 工具类 * @author: jeecg-boot * @date: 2022/3/30 14:43 */ @SuppressWarnings("AlibabaClassNamingShouldBeCamel") public class HTMLUtils { /** * 获取HTML内的文本,不包含标签 * * @param html HTML 代码 */ public static String getInnerText(String html) { if (StringUtils.isNotBlank(html)) { //去掉 html 的标签 String content = html.replaceAll("</?[^>]+>", ""); // 将多个空格合并成一个空格 content = content.replaceAll("(&nbsp;)+", "&nbsp;"); // 反向转义字符 content = HtmlUtils.htmlUnescape(content); return content.trim(); } return ""; } /** * 将Markdown解析成Html * @param markdownContent * @return */ public static String parseMarkdown(String markdownContent) { /*PegDownProcessor pdp = new PegDownProcessor(); return pdp.markdownToHtml(markdownContent);*/ Parser parser = Parser.builder().build(); Node document = parser.parse(markdownContent); HtmlRenderer renderer = HtmlRenderer.builder().build(); return renderer.render(document); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/FileDownloadUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/FileDownloadUtils.java
package org.jeecg.common.util; import cn.hutool.core.io.IoUtil; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.util.filter.SsrfFileTypeFilter; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @program: file * @description: 文件下载 * @author: chenrui * @date: 2019-05-24 16:34 **/ @Slf4j public class FileDownloadUtils { /** * 单文件下载 * * @param response * @param storePath 下载文件储存地址 * @param fileName 文件名称 * @author: chenrui * @date: 2019/5/24 17:10 */ public static void downloadFile(HttpServletResponse response, String storePath, String fileName) { response.setCharacterEncoding("UTF-8"); File file = new File(storePath); if (!file.exists()) { throw new NullPointerException("Specified file not found"); } if (fileName == null || fileName.isEmpty()) { throw new NullPointerException("The file name can not null"); } // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下载文件能正常显示中文 try { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); } catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); } // 实现文件下载 byte[] buffer = new byte[1024]; try (FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis);) { OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } } catch (Exception e) { log.error(e.getMessage(), e); } } /** * 多文件下载 * * @param filesPath 下载文件集合 * @param zipFileName 多文件合称名 * @author: chenrui * @date: 2019/5/24 17:48 */ public static void downloadFileMulti(HttpServletResponse response, List<String> filesPath, String zipFileName) throws IOException { //设置压缩包的名字 String downloadName = zipFileName + ".zip"; response.setCharacterEncoding("UTF-8"); response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "UTF-8")); response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); log.info("开始压缩文件:" + filesPath); //设置压缩流:直接写入response,实现边压缩边下载 try (ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); DataOutputStream os = new DataOutputStream(zipOut);) { //设置压缩方法 zipOut.setMethod(ZipOutputStream.DEFLATED); for (String filePath : filesPath) { //循环将文件写入压缩流 File file = new File(filePath); if (file.exists()) { //添加ZipEntry,并ZipEntry中写入文件流也就是将文件压入zip文件的目录下 String fileName = file.getName(); zipOut.putNextEntry(new ZipEntry(fileName)); //格式输出流文件 InputStream is = Files.newInputStream(file.toPath()); byte[] b = new byte[1024]; int length; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } is.close(); zipOut.closeEntry(); } } } catch (IOException e) { log.error(e.getMessage(), e); throw new JeecgBootException(e); } } /** * 下载网络资源到磁盘 * * @param fileUrl * @param storePath * @author chenrui * @date 2024/1/19 10:09 */ public static String download2DiskFromNet(String fileUrl, String storePath) { try { URL url = new URL(fileUrl); URLConnection conn = url.openConnection(); // 设置超时间为3秒 conn.setConnectTimeout(3 * 1000); // 防止屏蔽程序 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 确保目录存在 File file = ensureDestFileDir(storePath); try (InputStream inStream = conn.getInputStream(); FileOutputStream fs = new FileOutputStream(file);) { int byteread; byte[] buffer = new byte[1204]; while ((byteread = inStream.read(buffer)) != -1) { fs.write(buffer, 0, byteread); } return storePath; } catch (IOException e) { log.error(e.getMessage(), e); throw new JeecgBootException(e); } } catch (IOException e) { log.error(e.getMessage(), e); throw new JeecgBootException(e); } } /** * 获取不重名的文件 * * @param file * @return * @author chenrui * @date 2017年5月24日下午6:29:13 * @version v0.0.1 */ public static File getUniqueFile(final File file) { if (!file.exists()) { return file; } File tmpFile = new File(file.getAbsolutePath()); File parentDir = tmpFile.getParentFile(); int count = 1; String extension = FilenameUtils.getExtension(tmpFile.getName()); String baseName = FilenameUtils.getBaseName(tmpFile.getName()); do { tmpFile = new File(parentDir, baseName + "(" + count++ + ")." + extension); } while (tmpFile.exists()); return tmpFile; } /** * 确保输出文件目录 * * @param destFilePath * @return * @author: chenrui * @date: 2019-05-21 16:49 */ private static File ensureDestFileDir(String destFilePath) { File destFile = new File(destFilePath); FileDownloadUtils.checkDirAndCreate(destFile.getParentFile()); return destFile; } /** * 验证文件夹存在且创建目录 * * @param dir * @author chenrui * @date 2017年5月24日下午6:29:24 * @version v0.0.1 */ public static void checkDirAndCreate(File dir) { if (!dir.exists()) { dir.mkdirs(); } } /** * 下载单个文件到ZIP流 * 核心功能:获取文件流,写入ZIP条目 * @param fileUrl 文件URL(可以是HTTP URL或本地路径) * @param fileName ZIP内的文件名 * @param zous ZIP输出流 */ public static void downLoadSingleFile(String fileUrl, String fileName, String uploadUrl,ZipArchiveOutputStream zous) { InputStream inputStream = null; try { // 创建ZIP条目:每个文件在ZIP中都是一个独立条目 ZipArchiveEntry entry = new ZipArchiveEntry(fileName); zous.putArchiveEntry(entry); // 获取文件输入流:区分普通文件和快捷方式 if (fileUrl.endsWith(".url")) { // 处理快捷方式:生成.url文件内容 inputStream = FileDownloadUtils.createInternetShortcut(fileName, fileUrl, ""); } else { // 普通文件下载:从URL或本地路径获取流 inputStream = getDownInputStream(fileUrl,uploadUrl); } if (inputStream != null) { // 将文件流写入ZIP IOUtils.copy(inputStream, zous); } // 关闭当前ZIP条目 zous.closeArchiveEntry(); } catch (IOException e) { log.error("文件下载失败: {}", e); } finally { // 确保输入流关闭 IoUtil.close(inputStream); } } /** * 获取下载文件输入流 * 功能:根据URL类型(HTTP或本地)获取文件流 * @param fileUrl 文件URL(支持HTTP和本地路径) * @return 文件输入流,失败返回null */ public static InputStream getDownInputStream(String fileUrl, String uploadUrl) { try { // 处理HTTP URL:通过网络下载 if (oConvertUtils.isNotEmpty(fileUrl) && fileUrl.startsWith(CommonConstant.STR_HTTP)) { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); // 连接超时5秒 connection.setReadTimeout(30000); // 读取超时30秒 return connection.getInputStream(); } else { // 处理本地文件:直接读取文件系统 String downloadFilePath = uploadUrl + File.separator + fileUrl; // 安全检查:防止下载危险文件类型 SsrfFileTypeFilter.checkDownloadFileType(downloadFilePath); return new BufferedInputStream(new FileInputStream(downloadFilePath)); } } catch (IOException e) { // 异常时返回null,上层会处理空流情况 return null; } } /** * 获取文件扩展名 * 功能:从文件名中提取扩展名 * @param fileName 文件名 * @return 文件扩展名(不含点),如"txt"、"png" */ public static String getFileExtension(String fileName) { int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); } /** * 创建快捷方式(.url文件内容) * 功能:生成Internet快捷方式文件内容 * @param name 快捷方式名称 * @param url 目标URL地址 * @param icon 图标路径(可选) * @return 包含.url文件内容的输入流 */ public static InputStream createInternetShortcut(String name, String url, String icon) { StringWriter sw = new StringWriter(); try { // 按照Windows快捷方式格式写入内容 sw.write("[InternetShortcut]\n"); sw.write("URL=" + url + "\n"); if (oConvertUtils.isNotEmpty(icon)) { sw.write("IconFile=" + icon + "\n"); } // 将字符串内容转换为输入流 return new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8)); } finally { IoUtil.close(sw); } } /** * 从URL中提取文件名 * 功能:从HTTP URL或本地路径中提取纯文件名 * @param fileUrl 文件URL * @return 文件名(不含路径) */ public static String getFileNameFromUrl(String fileUrl) { try { // 处理HTTP URL:从路径部分提取文件名 if (fileUrl.startsWith(CommonConstant.STR_HTTP)) { URL url = new URL(fileUrl); String path = url.getPath(); return path.substring(path.lastIndexOf('/') + 1); } // 处理本地文件路径:从文件路径提取文件名 return fileUrl.substring(fileUrl.lastIndexOf(File.separator) + 1); } catch (Exception e) { // 如果解析失败,使用时间戳作为文件名 return "file_" + System.currentTimeMillis(); } } /** * 生成ZIP中的文件名 * 功能:避免文件名冲突,为多个文件添加序号 * @param fileUrl 文件URL(用于提取原始文件名) * @param index 文件序号(从0开始) * @param total 文件总数 * @return 处理后的文件名(带序号) */ public static String generateFileName(String fileUrl, int index, int total) { // 从URL中提取原始文件名 String originalFileName = getFileNameFromUrl(fileUrl); // 如果只有一个文件,直接使用原始文件名 if (total == 1) { return originalFileName; } // 多个文件时,使用序号+原始文件名 String extension = getFileExtension(originalFileName); String nameWithoutExtension = originalFileName.replace("." + extension, ""); return String.format("%s_%d.%s", nameWithoutExtension, index + 1, extension); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ReflectHelper.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ReflectHelper.java
package org.jeecg.common.util; import com.baomidou.mybatisplus.annotation.TableField; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author 张代浩 * @desc 通过反射来动态调用get 和 set 方法 */ @Slf4j public class ReflectHelper { private Class cls; /** * 传过来的对象 */ private Object obj; /** * 存放get方法 */ private Hashtable<String, Method> getMethods = null; /** * 存放set方法 */ private Hashtable<String, Method> setMethods = null; /** * 定义构造方法 -- 一般来说是个pojo * * @param o 目标对象 */ public ReflectHelper(Object o) { obj = o; initMethods(); } /** * @desc 初始化 */ public void initMethods() { getMethods = new Hashtable<String, Method>(); setMethods = new Hashtable<String, Method>(); cls = obj.getClass(); Method[] methods = cls.getMethods(); // 定义正则表达式,从方法中过滤出getter / setter 函数. String gs = "get(\\w+)"; Pattern getM = Pattern.compile(gs); String ss = "set(\\w+)"; Pattern setM = Pattern.compile(ss); // 把方法中的"set" 或者 "get" 去掉 String rapl = "$1"; String param; for (int i = 0; i < methods.length; ++i) { Method m = methods[i]; String methodName = m.getName(); if (Pattern.matches(gs, methodName)) { param = getM.matcher(methodName).replaceAll(rapl).toLowerCase(); getMethods.put(param, m); } else if (Pattern.matches(ss, methodName)) { param = setM.matcher(methodName).replaceAll(rapl).toLowerCase(); setMethods.put(param, m); } else { // logger.info(methodName + " 不是getter,setter方法!"); } } } /** * @desc 调用set方法 */ public boolean setMethodValue(String property, Object object) { Method m = setMethods.get(property.toLowerCase()); if (m != null) { try { // 调用目标类的setter函数 m.invoke(obj, object); return true; } catch (Exception ex) { log.info("invoke getter on " + property + " error: " + ex.toString()); return false; } } return false; } /** * @desc 调用set方法 */ public Object getMethodValue(String property) { Object value = null; Method m = getMethods.get(property.toLowerCase()); if (m != null) { try { /* * 调用obj类的setter函数 */ value = m.invoke(obj, new Object[]{}); } catch (Exception ex) { log.info("invoke getter on " + property + " error: " + ex.toString()); } } return value; } /** * 把map中的内容全部注入到obj中 * * @param data * @return */ public Object setAll(Map<String, Object> data) { if (data == null || data.keySet().size() <= 0) { return null; } for (Entry<String, Object> entry : data.entrySet()) { this.setMethodValue(entry.getKey(), entry.getValue()); } return obj; } /** * 把map中的内容全部注入到obj中 * * @param o * @param data * @return */ public static Object setAll(Object o, Map<String, Object> data) { ReflectHelper reflectHelper = new ReflectHelper(o); reflectHelper.setAll(data); return o; } /** * 把map中的内容全部注入到新实例中 * * @param clazz * @param data * @return */ @SuppressWarnings("unchecked") public static <T> T setAll(Class<T> clazz, Map<String, Object> data) { T o = null; try { o = clazz.newInstance(); } catch (Exception e) { e.printStackTrace(); o = null; return o; } return (T) setAll(o, data); } /** * 根据传入的class将mapList转换为实体类list * * @param mapist * @param clazz * @return */ public static <T> List<T> transList2Entrys(List<Map<String, Object>> mapist, Class<T> clazz) { List<T> list = new ArrayList<T>(); if (mapist != null && mapist.size() > 0) { for (Map<String, Object> data : mapist) { list.add(ReflectHelper.setAll(clazz, data)); } } return list; } /** * 根据属性名获取属性值 */ public static Object getFieldValueByName(String fieldName, Object o) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = o.getClass().getMethod(getter, new Class[]{}); Object value = method.invoke(o, new Object[]{}); return value; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取属性值 */ public static Object getFieldVal(String fieldName, Object o) { try { // 暴力反射获取属性 Field filed = o.getClass().getDeclaredField(fieldName); // 设置反射时取消Java的访问检查,暴力访问 filed.setAccessible(true); Object val = filed.get(o); return val; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取属性名数组 */ public static String[] getFiledName(Object o) { Field[] fields = o.getClass().getDeclaredFields(); String[] fieldNames = new String[fields.length]; for (int i = 0; i < fields.length; i++) { //log.info(fields[i].getType()); fieldNames[i] = fields[i].getName(); } return fieldNames; } /** * 获取属性类型(type),属性名(name),属性值(value)的map组成的list */ public static List<Map> getFiledsInfo(Object o) { Field[] fields = o.getClass().getDeclaredFields(); String[] fieldNames = new String[fields.length]; List<Map> list = new ArrayList<Map>(); Map<String, Object> infoMap = null; for (int i = 0; i < fields.length; i++) { infoMap = new HashMap<>(5); infoMap.put("type", fields[i].getType().toString()); infoMap.put("name", fields[i].getName()); infoMap.put("value", getFieldValueByName(fields[i].getName(), o)); list.add(infoMap); } return list; } /** * 获取对象的所有属性值,返回一个对象数组 */ public static Object[] getFiledValues(Object o) { String[] fieldNames = getFiledName(o); Object[] value = new Object[fieldNames.length]; for (int i = 0; i < fieldNames.length; i++) { value[i] = getFieldValueByName(fieldNames[i], o); } return value; } /** * 判断给定的字段是不是类中的属性 * @param field 字段名 * @param clazz 类对象 * @return */ public static boolean isClassField(String field, Class clazz){ Field[] fields = clazz.getDeclaredFields(); for(int i=0;i<fields.length;i++){ String fieldName = fields[i].getName(); String tableColumnName = oConvertUtils.camelToUnderline(fieldName); if(fieldName.equalsIgnoreCase(field) || tableColumnName.equalsIgnoreCase(field)){ return true; } } return false; } /** * 获取class的 包括父类的 * @param clazz * @return */ public static List<Field> getClassFields(Class<?> clazz) { List<Field> list = new ArrayList<Field>(); Field[] fields; do{ fields = clazz.getDeclaredFields(); for(int i = 0;i<fields.length;i++){ list.add(fields[i]); } clazz = clazz.getSuperclass(); }while(clazz!= Object.class&&clazz!=null); return list; } /** * 获取表字段名 * @param clazz * @param name * @return */ public static String getTableFieldName(Class<?> clazz, String name) { try { //如果字段加注解了@TableField(exist = false),不走DB查询 Field field = null; try { field = clazz.getDeclaredField(name); } catch (NoSuchFieldException e) { //e.printStackTrace(); } //如果为空,则去父类查找字段 if (field == null) { List<Field> allFields = getClassFields(clazz); List<Field> searchFields = allFields.stream().filter(a -> a.getName().equals(name)).collect(Collectors.toList()); if(searchFields!=null && searchFields.size()>0){ field = searchFields.get(0); } } if (field != null) { TableField tableField = field.getAnnotation(TableField.class); if (tableField != null){ if(tableField.exist() == false){ //如果设置了TableField false 这个字段不需要处理 return null; }else{ String column = tableField.value(); //如果设置了TableField value 这个字段是实体字段 if(!"".equals(column)){ return column; } } } } } catch (Exception e) { e.printStackTrace(); } return name; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/RestUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/RestUtil.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.http.*; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map; /** * 调用 Restful 接口 Util * * @author sunjianlei */ @Slf4j public class RestUtil { private static String domain = null; private static String path = null; private static String getDomain() { if (domain == null) { domain = SpringContextUtils.getDomain(); // issues/2959 // 微服务版集成企业微信单点登录 // 因为微服务版没有端口号,导致 SpringContextUtils.getDomain() 方法获取的域名的端口号变成了:-1所以出问题了,只需要把这个-1给去掉就可以了。 String port=":-1"; if (domain.endsWith(port)) { domain = domain.substring(0, domain.length() - 3); } } return domain; } private static String getPath() { if (path == null) { path = SpringContextUtils.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path"); } return oConvertUtils.getString(path); } public static String getBaseUrl() { String basepath = getDomain() + getPath(); log.info(" RestUtil.getBaseUrl: " + basepath); return basepath; } /** * RestAPI 调用器 */ private final static RestTemplate RT; static { // 解决[issues/8859]online表单java增强失效------------ // 使用 Apache HttpClient 避免 JDK HttpURLConnection 的 too many bytes written 问题 HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setConnectTimeout(30000); requestFactory.setReadTimeout(30000); RT = new RestTemplate(requestFactory); // 解决乱码问题(替换 StringHttpMessageConverter 为 UTF-8) for (int i = 0; i < RT.getMessageConverters().size(); i++) { if (RT.getMessageConverters().get(i) instanceof StringHttpMessageConverter) { RT.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8)); break; } } } public static RestTemplate getRestTemplate() { return RT; } /** * 发送 get 请求 */ public static JSONObject get(String url) { return getNative(url, null, null).getBody(); } /** * 发送 get 请求 */ public static JSONObject get(String url, JSONObject variables) { return getNative(url, variables, null).getBody(); } /** * 发送 get 请求 */ public static JSONObject get(String url, JSONObject variables, JSONObject params) { return getNative(url, variables, params).getBody(); } /** * 发送 get 请求,返回原生 ResponseEntity 对象 */ public static ResponseEntity<JSONObject> getNative(String url, JSONObject variables, JSONObject params) { return request(url, HttpMethod.GET, variables, params); } /** * 发送 Post 请求 */ public static JSONObject post(String url) { return postNative(url, null, null).getBody(); } /** * 发送 Post 请求 */ public static JSONObject post(String url, JSONObject params) { return postNative(url, null, params).getBody(); } /** * 发送 Post 请求 */ public static JSONObject post(String url, JSONObject variables, JSONObject params) { return postNative(url, variables, params).getBody(); } /** * 发送 POST 请求,返回原生 ResponseEntity 对象 */ public static ResponseEntity<JSONObject> postNative(String url, JSONObject variables, JSONObject params) { return request(url, HttpMethod.POST, variables, params); } /** * 发送 put 请求 */ public static JSONObject put(String url) { return putNative(url, null, null).getBody(); } /** * 发送 put 请求 */ public static JSONObject put(String url, JSONObject params) { return putNative(url, null, params).getBody(); } /** * 发送 put 请求 */ public static JSONObject put(String url, JSONObject variables, JSONObject params) { return putNative(url, variables, params).getBody(); } /** * 发送 put 请求,返回原生 ResponseEntity 对象 */ public static ResponseEntity<JSONObject> putNative(String url, JSONObject variables, JSONObject params) { return request(url, HttpMethod.PUT, variables, params); } /** * 发送 delete 请求 */ public static JSONObject delete(String url) { return deleteNative(url, null, null).getBody(); } /** * 发送 delete 请求 */ public static JSONObject delete(String url, JSONObject variables, JSONObject params) { return deleteNative(url, variables, params).getBody(); } /** * 发送 delete 请求,返回原生 ResponseEntity 对象 */ public static ResponseEntity<JSONObject> deleteNative(String url, JSONObject variables, JSONObject params) { return request(url, HttpMethod.DELETE, null, variables, params, JSONObject.class); } /** * 发送请求 */ public static ResponseEntity<JSONObject> request(String url, HttpMethod method, JSONObject variables, JSONObject params) { return request(url, method, getHeaderApplicationJson(), variables, params, JSONObject.class); } /** * 发送请求 * * @param url 请求地址 * @param method 请求方式 * @param headers 请求头 可空 * @param variables 请求url参数 可空 * @param params 请求body参数 可空 * @param responseType 返回类型 * @return ResponseEntity<responseType> */ public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers, JSONObject variables, Object params, Class<T> responseType) { log.info(" RestUtil --- request --- url = "+ url); if (StringUtils.isEmpty(url)) { throw new RuntimeException("url 不能为空"); } if (method == null) { throw new RuntimeException("method 不能为空"); } if (headers == null) { headers = new HttpHeaders(); } // 请求体 String body = ""; if (params != null) { if (params instanceof JSONObject) { body = ((JSONObject) params).toJSONString(); } else { body = params.toString(); } } // 拼接 url 参数 if (variables != null && !variables.isEmpty()) { url += ("?" + asUrlVariables(variables)); } // 解决[issues/8951]从jeecgboot 3.8.2 升级到 3.8.3 在线表单java增强功能报错------------ // Content-Length 强制设置(解决可能出现的截断问题) if (StringUtils.isNotEmpty(body)) { int contentLength = body.getBytes(StandardCharsets.UTF_8).length; String current = headers.getFirst(HttpHeaders.CONTENT_LENGTH); if (current == null || !current.equals(String.valueOf(contentLength))) { headers.setContentLength(contentLength); log.info(" RestUtil --- request --- 修正/设置 Content-Length = " + contentLength + (current!=null?" (原值="+current+")":"")); } } // 发送请求 HttpEntity<String> request = new HttpEntity<>(body, headers); return RT.exchange(url, method, request, responseType); } /** * 发送请求(支持自定义超时时间) * * @param url 请求地址 * @param method 请求方式 * @param headers 请求头 可空 * @param variables 请求url参数 可空 * @param params 请求body参数 可空 * @param responseType 返回类型 * @param timeout 超时时间(毫秒),如果为0或负数则使用默认超时 * @return ResponseEntity<responseType> */ public static <T> ResponseEntity<T> request(String url, HttpMethod method, HttpHeaders headers, JSONObject variables, Object params, Class<T> responseType, int timeout) { log.info(" RestUtil --- request --- url = "+ url + ", timeout = " + timeout); if (StringUtils.isEmpty(url)) { throw new RuntimeException("url 不能为空"); } if (method == null) { throw new RuntimeException("method 不能为空"); } if (headers == null) { headers = new HttpHeaders(); } // 创建自定义RestTemplate(如果需要设置超时) RestTemplate restTemplate = RT; if (timeout > 0) { // 代码逻辑说明: [issues/8859]online表单java增强失效------------ HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setConnectTimeout(timeout); requestFactory.setReadTimeout(timeout); restTemplate = new RestTemplate(requestFactory); // 解决乱码问题(替换 StringHttpMessageConverter 为 UTF-8) for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) { if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) { restTemplate.getMessageConverters().set(i, new StringHttpMessageConverter(StandardCharsets.UTF_8)); break; } } } // 请求体 String body = ""; if (params != null) { if (params instanceof JSONObject) { body = ((JSONObject) params).toJSONString(); } else { body = params.toString(); } } // 拼接 url 参数 if (variables != null && !variables.isEmpty()) { url += ("?" + asUrlVariables(variables)); } // Content-Length 强制设置(解决可能出现的截断问题) if (StringUtils.isNotEmpty(body) && !headers.containsKey(HttpHeaders.CONTENT_LENGTH)) { int contentLength = body.getBytes(StandardCharsets.UTF_8).length; String current = headers.getFirst(HttpHeaders.CONTENT_LENGTH); if (current == null || !current.equals(String.valueOf(contentLength))) { headers.setContentLength(contentLength); log.info(" RestUtil --- request(timeout) --- 修正/设置 Content-Length = " + contentLength + (current!=null?" (原值="+current+")":"")); } } // 发送请求 HttpEntity<String> request = new HttpEntity<>(body, headers); return restTemplate.exchange(url, method, request, responseType); } /** * 获取JSON请求头 */ public static HttpHeaders getHeaderApplicationJson() { return getHeader(MediaType.APPLICATION_JSON_UTF8_VALUE); } /** * 获取请求头 */ public static HttpHeaders getHeader(String mediaType) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(mediaType)); headers.add("Accept", mediaType); return headers; } /** * 将 JSONObject 转为 a=1&b=2&c=3...&n=n 的形式 */ public static String asUrlVariables(JSONObject variables) { Map<String, Object> source = variables.getInnerMap(); Iterator<String> it = source.keySet().iterator(); StringBuilder urlVariables = new StringBuilder(); while (it.hasNext()) { String key = it.next(); String value = ""; Object object = source.get(key); if (object != null) { if (!StringUtils.isEmpty(object.toString())) { value = object.toString(); } } urlVariables.append("&").append(key).append("=").append(value); } // 去掉第一个& return urlVariables.substring(1); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ImportExcelUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ImportExcelUtil.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.extension.service.IService; import lombok.extern.slf4j.Slf4j; import org.jeecg.common.api.vo.Result; import org.jeecg.common.constant.CommonConstant; import java.io.File; import java.io.IOException; import java.util.List; /** * 导出返回信息 * @author: jeecg-boot */ @Slf4j public class ImportExcelUtil { public static Result<?> imporReturnRes(int errorLines,int successLines,List<String> errorMessage) throws IOException { if (errorLines == 0) { return Result.ok("共" + successLines + "行数据全部导入成功!"); } else { JSONObject result = new JSONObject(5); int totalCount = successLines + errorLines; result.put("totalCount", totalCount); result.put("errorCount", errorLines); result.put("successCount", successLines); result.put("msg", "总上传行数:" + totalCount + ",已导入行数:" + successLines + ",错误行数:" + errorLines); String fileUrl = PmsUtil.saveErrorTxtByList(errorMessage, "userImportExcelErrorLog"); int lastIndex = fileUrl.lastIndexOf(File.separator); String fileName = fileUrl.substring(lastIndex + 1); result.put("fileUrl", "/sys/common/static/" + fileUrl); result.put("fileName", fileName); Result res = Result.ok(result); res.setCode(201); res.setMessage("文件导入成功,但有错误。"); return res; } } public static List<String> importDateSave(List<?> list, Class serviceClass, List<String> errorMessage, String errorFlag) { IService bean =(IService) SpringContextUtils.getBean(serviceClass); for (int i = 0; i < list.size(); i++) { try { boolean save = bean.save(list.get(i)); if(!save){ throw new Exception(errorFlag); } } catch (Exception e) { String message = e.getMessage().toLowerCase(); int lineNumber = i + 1; // 通过索引名判断出错信息 if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_ROLE_CODE)) { errorMessage.add("第 " + lineNumber + " 行:角色编码已经存在,忽略导入。"); } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_JOB_CLASS_NAME)) { errorMessage.add("第 " + lineNumber + " 行:任务类名已经存在,忽略导入。"); }else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_CODE)) { errorMessage.add("第 " + lineNumber + " 行:职务编码已经存在,忽略导入。"); }else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_DEPART_ORG_CODE)) { errorMessage.add("第 " + lineNumber + " 行:部门编码已经存在,忽略导入。"); }else { errorMessage.add("第 " + lineNumber + " 行:未知错误,忽略导入"); log.error(e.getMessage(), e); } } } return errorMessage; } public static List<String> importDateSaveOne(Object obj, Class serviceClass,List<String> errorMessage,int i,String errorFlag) { IService bean =(IService) SpringContextUtils.getBean(serviceClass); try { boolean save = bean.save(obj); if(!save){ throw new Exception(errorFlag); } } catch (Exception e) { String message = e.getMessage().toLowerCase(); int lineNumber = i + 1; // 通过索引名判断出错信息 if (message.contains(CommonConstant.SQL_INDEX_UNIQ_SYS_ROLE_CODE)) { errorMessage.add("第 " + lineNumber + " 行:角色编码已经存在,忽略导入。"); } else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_JOB_CLASS_NAME)) { errorMessage.add("第 " + lineNumber + " 行:任务类名已经存在,忽略导入。"); }else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_CODE)) { errorMessage.add("第 " + lineNumber + " 行:职务编码已经存在,忽略导入。"); }else if (message.contains(CommonConstant.SQL_INDEX_UNIQ_DEPART_ORG_CODE)) { errorMessage.add("第 " + lineNumber + " 行:部门编码已经存在,忽略导入。"); }else { errorMessage.add("第 " + lineNumber + " 行:未知错误,忽略导入"); log.error(e.getMessage(), e); } } return errorMessage; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/oConvertUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/oConvertUtils.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSONArray; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.SymbolConstant; import org.jeecg.config.mybatis.MybatisPlusSaasConfig; import org.springframework.beans.BeanUtils; import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.net.*; import java.sql.Date; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * * @Author 张代浩 * */ @Slf4j public class oConvertUtils { public static boolean isEmpty(Object object) { if (object == null) { return (true); } if ("".equals(object)) { return (true); } if (CommonConstant.STRING_NULL.equals(object)) { return (true); } return (false); } public static boolean isNotEmpty(Object object) { if (object != null && !"".equals(object) && !object.equals(CommonConstant.STRING_NULL)) { return (true); } return (false); } /** * 返回decode解密字符串 * * @param inStr * @return */ public static String decodeString(String inStr) { if (oConvertUtils.isEmpty(inStr)) { return null; } try { inStr = URLDecoder.decode(inStr, "UTF-8"); } catch (Exception e) { // 解决:URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "自动" //e.printStackTrace(); } return inStr; } public static String decode(String strIn, String sourceCode, String targetCode) { String temp = code2code(strIn, sourceCode, targetCode); return temp; } @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming") public static String StrToUTF(String strIn, String sourceCode, String targetCode) { strIn = ""; try { strIn = new String(strIn.getBytes("ISO-8859-1"), "GBK"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return strIn; } private static String code2code(String strIn, String sourceCode, String targetCode) { String strOut = null; if (strIn == null || "".equals(strIn.trim())) { return strIn; } try { byte[] b = strIn.getBytes(sourceCode); for (int i = 0; i < b.length; i++) { System.out.print(b[i] + " "); } strOut = new String(b, targetCode); } catch (Exception e) { e.printStackTrace(); return null; } return strOut; } public static int getInt(String s, int defval) { if (s == null || "".equals(s)) { return (defval); } try { return (Integer.parseInt(s)); } catch (NumberFormatException e) { return (defval); } } public static int getInt(String s) { if (s == null || "".equals(s)) { return 0; } try { return (Integer.parseInt(s)); } catch (NumberFormatException e) { return 0; } } public static int getInt(String s, Integer df) { if (s == null || "".equals(s)) { return df; } try { return (Integer.parseInt(s)); } catch (NumberFormatException e) { return 0; } } public static Integer[] getInts(String[] s) { if (s == null) { return null; } Integer[] integer = new Integer[s.length]; for (int i = 0; i < s.length; i++) { integer[i] = Integer.parseInt(s[i]); } return integer; } public static double getDouble(String s, double defval) { if (s == null || "".equals(s)) { return (defval); } try { return (Double.parseDouble(s)); } catch (NumberFormatException e) { return (defval); } } public static double getDou(Double s, double defval) { if (s == null) { return (defval); } return s; } /*public static Short getShort(String s) { if (StringUtil.isNotEmpty(s)) { return (Short.parseShort(s)); } else { return null; } }*/ public static int getInt(Object object, int defval) { if (isEmpty(object)) { return (defval); } try { return (Integer.parseInt(object.toString())); } catch (NumberFormatException e) { return (defval); } } public static Integer getInteger(Object object, Integer defval) { if (isEmpty(object)) { return (defval); } try { return (Integer.parseInt(object.toString())); } catch (NumberFormatException e) { return (defval); } } public static Integer getInt(Object object) { if (isEmpty(object)) { return null; } try { return (Integer.parseInt(object.toString())); } catch (NumberFormatException e) { return null; } } public static int getInt(BigDecimal s, int defval) { if (s == null) { return (defval); } return s.intValue(); } public static Integer[] getIntegerArry(String[] object) { int len = object.length; Integer[] result = new Integer[len]; try { for (int i = 0; i < len; i++) { result[i] = new Integer(object[i].trim()); } return result; } catch (NumberFormatException e) { return null; } } public static String getString(String s) { return (getString(s, "")); } /** * 转义成Unicode编码 * @param s * @return */ /*public static String escapeJava(Object s) { return StringEscapeUtils.escapeJava(getString(s)); }*/ public static String getString(Object object) { if (isEmpty(object)) { return ""; } return (object.toString().trim()); } public static String getString(int i) { return (String.valueOf(i)); } public static String getString(float i) { return (String.valueOf(i)); } /** * 返回常规字符串(只保留字符串中的数字、字母、中文) * * @param input * @return */ public static String getNormalString(String input) { if (oConvertUtils.isEmpty(input)) { return null; } String result = input.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", ""); return result; } public static String getString(String s, String defval) { if (isEmpty(s)) { return (defval); } return (s.trim()); } public static String getString(Object s, String defval) { if (isEmpty(s)) { return (defval); } return (s.toString().trim()); } public static long stringToLong(String str) { Long test = new Long(0); try { test = Long.valueOf(str); } catch (Exception e) { } return test.longValue(); } /** * 获取本机IP */ public static String getIp() { String ip = null; try { InetAddress address = InetAddress.getLocalHost(); ip = address.getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } return ip; } /** * 判断一个类是否为基本数据类型。 * * @param clazz * 要判断的类。 * @return true 表示为基本数据类型。 */ private static boolean isBaseDataType(Class clazz) throws Exception { return (clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Byte.class) || clazz.equals(Long.class) || clazz.equals(Double.class) || clazz.equals(Float.class) || clazz.equals(Character.class) || clazz.equals(Short.class) || clazz.equals(BigDecimal.class) || clazz.equals(BigInteger.class) || clazz.equals(Boolean.class) || clazz.equals(Date.class) || clazz.isPrimitive()); } /** * 解码base64 * * @param base64Str base64字符串 * @return 被加密后的字符串 */ public static String decodeBase64Str(String base64Str) { byte[] byteContent = Base64.decodeBase64(base64Str); if (byteContent == null) { return null; } String decodedString = new String(byteContent); return decodedString; } /** * @param request * IP * @return IP Address */ public static String getIpAddrByRequest(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } /** * @return 本机IP * @throws SocketException */ public static String getRealIp() throws SocketException { // 本地IP,如果没有配置外网IP则返回它 String localip = null; // 外网IP String netip = null; Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; // 是否找到外网IP boolean finded = false; while (netInterfaces.hasMoreElements() && !finded) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> address = ni.getInetAddresses(); while (address.hasMoreElements()) { ip = address.nextElement(); // 外网IP if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { netip = ip.getHostAddress(); finded = true; break; } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { // 内网IP localip = ip.getHostAddress(); } } } if (netip != null && !"".equals(netip)) { return netip; } else { return localip; } } /** * java去除字符串中的空格、回车、换行符、制表符 * * @param str * @return */ public static String replaceBlank(String str) { String dest = ""; if (str != null) { String reg = "\\s*|\t|\r|\n"; Pattern p = Pattern.compile(reg); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } /** * 判断元素是否在数组内 * * @param child * @param all * @return */ public static boolean isIn(String child, String[] all) { if (all == null || all.length == 0) { return false; } for (int i = 0; i < all.length; i++) { String aSource = all[i]; if (aSource.equals(child)) { return true; } } return false; } /** * 判断元素是否在数组内 * * @param childArray * @param all * @return */ public static boolean isArrayIn(String[] childArray, String[] all) { if (all == null || all.length == 0) { return false; } for (String v : childArray) { if (!isIn(v, all)) { return false; } } return true; } /** * 判断元素是否在数组内 * * @param childArray * @param all * @return */ public static boolean isJsonArrayIn(JSONArray childArray, String[] all) { if (all == null || all.length == 0) { return false; } List<String> childs = childArray.toJavaList(String.class); for (String v : childs) { if (!isIn(v, all)) { return false; } } return true; } /** * 判断字符串是否为JSON格式 * @param str * @return */ public static boolean isJson(String str) { if (str == null || str.trim().isEmpty()) { return false; } try { com.alibaba.fastjson.JSON.parse(str); return true; } catch (Exception e) { return false; } } /** * 获取Map对象 */ public static Map<Object, Object> getHashMap() { return new HashMap<>(5); } /** * SET转换MAP * * @param str * @return */ public static Map<Object, Object> setToMap(Set<Object> setobj) { Map<Object, Object> map = getHashMap(); for (Iterator iterator = setobj.iterator(); iterator.hasNext();) { Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) iterator.next(); map.put(entry.getKey().toString(), entry.getValue() == null ? "" : entry.getValue().toString().trim()); } return map; } public static boolean isInnerIp(String ipAddress) { boolean isInnerIp = false; long ipNum = getIpNum(ipAddress); /** * 私有IP:A类 10.0.0.0-10.255.255.255 B类 172.16.0.0-172.31.255.255 C类 192.168.0.0-192.168.255.255 当然,还有127这个网段是环回地址 **/ long aBegin = getIpNum("10.0.0.0"); long aEnd = getIpNum("10.255.255.255"); long bBegin = getIpNum("172.16.0.0"); long bEnd = getIpNum("172.31.255.255"); long cBegin = getIpNum("192.168.0.0"); long cEnd = getIpNum("192.168.255.255"); String localIp = "127.0.0.1"; isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd) || localIp.equals(ipAddress); return isInnerIp; } private static long getIpNum(String ipAddress) { String[] ip = ipAddress.split("\\."); long a = Integer.parseInt(ip[0]); long b = Integer.parseInt(ip[1]); long c = Integer.parseInt(ip[2]); long d = Integer.parseInt(ip[3]); long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d; return ipNum; } private static boolean isInner(long userIp, long begin, long end) { return (userIp >= begin) && (userIp <= end); } /** * 将下划线大写方式命名的字符串转换为驼峰式。 * 如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br> * 例如:hello_world->helloWorld * * @param name * 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ public static String camelName(String name) { StringBuilder result = new StringBuilder(); // 快速检查 if (name == null || name.isEmpty()) { // 没必要转换 return ""; } else if (!name.contains(SymbolConstant.UNDERLINE)) { // 不含下划线,仅将首字母小写 // 代码逻辑说明: TASK #2500 【代码生成器】代码生成器开发一通用模板生成功能 return name.substring(0, 1).toLowerCase() + name.substring(1).toLowerCase(); } // 用下划线将原始字符串分割 String[] camels = name.split("_"); for (String camel : camels) { // 跳过原始字符串中开头、结尾的下换线或双重下划线 if (camel.isEmpty()) { continue; } // 处理真正的驼峰片段 if (result.length() == 0) { // 第一个驼峰片段,全部字母都小写 result.append(camel.toLowerCase()); } else { // 其他的驼峰片段,首字母大写 result.append(camel.substring(0, 1).toUpperCase()); result.append(camel.substring(1).toLowerCase()); } } return result.toString(); } /** * 将下划线大写方式命名的字符串转换为驼峰式。 * 如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br> * 例如:hello_world,test_id->helloWorld,testId * * @param name * 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ public static String camelNames(String names) { if(names==null||"".equals(names)){ return null; } StringBuffer sf = new StringBuffer(); String[] fs = names.split(","); for (String field : fs) { field = camelName(field); sf.append(field + ","); } String result = sf.toString(); return result.substring(0, result.length() - 1); } /** * 将下划线大写方式命名的字符串转换为驼峰式。(首字母写) * 如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br> * 例如:hello_world->HelloWorld * * @param name * 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ public static String camelNameCapFirst(String name) { StringBuilder result = new StringBuilder(); // 快速检查 if (name == null || name.isEmpty()) { // 没必要转换 return ""; } else if (!name.contains(SymbolConstant.UNDERLINE)) { // 不含下划线,仅将首字母小写 return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); } // 用下划线将原始字符串分割 String[] camels = name.split("_"); for (String camel : camels) { // 跳过原始字符串中开头、结尾的下换线或双重下划线 if (camel.isEmpty()) { continue; } // 其他的驼峰片段,首字母大写 result.append(camel.substring(0, 1).toUpperCase()); result.append(camel.substring(1).toLowerCase()); } return result.toString(); } /** * 将驼峰命名转化成下划线 * @param para * @return */ public static String camelToUnderline(String para){ int length = 3; if(para.length()<length){ return para.toLowerCase(); } StringBuilder sb=new StringBuilder(para); //定位 int temp=0; //从第三个字符开始 避免命名不规范 for(int i=2;i<para.length();i++){ if(Character.isUpperCase(para.charAt(i))){ sb.insert(i+temp, "_"); temp+=1; } } return sb.toString().toLowerCase(); } /** * 随机数 * @param place 定义随机数的位数 */ public static String randomGen(int place) { String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789"; StringBuffer sb = new StringBuffer(); Random rd = new Random(); for(int i=0;i<place;i++) { sb.append(base.charAt(rd.nextInt(base.length()))); } return sb.toString(); } /** * 获取类的所有属性,包括父类 * * @param object * @return */ public static Field[] getAllFields(Object object) { Class<?> clazz = object.getClass(); List<Field> fieldList = new ArrayList<>(); while (clazz != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } Field[] fields = new Field[fieldList.size()]; fieldList.toArray(fields); return fields; } /** * 将map的key全部转成小写 * @param list * @return */ public static List<Map<String, Object>> toLowerCasePageList(List<Map<String, Object>> list){ List<Map<String, Object>> select = new ArrayList<>(); for (Map<String, Object> row : list) { Map<String, Object> resultMap = new HashMap<>(5); Set<String> keySet = row.keySet(); for (String key : keySet) { String newKey = key.toLowerCase(); resultMap.put(newKey, row.get(key)); } select.add(resultMap); } return select; } /** * 将entityList转换成modelList * @param fromList * @param tClass * @param <F> * @param <T> * @return */ public static<F,T> List<T> entityListToModelList(List<F> fromList, Class<T> tClass){ if(fromList == null || fromList.isEmpty()){ return null; } List<T> tList = new ArrayList<>(); for(F f : fromList){ T t = entityToModel(f, tClass); tList.add(t); } return tList; } public static<F,T> T entityToModel(F entity, Class<T> modelClass) { log.debug("entityToModel : Entity属性的值赋值到Model"); Object model = null; if (entity == null || modelClass ==null) { return null; } try { model = modelClass.newInstance(); } catch (InstantiationException e) { log.error("entityToModel : 实例化异常", e); } catch (IllegalAccessException e) { log.error("entityToModel : 安全权限异常", e); } BeanUtils.copyProperties(entity, model); return (T)model; } /** * 判断 list 是否为空 * * @param list * @return true or false * list == null : true * list.size() == 0 : true */ public static boolean listIsEmpty(Collection list) { return (list == null || list.size() == 0); } /** * 判断旧值与新值 是否相等 * * @param oldVal * @param newVal * @return */ public static boolean isEqual(Object oldVal, Object newVal) { if (oldVal != null && newVal != null) { if (isArray(oldVal)) { return equalityOfArrays((Object[]) oldVal, (Object[]) newVal); }else if(oldVal instanceof JSONArray){ if(newVal instanceof JSONArray){ return equalityOfJSONArray((JSONArray) oldVal, (JSONArray) newVal); }else{ if (isEmpty(newVal) && (oldVal == null || ((JSONArray) oldVal).size() == 0)) { return true; } List<Object> arrayStr = Arrays.asList(newVal.toString().split(",")); JSONArray newValArray = new JSONArray(arrayStr); return equalityOfJSONArray((JSONArray) oldVal, newValArray); } }else{ return oldVal.equals(newVal); } } else { if (oldVal == null && newVal == null) { return true; } else { return false; } } } /** * 方法描述 判断一个对象是否是一个数组 * * @param obj * @return * @author yaomy * @date 2018年2月5日 下午5:03:00 */ public static boolean isArray(Object obj) { if (obj == null) { return false; } return obj.getClass().isArray(); } /** * 获取集合的大小 * * @param collection * @return */ public static int getCollectionSize(Collection<?> collection) { return collection != null ? collection.size() : 0; } /** * 判断两个数组是否相等(数组元素不分顺序) * * @param oldVal * @param newVal * @return */ public static boolean equalityOfJSONArray(JSONArray oldVal, JSONArray newVal) { if (oldVal != null && newVal != null) { Object[] oldValArray = oldVal.toArray(); Object[] newValArray = newVal.toArray(); return equalityOfArrays(oldValArray,newValArray); } else { if ((oldVal == null || oldVal.size() == 0) && (newVal == null || newVal.size() == 0)) { return true; } else { return false; } } } /** * 比较带逗号的字符串 * QQYUN-5212【简流】按日期触发 多选 人员组件 选择顺序不一致时 不触发,应该是统一问题 包括多选部门组件 * @param oldVal * @param newVal * @return */ public static boolean equalityOfStringArrays(String oldVal, String newVal) { if(oldVal.equals(newVal)){ return true; } if(oldVal.indexOf(",")>=0 && newVal.indexOf(",")>=0){ String[] arr1 = oldVal.split(","); String[] arr2 = newVal.split(","); if(arr1.length == arr2.length){ boolean flag = true; Map<String, Integer> map = new HashMap<>(); for(String s1: arr1){ map.put(s1, 1); } for(String s2: arr2){ if(map.get(s2) == null){ flag = false; break; } } return flag; } } return false; } /** * 判断两个数组是否相等(数组元素不分顺序) * * @param oldVal * @param newVal * @return */ public static boolean equalityOfArrays(Object[] oldVal, Object newVal[]) { if (oldVal != null && newVal != null) { Arrays.sort(oldVal); Arrays.sort(newVal); return Arrays.equals(oldVal, newVal); } else { if ((oldVal == null || oldVal.length == 0) && (newVal == null || newVal.length == 0)) { return true; } else { return false; } } } // public static void main(String[] args) { //// String[] a = new String[]{"1", "2"}; //// String[] b = new String[]{"2", "1"}; // Integer a = null; // Integer b = 1; // System.out.println(oConvertUtils.isEqual(a, b)); // } /** * 判断 list 是否不为空 * * @param list * @return true or false * list == null : false * list.size() == 0 : false */ public static boolean listIsNotEmpty(Collection list) { return !listIsEmpty(list); } /** * 读取静态文本内容 * @param url * @return */ public static String readStatic(String url) { String json = ""; try { //换个写法,解决springboot读取jar包中文件的问题 InputStream stream = oConvertUtils.class.getClassLoader().getResourceAsStream(url.replace("classpath:", "")); json = IOUtils.toString(stream,"UTF-8"); } catch (IOException e) { log.error(e.getMessage(),e); } return json; } /** * 将List 转成 JSONArray * @return */ public static JSONArray list2JSONArray(List<String> list){ if(list==null || list.size()==0){ return null; } JSONArray array = new JSONArray(); for(String str: list){ array.add(str); } return array; } /** * 判断两个list中的元素是否完全一致 * QQYUN-5326【简流】获取组织人员 单/多 筛选条件 没有部门筛选 * @return */ public static boolean isEqList(List<String> list1, List<String> list2){ if(list1.size() != list2.size()){ return false; } for(String str1: list1){ boolean flag = false; for(String str2: list2){ if(str1.equals(str2)){ flag = true; break; } } if(!flag){ return false; } } return true; } /** * 判断 sourceList中的元素是否在targetList中出现 * * QQYUN-5326【简流】获取组织人员 单/多 筛选条件 没有部门筛选 * @param sourceList 源列表,要检查的元素列表 * @param targetList 目标列表,用于匹配的列表 * @return 如果sourceList中有任何元素在targetList中存在则返回true,否则返回false */ public static boolean isInList(List<String> sourceList, List<String> targetList){ for(String sourceItem: sourceList){ boolean flag = false; for(String targetItem: targetList){ if(sourceItem.equals(targetItem)){ flag = true; break; } } if(flag){ return true; } } return false; } /** * 判断 sourceList中的所有元素是否都在targetList中存在 * @param sourceList 源列表,要检查的元素列表 * @param targetList 目标列表,用于匹配的列表 * @return 如果sourceList中的所有元素都在targetList中存在则返回true,否则返回false */ public static boolean isAllInList(List<String> sourceList, List<String> targetList){ if(sourceList == null || sourceList.isEmpty()){ return true; // 空列表视为所有元素都存在 } if(targetList == null || targetList.isEmpty()){ return false; // 目标列表为空,源列表非空时返回false } for(String sourceItem: sourceList){ boolean found = false; for(String targetItem: targetList){ if(sourceItem.equals(targetItem)){ found = true; break; } } if(!found){ return false; // 有任何一个元素不在目标列表中,返回false } } return true; // 所有元素都找到了 } /** * 计算文件大小转成MB * @param uploadCount * @return */ public static Double calculateFileSizeToMb(Long uploadCount){ double count = 0.0; if(uploadCount>0) { BigDecimal bigDecimal = new BigDecimal(uploadCount); //换算成MB BigDecimal divide = bigDecimal.divide(new BigDecimal(1048576)); count = divide.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); return count; } return count; } /** * map转str * * @param map * @return */ public static String mapToString(Map<String, String[]> map) { if (map == null || map.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String[]> entry : map.entrySet()) { String key = entry.getKey(); String[] values = entry.getValue(); sb.append(key).append("="); sb.append(values != null ? StringUtils.join(values, ",") : ""); sb.append("&"); } String result = sb.toString(); if (result.endsWith("&")) { result = result.substring(0, sb.length() - 1); } return result; } /** * 判断对象是否为空 <br/> * 支持各种类型的对象 * for for [QQYUN-10990]AIRAG * @param obj * @return * @author chenrui * @date 2025/2/13 18:34 */ public static boolean isObjectEmpty(Object obj) { if (null == obj) { return true; } if (obj instanceof CharSequence) { return isEmpty(obj); } else if (obj instanceof Map) { return ((Map<?, ?>) obj).isEmpty(); } else if (obj instanceof Iterable) { return isObjectEmpty(((Iterable<?>) obj).iterator()); } else if (obj instanceof Iterator) { return !((Iterator<?>) obj).hasNext(); } else if (isArray(obj)) { return 0 == Array.getLength(obj); } return false; } /** * iterator 是否为空 * for for [QQYUN-10990]AIRAG * @param iterator Iterator对象 * @return 是否为空 */ public static boolean isEmptyIterator(Iterator<?> iterator) { return null == iterator || false == iterator.hasNext(); } /** * 判断对象是否不为空 * for for [QQYUN-10990]AIRAG * @param object * @return * @author chenrui * @date 2025/2/13 18:35 */ public static boolean isObjectNotEmpty(Object object) { return !isObjectEmpty(object); } /** * 如果src大于des返回true * for [QQYUN-10990]AIRAG * @param src * @param des * @return * @author: chenrui * @date: 2018/9/19 15:30 */ public static boolean isGt(Number src, Number des) { if (null == src || null == des) { throw new IllegalArgumentException("参数不能为空"); } if (src.doubleValue() > des.doubleValue()) { return true; } return false; } /** * 如果src大于等于des返回true * for [QQYUN-10990]AIRAG * @param src * @param des * @return * @author: chenrui * @date: 2018/9/19 15:30 */ public static boolean isGe(Number src, Number des) { if (null == src || null == des) { throw new IllegalArgumentException("参数不能为空"); } if (src.doubleValue() < des.doubleValue()) { return false; } return true; } /** * 判断是否存在 * for [QQYUN-10990]AIRAG * @param obj * @param objs * @param <T> * @return * @author chenrui * @date 2020/9/12 15:50 */ public static <T> boolean isIn(T obj, T... objs) { if (isEmpty(objs)) { return false; } for (T obj1 : objs) { if (isEqual(obj, obj1)) { return true; } } return false; } /** * 判断租户ID是否有效 * @param tenantId * @return */ public static boolean isEffectiveTenant(String tenantId) { return MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && isNotEmpty(tenantId) && !("0").equals(tenantId); } /** * 复制源对象的非空属性到目标对象(同名属性) * * @param source 源对象(页面) * @param target 目标对象(数据库实体) */ public static void copyNonNullFields(Object source, Object target) { if (source == null || target == null) { return; } // 获取源对象的非空属性名数组 String[] nullPropertyNames = getNullPropertyNames(source); // 复制:忽略源对象的空属性,仅覆盖目标对象的对应非空属性 BeanUtils.copyProperties(source, target, nullPropertyNames); } /** * 获取源对象中值为 null 的属性名数组 * * @param source */ private static String[] getNullPropertyNames(Object source) { BeanWrapper beanWrapper = new BeanWrapperImpl(source); //获取类的属性 PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors(); // 过滤出值为 null 的属性名 return Stream.of(propertyDescriptors) .map(PropertyDescriptor::getName) .filter(name -> beanWrapper.getPropertyValue(name) == null) .toArray(String[]::new); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/YouBianCodeUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/YouBianCodeUtil.java
package org.jeecg.common.util; import io.netty.util.internal.StringUtil; /** * 流水号生成规则(按默认规则递增,数字从1-99开始递增,数字到99,递增字母;位数不够增加位数) * A001 * A001A002 * @Author zhangdaihao * */ public class YouBianCodeUtil { // 数字位数(默认生成3位的数字) /**代表数字位数*/ private static final int NUM_LENGTH = 2; public static final int ZHANWEI_LENGTH = 1+ NUM_LENGTH; public static final char LETTER= 'Z'; /** * 根据前一个code,获取同级下一个code * 例如:当前最大code为D01A04,下一个code为:D01A05 * * @param code * @return */ public static synchronized String getNextYouBianCode(String code) { String newcode = ""; if (oConvertUtils.isEmpty(code)) { String zimu = "A"; String num = getStrNum(1); newcode = zimu + num; } else { String beforeCode = code.substring(0, code.length() - 1- NUM_LENGTH); String afterCode = code.substring(code.length() - 1 - NUM_LENGTH,code.length()); char afterCodeZimu = afterCode.substring(0, 1).charAt(0); Integer afterCodeNum = Integer.parseInt(afterCode.substring(1)); // org.jeecgframework.core.util.LogUtil.info(after_code); // org.jeecgframework.core.util.LogUtil.info(after_code_zimu); // org.jeecgframework.core.util.LogUtil.info(after_code_num); String nextNum = ""; char nextZimu = 'A'; // 先判断数字等于999*,则计数从1重新开始,递增 if (afterCodeNum == getMaxNumByLength(NUM_LENGTH)) { nextNum = getNextStrNum(0); } else { nextNum = getNextStrNum(afterCodeNum); } // 先判断数字等于999*,则字母从A重新开始,递增 if(afterCodeNum == getMaxNumByLength(NUM_LENGTH)) { nextZimu = getNextZiMu(afterCodeZimu); }else{ nextZimu = afterCodeZimu; } // 例如Z99,下一个code就是Z99A01 if (LETTER == afterCodeZimu && getMaxNumByLength(NUM_LENGTH) == afterCodeNum) { newcode = code + (nextZimu + nextNum); } else { newcode = beforeCode + (nextZimu + nextNum); } } return newcode; } /** * 根据父亲code,获取下级的下一个code * * 例如:父亲CODE:A01 * 当前CODE:A01B03 * 获取的code:A01B04 * * @param parentCode 上级code * @param localCode 同级code * @return */ public static synchronized String getSubYouBianCode(String parentCode,String localCode) { if(localCode!=null && localCode!=""){ // return parentCode + getNextYouBianCode(localCode); return getNextYouBianCode(localCode); }else{ parentCode = parentCode + "A"+ getNextStrNum(0); } return parentCode; } /** * 将数字前面位数补零 * * @param num * @return */ private static String getNextStrNum(int num) { return getStrNum(getNextNum(num)); } /** * 将数字前面位数补零 * * @param num * @return */ private static String getStrNum(int num) { String s = String.format("%0" + NUM_LENGTH + "d", num); return s; } /** * 递增获取下个数字 * * @param num * @return */ private static int getNextNum(int num) { num++; return num; } /** * 递增获取下个字母 * * @param num * @return */ private static char getNextZiMu(char zimu) { if (zimu == LETTER) { return 'A'; } zimu++; return zimu; } /** * 根据数字位数获取最大值 * @param length * @return */ private static int getMaxNumByLength(int length){ if(length==0){ return 0; } StringBuilder maxNum = new StringBuilder(); for (int i=0;i<length;i++){ maxNum.append("9"); } return Integer.parseInt(maxNum.toString()); } public static String[] cutYouBianCode(String code){ if(code==null || StringUtil.isNullOrEmpty(code)){ return null; }else{ //获取标准长度为numLength+1,截取的数量为code.length/numLength+1 int c = code.length()/(NUM_LENGTH +1); String[] cutcode = new String[c]; for(int i =0 ; i <c;i++){ cutcode[i] = code.substring(0,(i+1)*(NUM_LENGTH +1)); } return cutcode; } } // public static void main(String[] args) { // // org.jeecgframework.core.util.LogUtil.info(getNextZiMu('C')); // // org.jeecgframework.core.util.LogUtil.info(getNextNum(8)); // // org.jeecgframework.core.util.LogUtil.info(cutYouBianCode("C99A01B01")[2]); // } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DySmsLimit.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/DySmsLimit.java
package org.jeecg.common.util; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ConcurrentHashMap; /** * 防止刷短信接口(只针对绑定手机号模板:SMS_175430166) * * 1、同一IP,1分钟内发短信不允许超过5次(每一分钟重置每个IP请求次数) * 2、同一IP,1分钟内发短信超过20次,进入黑名单,不让使用短信接口 * * 3、短信接口加签和时间戳 * 涉及接口: * /sys/sms * /desform/api/sendVerifyCode * /sys/sendChangePwdSms */ @Slf4j public class DySmsLimit { // 1分钟内最大发短信数量(单一IP) private static final int MAX_MESSAGE_PER_MINUTE = 5; // 1分钟 private static final int MILLIS_PER_MINUTE = 60000; // 一分钟内报警线最大短信数量,超了进黑名单(单一IP) private static final int MAX_TOTAL_MESSAGE_PER_MINUTE = 20; private static ConcurrentHashMap<String, Long> ipLastRequestTime = new ConcurrentHashMap<>(); private static ConcurrentHashMap<String, Integer> ipRequestCount = new ConcurrentHashMap<>(); private static ConcurrentHashMap<String, Boolean> ipBlacklist = new ConcurrentHashMap<>(); /** * @param ip 请求发短信的IP地址 * @return */ public static boolean canSendSms(String ip) { long currentTime = System.currentTimeMillis(); long lastRequestTime = ipLastRequestTime.getOrDefault(ip, 0L); int requestCount = ipRequestCount.getOrDefault(ip, 0); log.info("IP:{}, Msg requestCount:{} ", ip, requestCount); if (ipBlacklist.getOrDefault(ip, false)) { // 如果IP在黑名单中,则禁止发送短信 log.error("IP:{}, 进入黑名单,禁止发送请求短信!", ip); return false; } if (currentTime - lastRequestTime >= MILLIS_PER_MINUTE) { // 如果距离上次请求已经超过一分钟,则重置计数 ipRequestCount.put(ip, 1); ipLastRequestTime.put(ip, currentTime); return true; } else { // 如果距离上次请求不到一分钟 ipRequestCount.put(ip, requestCount + 1); if (requestCount < MAX_MESSAGE_PER_MINUTE) { // 如果请求次数小于5次,允许发送短信 return true; } else if (requestCount >= MAX_TOTAL_MESSAGE_PER_MINUTE) { // 如果请求次数超过报警线短信数量,将IP加入黑名单 ipBlacklist.put(ip, true); return false; } else { log.error("IP:{}, 1分钟内请求短信超过5次,请稍后重试!", ip); return false; } } } /** * 图片二维码验证成功之后清空数量 * * @param ip IP地址 */ public static void clearSendSmsCount(String ip) { long currentTime = System.currentTimeMillis(); ipRequestCount.put(ip, 0); ipLastRequestTime.put(ip, currentTime); } // public static void main(String[] args) { // String ip = "192.168.1.1"; // for (int i = 1; i < 50; i++) { // if (canSendSms(ip)) { // System.out.println("Send SMS successfully"); // } else { // //System.out.println("Exceed SMS limit for IP " + ip); // } // } // // System.out.println(ipLastRequestTime); // System.out.println(ipRequestCount); // System.out.println(ipBlacklist); // } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/PmsUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/PmsUtil.java
package org.jeecg.common.util; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Date; import java.util.List; /** * @Description: PmsUtil * @author: jeecg-boot */ @Slf4j @Component @Lazy(false) public class PmsUtil { private static String uploadPath; @Value("${jeecg.path.upload:}") public void setUploadPath(String uploadPath) { PmsUtil.uploadPath = uploadPath; } public static String saveErrorTxtByList(List<String> msg, String name) { Date d = new Date(); String saveDir = "logs" + File.separator + DateUtils.yyyyMMdd.get().format(d) + File.separator; String saveFullDir = uploadPath + File.separator + saveDir; File saveFile = new File(saveFullDir); if (!saveFile.exists()) { saveFile.mkdirs(); } name += DateUtils.yyyymmddhhmmss.get().format(d) + Math.round(Math.random() * 10000); String saveFilePath = saveFullDir + name + ".txt"; try { //封装目的地 BufferedWriter bw = new BufferedWriter(new FileWriter(saveFilePath)); //遍历集合 for (String s : msg) { //写数据 if (s.indexOf("_") > 0) { String[] arr = s.split("_"); bw.write("第" + arr[0] + "行:" + arr[1]); } else { bw.write(s); } //bw.newLine(); bw.write("\r\n"); } //释放资源 bw.flush(); bw.close(); } catch (Exception e) { log.info("excel导入生成错误日志文件异常:" + e.getMessage()); } return saveDir + name + ".txt"; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ShiroThreadPoolExecutor.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/ShiroThreadPoolExecutor.java
package org.jeecg.common.util; import org.apache.shiro.SecurityUtils; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.ThreadContext; import java.util.concurrent.*; /** * @date 2025-09-04 * @author scott * * @Description: 支持shiro的API,获取当前登录人方法的线程池 */ public class ShiroThreadPoolExecutor extends ThreadPoolExecutor { public ShiroThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override public void execute(Runnable command) { Subject subject = SecurityUtils.getSubject(); SecurityManager securityManager = SecurityUtils.getSecurityManager(); super.execute(() -> { try { ThreadContext.bind(securityManager); ThreadContext.bind(subject); command.run(); } finally { ThreadContext.unbindSubject(); ThreadContext.unbindSecurityManager(); } }); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/RestDesformUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/RestDesformUtil.java
package org.jeecg.common.util; import com.alibaba.fastjson.JSONObject; import org.jeecg.common.api.vo.Result; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; /** * 通过 RESTful 风格的接口操纵 desform 里的数据 * * @author sunjianlei */ public class RestDesformUtil { private static String domain = null; private static String path = null; static { domain = SpringContextUtils.getDomain(); path = oConvertUtils.getString(SpringContextUtils.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path")); } /** * 查询数据 * * @param desformCode * @param dataId * @param token * @return */ public static Result queryOne(String desformCode, String dataId, String token) { String url = getBaseUrl(desformCode, dataId).toString(); HttpHeaders headers = getHeaders(token); ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.GET, headers, null, null, JSONObject.class); return packageReturn(result); } /** * 新增数据 * * @param desformCode * @param formData * @param token * @return */ public static Result addOne(String desformCode, JSONObject formData, String token) { return addOrEditOne(desformCode, formData, token, HttpMethod.POST); } /** * 修改数据 * * @param desformCode * @param formData * @param token * @return */ public static Result editOne(String desformCode, JSONObject formData, String token) { return addOrEditOne(desformCode, formData, token, HttpMethod.PUT); } private static Result addOrEditOne(String desformCode, JSONObject formData, String token, HttpMethod method) { String url = getBaseUrl(desformCode).toString(); HttpHeaders headers = getHeaders(token); ResponseEntity<JSONObject> result = RestUtil.request(url, method, headers, null, formData, JSONObject.class); return packageReturn(result); } /** * 删除数据 * * @param desformCode * @param dataId * @param token * @return */ public static Result removeOne(String desformCode, String dataId, String token) { String url = getBaseUrl(desformCode, dataId).toString(); HttpHeaders headers = getHeaders(token); ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.DELETE, headers, null, null, JSONObject.class); return packageReturn(result); } private static Result packageReturn(ResponseEntity<JSONObject> result) { if (result.getBody() != null) { return result.getBody().toJavaObject(Result.class); } return Result.error("操作失败"); } private static StringBuilder getBaseUrl() { StringBuilder builder = new StringBuilder(domain).append(path); builder.append("/desform/api"); return builder; } private static StringBuilder getBaseUrl(String desformCode, String dataId) { StringBuilder builder = getBaseUrl(); builder.append("/").append(desformCode); if (dataId != null) { builder.append("/").append(dataId); } return builder; } private static StringBuilder getBaseUrl(String desformCode) { return getBaseUrl(desformCode, null); } private static HttpHeaders getHeaders(String token) { HttpHeaders headers = new HttpHeaders(); String mediaType = MediaType.APPLICATION_JSON_UTF8_VALUE; headers.setContentType(MediaType.parseMediaType(mediaType)); headers.set("Accept", mediaType); headers.set("X-Access-Token", token); return headers; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/IpUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/IpUtils.java
package org.jeecg.common.util; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.constant.CommonConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * IP地址 * * @Author scott * @email jeecgos@163.com * @Date 2019年01月14日 */ public class IpUtils { private static Logger logger = LoggerFactory.getLogger(IpUtils.class); /** * 获取IP地址 * * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 */ public static String getIpAddr(HttpServletRequest request) { String ip = null; try { ip = request.getHeader("x-forwarded-for"); if (StringUtils.isEmpty(ip) || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || ip.length() == 0 ||CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isEmpty(ip) || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isEmpty(ip) || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isEmpty(ip) || CommonConstant.UNKNOWN.equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } catch (Exception e) { logger.error("IPUtils ERROR ", e); } //logger.info("获取客户端 ip:{} ", ip); // 使用代理,则获取第一个IP地址 if (StringUtils.isNotEmpty(ip) && ip.length() > 15) { if (ip.indexOf(",") > 0) { //ip = ip.substring(0, ip.indexOf(",")); String[] ipAddresses = ip.split(","); for (String ipAddress : ipAddresses) { ipAddress = ipAddress.trim(); if (isValidIpAddress(ipAddress)) { return ipAddress; } } } } return ip; } /** * 判断是否是IP格式 * @param ipAddress * @return */ public static boolean isValidIpAddress(String ipAddress) { String ipPattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"; Pattern pattern = Pattern.compile(ipPattern); Matcher matcher = pattern.matcher(ipAddress); return matcher.matches(); } /** * 获取服务器上的ip * @return */ public static String getServerIp(){ InetAddress inetAddress = null; try { inetAddress = InetAddress.getLocalHost(); String ipAddress = inetAddress.getHostAddress(); //System.out.println("IP地址: " + ipAddress); return ipAddress; } catch (UnknownHostException e) { logger.error("获取ip地址失败", e); } return ""; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/superSearch/QueryRuleEnum.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/superSearch/QueryRuleEnum.java
//package org.jeecg.common.util.superSearch; // //import org.jeecg.common.util.oConvertUtils; // ///** // * Query 规则 常量 // * @Author Scott // * @Date 2019年02月14日 // */ //public enum QueryRuleEnum { // // /**查询规则 大于*/ // GT(">","大于"), // /**查询规则 大于等于*/ // GE(">=","大于等于"), // /**查询规则 小于*/ // LT("<","小于"), // /**查询规则 小于等于*/ // LE("<=","小于等于"), // /**查询规则 等于*/ // EQ("=","等于"), // /**查询规则 不等于*/ // NE("!=","不等于"), // /**查询规则 包含*/ // IN("IN","包含"), // /**查询规则 全模糊*/ // LIKE("LIKE","全模糊"), // /**查询规则 左模糊*/ // LEFT_LIKE("LEFT_LIKE","左模糊"), // /**查询规则 右模糊*/ // RIGHT_LIKE("RIGHT_LIKE","右模糊"), // /**查询规则 自定义SQL片段*/ // SQL_RULES("EXTEND_SQL","自定义SQL片段"); // // private String value; // // private String msg; // // QueryRuleEnum(String value, String msg){ // this.value = value; // this.msg = msg; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // public static QueryRuleEnum getByValue(String value){ // if(oConvertUtils.isEmpty(value)) { // return null; // } // for(QueryRuleEnum val :values()){ // if (val.getValue().equals(value)){ // return val; // } // } // return null; // } //}
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/superSearch/QueryRuleVo.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/superSearch/QueryRuleVo.java
//package org.jeecg.common.util.superSearch; // //import lombok.Data; // ///** // * @Description: QueryRuleVo // * @author: jeecg-boot // */ //@Data //public class QueryRuleVo { // // private String field; // private String rule; // private String val; //}
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/superSearch/ObjectParseUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/superSearch/ObjectParseUtil.java
//package org.jeecg.common.util.superSearch; // //import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; // ///** // * 判断类型,追加查询规则 // * // * @Author Scott // * @Date 2019年02月14日 // */ //public class ObjectParseUtil { // // /** // * // * @param queryWrapper QueryWrapper // * @param name 字段名字 // * @param rule 查询规则 // * @param value 查询条件值 // */ // public static void addCriteria(QueryWrapper<?> queryWrapper, String name, QueryRuleEnum rule, Object value) { // if (value == null || rule == null) { // return; // } // switch (rule) { // case GT: // queryWrapper.gt(name, value); // break; // case GE: // queryWrapper.ge(name, value); // break; // case LT: // queryWrapper.lt(name, value); // break; // case LE: // queryWrapper.le(name, value); // break; // case EQ: // queryWrapper.eq(name, value); // break; // case NE: // queryWrapper.ne(name, value); // break; // case IN: // queryWrapper.in(name, (Object[]) value); // break; // case LIKE: // queryWrapper.like(name, value); // break; // case LEFT_LIKE: // queryWrapper.likeLeft(name, value); // break; // case RIGHT_LIKE: // queryWrapper.likeRight(name, value); // break; // default: // break; // } // } // //}
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/filter/SsrfFileTypeFilter.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/filter/SsrfFileTypeFilter.java
package org.jeecg.common.util.filter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.exception.JeecgBootException; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * @Description: 校验文件敏感后缀 * @author: lsq * @date: 2023年09月12日 15:29 */ @Slf4j public class SsrfFileTypeFilter { /** * 允许操作文件类型白名单 */ private final static List<String> FILE_TYPE_WHITE_LIST = new ArrayList<>(); /**初始化文件头类型,不够的自行补充*/ final static HashMap<String, String> FILE_TYPE_MAP = new HashMap<>(); static { //图片文件 FILE_TYPE_WHITE_LIST.add("jpg"); FILE_TYPE_WHITE_LIST.add("jpeg"); FILE_TYPE_WHITE_LIST.add("png"); FILE_TYPE_WHITE_LIST.add("gif"); FILE_TYPE_WHITE_LIST.add("bmp"); FILE_TYPE_WHITE_LIST.add("svg"); FILE_TYPE_WHITE_LIST.add("ico"); FILE_TYPE_WHITE_LIST.add("heic"); //文本文件 FILE_TYPE_WHITE_LIST.add("txt"); FILE_TYPE_WHITE_LIST.add("doc"); FILE_TYPE_WHITE_LIST.add("docx"); FILE_TYPE_WHITE_LIST.add("pdf"); FILE_TYPE_WHITE_LIST.add("csv"); // FILE_TYPE_WHITE_LIST.add("xml"); FILE_TYPE_WHITE_LIST.add("md"); //音视频文件 FILE_TYPE_WHITE_LIST.add("mp4"); FILE_TYPE_WHITE_LIST.add("avi"); FILE_TYPE_WHITE_LIST.add("mov"); FILE_TYPE_WHITE_LIST.add("wmv"); FILE_TYPE_WHITE_LIST.add("mp3"); FILE_TYPE_WHITE_LIST.add("wav"); //表格文件 FILE_TYPE_WHITE_LIST.add("xls"); FILE_TYPE_WHITE_LIST.add("xlsx"); //压缩文件 FILE_TYPE_WHITE_LIST.add("zip"); FILE_TYPE_WHITE_LIST.add("rar"); FILE_TYPE_WHITE_LIST.add("7z"); FILE_TYPE_WHITE_LIST.add("tar"); //app文件后缀 FILE_TYPE_WHITE_LIST.add("apk"); FILE_TYPE_WHITE_LIST.add("wgt"); //幻灯片文件后缀 FILE_TYPE_WHITE_LIST.add("ppt"); FILE_TYPE_WHITE_LIST.add("pptx"); //设置禁止文件的头部标记 FILE_TYPE_MAP.put("3c25402070616765206c", "jsp"); FILE_TYPE_MAP.put("3c3f7068700a0a2f2a2a0a202a205048", "php"); FILE_TYPE_MAP.put("cafebabe0000002e0041", "class"); FILE_TYPE_MAP.put("494e5345525420494e54", "sql"); /* fileTypeMap.put("ffd8ffe000104a464946", "jpg"); fileTypeMap.put("89504e470d0a1a0a0000", "png"); fileTypeMap.put("47494638396126026f01", "gif"); fileTypeMap.put("49492a00227105008037", "tif"); fileTypeMap.put("424d228c010000000000", "bmp"); fileTypeMap.put("424d8240090000000000", "bmp"); fileTypeMap.put("424d8e1b030000000000", "bmp"); fileTypeMap.put("41433130313500000000", "dwg"); fileTypeMap.put("3c21444f435459504520", "html"); fileTypeMap.put("3c21646f637479706520", "htm"); fileTypeMap.put("48544d4c207b0d0a0942", "css"); fileTypeMap.put("696b2e71623d696b2e71", "js"); fileTypeMap.put("7b5c727466315c616e73", "rtf"); fileTypeMap.put("38425053000100000000", "psd"); fileTypeMap.put("46726f6d3a203d3f6762", "eml"); fileTypeMap.put("d0cf11e0a1b11ae10000", "doc"); fileTypeMap.put("5374616E64617264204A", "mdb"); fileTypeMap.put("252150532D41646F6265", "ps"); fileTypeMap.put("255044462d312e350d0a", "pdf"); fileTypeMap.put("2e524d46000000120001", "rmvb"); fileTypeMap.put("464c5601050000000900", "flv"); fileTypeMap.put("00000020667479706d70", "mp4"); fileTypeMap.put("49443303000000002176", "mp3"); fileTypeMap.put("000001ba210001000180", "mpg"); fileTypeMap.put("3026b2758e66cf11a6d9", "wmv"); fileTypeMap.put("52494646e27807005741", "wav"); fileTypeMap.put("52494646d07d60074156", "avi"); fileTypeMap.put("4d546864000000060001", "mid"); fileTypeMap.put("504b0304140000000800", "zip"); fileTypeMap.put("526172211a0700cf9073", "rar"); fileTypeMap.put("235468697320636f6e66", "ini"); fileTypeMap.put("504b03040a0000000000", "jar"); fileTypeMap.put("4d5a9000030000000400", "exe"); fileTypeMap.put("3c25402070616765206c", "jsp"); fileTypeMap.put("4d616e69666573742d56", "mf"); fileTypeMap.put("3c3f786d6c2076657273", "xml"); fileTypeMap.put("494e5345525420494e54", "sql"); fileTypeMap.put("7061636b616765207765", "java"); fileTypeMap.put("406563686f206f66660d", "bat"); fileTypeMap.put("1f8b0800000000000000", "gz"); fileTypeMap.put("6c6f67346a2e726f6f74", "properties"); fileTypeMap.put("cafebabe0000002e0041", "class"); fileTypeMap.put("49545346030000006000", "chm"); fileTypeMap.put("04000000010000001300", "mxp"); fileTypeMap.put("504b0304140006000800", "docx"); fileTypeMap.put("6431303a637265617465", "torrent"); fileTypeMap.put("6D6F6F76", "mov"); fileTypeMap.put("FF575043", "wpd"); fileTypeMap.put("CFAD12FEC5FD746F", "dbx"); fileTypeMap.put("2142444E", "pst"); fileTypeMap.put("AC9EBD8F", "qdf"); fileTypeMap.put("E3828596", "pwl"); fileTypeMap.put("2E7261FD", "ram");*/ } /** * @param fileName * @return String * @description 通过文件后缀名获取文件类型 */ private static String getFileTypeBySuffix(String fileName) { return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); } /** * 下载文件类型过滤 * * @param filePath */ public static void checkDownloadFileType(String filePath) throws IOException { //文件后缀 String suffix = getFileTypeBySuffix(filePath); log.debug(" 【文件下载校验】文件后缀 suffix: {}", suffix); boolean isAllowExtension = FILE_TYPE_WHITE_LIST.contains(suffix.toLowerCase()); //是否允许下载的文件 if (!isAllowExtension) { throw new JeecgBootException("下载失败,存在非法文件类型:" + suffix); } } /** * 上传文件类型过滤 * * @param file */ public static void checkUploadFileType(MultipartFile file) throws Exception { checkUploadFileType(file, null); } /** * 上传文件类型过滤 * * @param file */ public static void checkUploadFileType(MultipartFile file, String customPath) throws Exception { //1. 路径安全校验 validatePathSecurity(customPath); //2. 校验文件后缀和头 String suffix = getFileType(file, customPath); log.info("【文件上传校验】文件后缀 suffix: {},customPath:{}", suffix, customPath); boolean isAllowExtension = FILE_TYPE_WHITE_LIST.contains(suffix.toLowerCase()); //是否允许下载的文件 if (!isAllowExtension) { throw new JeecgBootException("上传失败,存在非法文件类型:" + suffix); } } /** * 通过读取文件头部获得文件类型 * * @param file * @return 文件类型 * @throws Exception */ private static String getFileType(MultipartFile file, String customPath) throws Exception { // 代码逻辑说明: [issue/4672]方法造成的文件被占用,注释掉此方法tomcat就能自动清理掉临时文件 String fileExtendName = null; InputStream is = null; try { //is = new FileInputStream(file); is = file.getInputStream(); byte[] b = new byte[10]; is.read(b, 0, b.length); String fileTypeHex = String.valueOf(bytesToHexString(b)); Iterator<String> keyIter = FILE_TYPE_MAP.keySet().iterator(); while (keyIter.hasNext()) { String key = keyIter.next(); // 验证前5个字符比较 if (key.toLowerCase().startsWith(fileTypeHex.toLowerCase().substring(0, 5)) || fileTypeHex.toLowerCase().substring(0, 5).startsWith(key.toLowerCase())) { fileExtendName = FILE_TYPE_MAP.get(key); break; } } log.debug("-----获取到的指定文件类型------"+fileExtendName); // 如果不是上述类型,则判断扩展名 if (StringUtils.isBlank(fileExtendName)) { String fileName = file.getOriginalFilename(); // 如果无扩展名,则直接返回空串 if (-1 == fileName.indexOf(".")) { return ""; } // 如果有扩展名,则返回扩展名 return getFileTypeBySuffix(fileName); } is.close(); return fileExtendName; } catch (Exception e) { log.error(e.getMessage(), e); return ""; }finally { if (is != null) { is.close(); } } } /** * 获得文件头部字符串 * * @param src * @return */ private static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); } /** * 路径安全校验 */ private static void validatePathSecurity(String customPath) throws JeecgBootException { if (customPath == null || customPath.trim().isEmpty()) { return; } // 统一分隔符为 / String normalized = customPath.replace("\\", "/"); // 1. 防止路径遍历攻击 if (normalized.contains("..") || normalized.contains("~")) { throw new JeecgBootException("上传业务路径包含非法字符!"); } // 2. 限制路径深度 int depth = normalized.split("/").length; if (depth > 5) { throw new JeecgBootException("上传业务路径深度超出限制!"); } // 3. 限制字符集(只允许字母、数字、下划线、横线、斜杠) if (!normalized.matches("^[a-zA-Z0-9/_-]+$")) { throw new JeecgBootException("上传业务路径包含非法字符!"); } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/filter/StrAttackFilter.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/filter/StrAttackFilter.java
package org.jeecg.common.util.filter; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * 文件上传字符串过滤特殊字符 * @author: jeecg-boot */ public class StrAttackFilter { public static String filter(String str) throws PatternSyntaxException { // 清除掉所有特殊字符 String regEx = "[`_《》~!@#$%^&*()+=|{}':;',\\[\\].<>?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); } // public static void main(String[] args) { // String filter = filter("@#jeecg/《》【bo】¥%……&*(o))))!@t<>,.,/?'\'~~`"); // System.out.println(filter); // } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/encryption/AesEncryptUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/encryption/AesEncryptUtil.java
package org.jeecg.common.util.encryption; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.lang.codec.Base64; import org.jeecg.common.util.oConvertUtils; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; /** * AES 工具 (兼容历史 NoPadding + 新 PKCS5Padding) */ @Slf4j public class AesEncryptUtil { private static final String KEY = EncryptedString.key; private static final String IV = EncryptedString.iv; /* -------- 新版:CBC + PKCS5Padding (与前端 CryptoJS Pkcs7 兼容) -------- */ private static String decryptPkcs5(String cipherBase64) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec ks = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, ks, ivSpec); byte[] plain = cipher.doFinal(Base64.decode(cipherBase64)); return new String(plain, StandardCharsets.UTF_8); } /* -------- 旧版:CBC + NoPadding (手工补 0) -------- */ private static String decryptLegacyNoPadding(String cipherBase64) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec ks = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, ks, ivSpec); byte[] data = cipher.doFinal(Base64.decode(cipherBase64)); return new String(data, StandardCharsets.UTF_8) .replace("\u0000",""); // 旧填充 0 } /* -------- 兼容入口:登录使用 -------- */ public static String resolvePassword(String input){ if(oConvertUtils.isEmpty(input)){ return input; } // 1. 先尝试新版 try{ String p = decryptPkcs5(input); return clean(p); }catch(Exception ignore){ //log.debug("【AES解密】Password not AES PKCS5 cipher, try legacy."); } // 2. 回退旧版 try{ String legacy = decryptLegacyNoPadding(input); return clean(legacy); }catch(Exception e){ log.debug("【AES解密】Password not AES cipher, raw used."); } // 3. 视为明文 return input; } /* -------- 可选:统一清理尾部不可见控制字符 -------- */ private static String clean(String s){ if(s==null) return null; // 去除结尾控制符/空白(不影响中间合法空格) return s.replaceAll("[\\p{Cntrl}]+","").trim(); } /* -------- 若仍需要旧接口,可保留 (不建议再用于新前端) -------- */ @Deprecated public static String desEncrypt(String data) throws Exception { return decryptLegacyNoPadding(data); } /* 加密(若前端不再使用,可忽略;保留旧实现避免影响历史) */ @Deprecated public static String encrypt(String data) throws Exception { try{ Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength += (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivspec = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return Base64.encodeToString(encrypted); }catch(Exception e){ throw new IllegalStateException("legacy encrypt error", e); } } // public static void main(String[] args) throws Exception { // // 前端 CBC/Pkcs7 密文测试 // String frontCipher = encrypt("sa"); // 仅验证管道是否可用(旧方式) // System.out.println(resolvePassword(frontCipher)); // } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/encryption/EncryptedString.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/encryption/EncryptedString.java
package org.jeecg.common.util.encryption; import lombok.Data; /** * @Description: EncryptedString * @author: jeecg-boot */ @Data public class EncryptedString { /** * 长度为16个字符 */ public static String key = "1234567890adbcde"; /** * 长度为16个字符 */ public static String iv = "1234567890hjlkew"; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/DbTypeUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/DbTypeUtils.java
package org.jeecg.common.util.dynamic.db; import com.baomidou.mybatisplus.annotation.DbType; import org.jeecg.common.constant.DataBaseConstant; import java.util.HashMap; import java.util.Map; /** * 数据库类型判断 * 【有些数据库引擎是一样的,以达到复用目的】 * @author: jeecg-boot */ public class DbTypeUtils { public static Map<String, String> dialectMap = new HashMap<String, String>(); static{ dialectMap.put("mysql", "org.hibernate.dialect.MySQL5InnoDBDialect"); // mariadb数据库 1 -- dialectMap.put("mariadb", "org.hibernate.dialect.MariaDBDialect"); //oracle数据库 1 dialectMap.put("oracle", "org.hibernate.dialect.OracleDialect"); // TODO 没找到不确定 dialectMap.put("oracle12c", "org.hibernate.dialect.OracleDialect"); // db2数据库 1xx dialectMap.put("db2", "org.hibernate.dialect.DB2390Dialect"); // H2数据库 dialectMap.put("h2", "org.hibernate.dialect.HSQLDialect"); // HSQL数据库 1 dialectMap.put("hsql", "org.hibernate.dialect.HSQLDialect"); //SQLite数据库 应用平台mobile dialectMap.put("sqlite", "org.jeecg.modules.online.config.dialect.SQLiteDialect"); //PostgreSQL数据库1 -- dialectMap.put("postgresql", "org.hibernate.dialect.PostgreSQLDialect"); dialectMap.put("sqlserver2005", "org.hibernate.dialect.SQLServer2005Dialect"); //sqlserver数据库1 dialectMap.put("sqlserver", "org.hibernate.dialect.SQLServerDialect"); //达梦数据库 [国产] 1-- dialectMap.put("dm", "org.hibernate.dialect.DmDialect"); //虚谷数据库 dialectMap.put("xugu", "org.hibernate.dialect.HSQLDialect"); //人大金仓 [国产] 1 dialectMap.put("kingbasees", "org.hibernate.dialect.PostgreSQLDialect"); // Phoenix HBase数据库 dialectMap.put("phoenix", "org.hibernate.dialect.HSQLDialect"); // Gauss 数据库 dialectMap.put("zenith", "org.hibernate.dialect.PostgreSQLDialect"); //阿里云PolarDB dialectMap.put("clickhouse", "org.hibernate.dialect.MySQLDialect"); // 南大通用数据库 TODO 没找到不确定 dialectMap.put("gbase", "org.hibernate.dialect.PostgreSQLDialect"); //神通数据库 [国产] TODO 没找到不确定 dialectMap.put("oscar", "org.hibernate.dialect.PostgreSQLDialect"); //Sybase ASE 数据库 dialectMap.put("sybase", "org.hibernate.dialect.SybaseDialect"); dialectMap.put("oceanbase", "org.hibernate.dialect.PostgreSQLDialect"); dialectMap.put("Firebird", "org.hibernate.dialect.FirebirdDialect"); //瀚高数据库 dialectMap.put("highgo", "org.hibernate.dialect.HSQLDialect"); dialectMap.put("other", "org.hibernate.dialect.PostgreSQLDialect"); } public static boolean dbTypeIsMySql(DbType dbType) { return dbTypeIf(dbType, DbType.MYSQL, DbType.MARIADB, DbType.CLICK_HOUSE, DbType.SQLITE); } public static boolean dbTypeIsOracle(DbType dbType) { return dbTypeIf(dbType, DbType.ORACLE, DbType.ORACLE_12C, DbType.DM); } /** * 是否是达梦 */ public static boolean dbTypeIsDm(DbType dbType) { return dbTypeIf(dbType, DbType.DM); } public static boolean dbTypeIsSqlServer(DbType dbType) { return dbTypeIf(dbType, DbType.SQL_SERVER, DbType.SQL_SERVER2005); } public static boolean dbTypeIsPostgre(DbType dbType) { return dbTypeIf(dbType, DbType.POSTGRE_SQL, DbType.KINGBASE_ES, DbType.GAUSS); } /** * 根据枚举类 获取数据库类型的字符串 * @param dbType * @return */ public static String getDbTypeString(DbType dbType){ if(DbType.DB2.equals(dbType)){ return DataBaseConstant.DB_TYPE_DB2; }else if(DbType.HSQL.equals(dbType)){ return DataBaseConstant.DB_TYPE_HSQL; }else if(dbTypeIsOracle(dbType)){ return DataBaseConstant.DB_TYPE_ORACLE; }else if(dbTypeIsSqlServer(dbType)){ return DataBaseConstant.DB_TYPE_SQLSERVER; }else if(dbTypeIsPostgre(dbType)){ return DataBaseConstant.DB_TYPE_POSTGRESQL; } return DataBaseConstant.DB_TYPE_MYSQL; } /** * 根据枚举类 获取数据库方言字符串 * @param dbType * @return */ public static String getDbDialect(DbType dbType){ return dialectMap.get(dbType.getDb()); } /** * 判断数据库类型 */ public static boolean dbTypeIf(DbType dbType, DbType... correctTypes) { for (DbType type : correctTypes) { if (type.equals(dbType)) { return true; } } return false; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/FreemarkerParseFactory.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/FreemarkerParseFactory.java
package org.jeecg.common.util.dynamic.db; import freemarker.cache.StringTemplateLoader; import freemarker.core.ParseException; import freemarker.core.TemplateClassResolver; import freemarker.template.Configuration; import freemarker.template.Template; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.jeecg.common.constant.DataBaseConstant; import org.jeecg.common.constant.SymbolConstant; import org.jeecgframework.codegenerate.generate.util.SimpleFormat; import java.io.StringWriter; import java.util.Map; import java.util.regex.Pattern; /** * @author 赵俊夫 * @version V1.0 * @Title:FreemarkerHelper * @description:Freemarker引擎协助类 * @date Jul 5, 2013 2:58:29 PM */ @Slf4j public class FreemarkerParseFactory { private static final String ENCODE = "utf-8"; /** * 参数格式化工具类 */ private static final String MINI_DAO_FORMAT = "DaoFormat"; /** * 文件缓存 */ private static final Configuration TPL_CONFIG = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); /** * SQL 缓存 */ private static final Configuration SQL_CONFIG = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); /**使用内嵌的(?ms)打开单行和多行模式*/ private final static Pattern NOTES_PATTERN = Pattern .compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$"); static { TPL_CONFIG.setClassForTemplateLoading(new FreemarkerParseFactory().getClass(), "/"); TPL_CONFIG.setNumberFormat("0.#####################"); SQL_CONFIG.setTemplateLoader(stringTemplateLoader); SQL_CONFIG.setNumberFormat("0.#####################"); //classic_compatible设置,解决报空指针错误 SQL_CONFIG.setClassicCompatible(true); // 解决freemarker模板注入问题 禁止解析ObjectConstructor,Execute和freemarker.template.utility.JythonRuntime。 //https://ackcent.com/in-depth-freemarker-template-injection/ TPL_CONFIG.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); SQL_CONFIG.setNewBuiltinClassResolver(TemplateClassResolver.SAFER_RESOLVER); } /** * 判断模板是否存在 * * @throws Exception */ public static boolean isExistTemplate(String tplName) throws Exception { try { Template mytpl = TPL_CONFIG.getTemplate(tplName, "UTF-8"); if (mytpl == null) { return false; } } catch (Exception e) { // 代码逻辑说明: 解决问题 - 错误提示sql文件不存在,实际问题是sql freemarker用法错误----- if (e instanceof ParseException) { log.error(e.getMessage(), e.fillInStackTrace()); throw new Exception(e); } log.debug("----isExistTemplate----" + e.toString()); return false; } return true; } /** * 解析ftl模板 * * @param tplName 模板名 * @param paras 参数 * @return */ public static String parseTemplate(String tplName, Map<String, Object> paras) { try { log.debug(" minidao sql templdate : " + tplName); StringWriter swriter = new StringWriter(); Template mytpl = TPL_CONFIG.getTemplate(tplName, ENCODE); if (paras.containsKey(MINI_DAO_FORMAT)) { throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!"); } paras.put(MINI_DAO_FORMAT, new SimpleFormat()); mytpl.process(paras, swriter); String sql = getSqlText(swriter.toString()); paras.remove(MINI_DAO_FORMAT); return sql; } catch (Exception e) { log.error(e.getMessage(), e.fillInStackTrace()); log.error("发送一次的模板key:{ " + tplName + " }"); //System.err.println(e.getMessage()); //System.err.println("模板名:{ "+ tplName +" }"); throw new RuntimeException("解析SQL模板异常"); } } /** * 解析ftl * * @param tplContent 模板内容 * @param paras 参数 * @return String 模板解析后内容 */ public static String parseTemplateContent(String tplContent,Map<String, Object> paras) { return parseTemplateContent(tplContent, paras, false); } public static String parseTemplateContent(String tplContent, Map<String, Object> paras, boolean keepSpace) { try { String sqlUnderline="sql_"; StringWriter swriter = new StringWriter(); if (stringTemplateLoader.findTemplateSource(sqlUnderline + tplContent.hashCode()) == null) { stringTemplateLoader.putTemplate(sqlUnderline + tplContent.hashCode(), tplContent); } Template mytpl = SQL_CONFIG.getTemplate(sqlUnderline + tplContent.hashCode(), ENCODE); if (paras.containsKey(MINI_DAO_FORMAT)) { throw new RuntimeException("DaoFormat 是 minidao 保留关键字,不允许使用 ,请更改参数定义!"); } paras.put(MINI_DAO_FORMAT, new SimpleFormat()); mytpl.process(paras, swriter); String sql = getSqlText(swriter.toString(), keepSpace); paras.remove(MINI_DAO_FORMAT); return sql; } catch (Exception e) { log.error(e.getMessage(), e.fillInStackTrace()); log.error("发送一次的模板key:{ " + tplContent + " }"); //System.err.println(e.getMessage()); //System.err.println("模板内容:{ "+ tplContent +" }"); throw new RuntimeException("解析SQL模板异常"); } } /** * 除去无效字段,去掉注释 不然批量处理可能报错 去除无效的等于 */ private static String getSqlText(String sql) { return getSqlText(sql, false); } private static String getSqlText(String sql, boolean keepSpace) { // 将注释替换成"" sql = NOTES_PATTERN.matcher(sql).replaceAll(""); if (!keepSpace) { sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ") .replaceAll("\\s{1,}", " ").trim(); } // 去掉 最后是 where这样的问题 //where空格 "where " String whereSpace = DataBaseConstant.SQL_WHERE+" "; //"where and" String whereAnd = DataBaseConstant.SQL_WHERE+" and"; //", where" String commaWhere = SymbolConstant.COMMA+" "+DataBaseConstant.SQL_WHERE; //", " String commaSpace = SymbolConstant.COMMA + " "; if (sql.endsWith(DataBaseConstant.SQL_WHERE) || sql.endsWith(whereSpace)) { sql = sql.substring(0, sql.lastIndexOf("where")); } // 去掉where and 这样的问题 int index = 0; while ((index = StringUtils.indexOfIgnoreCase(sql, whereAnd, index)) != -1) { sql = sql.substring(0, index + 5) + sql.substring(index + 9, sql.length()); } // 去掉 , where 这样的问题 index = 0; while ((index = StringUtils.indexOfIgnoreCase(sql, commaWhere, index)) != -1) { sql = sql.substring(0, index) + sql.substring(index + 1, sql.length()); } // 去掉 最后是 ,这样的问题 if (sql.endsWith(SymbolConstant.COMMA) || sql.endsWith(commaSpace)) { sql = sql.substring(0, sql.lastIndexOf(",")); } return sql; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/DynamicDBUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/DynamicDBUtil.java
package org.jeecg.common.util.dynamic.db; import com.alibaba.druid.pool.DruidDataSource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.system.vo.DynamicDataSourceModel; import org.jeecg.common.util.ReflectHelper; import org.jeecg.common.util.oConvertUtils; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import javax.sql.DataSource; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Spring JDBC 实时数据库访问 * * @author chenguobin * @version 1.0 * @date 2014-09-05 */ @Slf4j public class DynamicDBUtil { /** * 获取数据源【最底层方法,不要随便调用】 * * @param dbSource * @return */ private static DruidDataSource getJdbcDataSource(final DynamicDataSourceModel dbSource) { DruidDataSource dataSource = new DruidDataSource(); String driverClassName = dbSource.getDbDriver(); String url = dbSource.getDbUrl(); // url配置成 “123” 会触发Druid死循环,一直去重复尝试连接 if (oConvertUtils.isEmpty(url) || !url.toLowerCase().startsWith("jdbc:")) { throw new JeecgBootException("数据源URL配置格式不正确!"); } String dbUser = dbSource.getDbUsername(); String dbPassword = dbSource.getDbPassword(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); //dataSource.setValidationQuery("SELECT 1 FROM DUAL"); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setTestOnReturn(false); dataSource.setBreakAfterAcquireFailure(true); //设置超时时间60秒 dataSource.setLoginTimeout(60); dataSource.setConnectionErrorRetryAttempts(0); dataSource.setUsername(dbUser); dataSource.setMaxWait(30000); dataSource.setPassword(dbPassword); log.info("******************************************"); log.info("* *"); log.info("*====【"+dbSource.getCode()+"】=====Druid连接池已启用 ====*"); log.info("* *"); log.info("******************************************"); return dataSource; } /** * 通过 dbKey ,获取数据源 * * @param dbKey * @return */ public static DruidDataSource getDbSourceByDbKey(final String dbKey) { //获取多数据源配置 DynamicDataSourceModel dbSource = DataSourceCachePool.getCacheDynamicDataSourceModel(dbKey); //先判断缓存中是否存在数据库链接 DruidDataSource cacheDbSource = DataSourceCachePool.getCacheBasicDataSource(dbKey); if (cacheDbSource != null && !cacheDbSource.isClosed()) { log.debug("--------getDbSourceBydbKey------------------从缓存中获取DB连接-------------------"); return cacheDbSource; } else { DruidDataSource dataSource = getJdbcDataSource(dbSource); if(dataSource!=null && dataSource.isEnable()){ // 【TV360X-2060】设置超时时间 6秒 dataSource.setMaxWait(6000); DataSourceCachePool.putCacheBasicDataSource(dbKey, dataSource); }else{ throw new JeecgBootException("动态数据源连接失败,dbKey:"+dbKey); } log.info("--------getDbSourceBydbKey------------------创建DB数据库连接-------------------"); return dataSource; } } /** * 关闭数据库连接池 * * @param dbKey * @return */ public static void closeDbKey(final String dbKey) { DruidDataSource dataSource = getDbSourceByDbKey(dbKey); try { if (dataSource != null && !dataSource.isClosed()) { dataSource.getConnection().commit(); dataSource.getConnection().close(); dataSource.close(); DataSourceCachePool.removeCache(dbKey); } } catch (SQLException e) { log.warn(e.getMessage(), e); } } private static JdbcTemplate getJdbcTemplate(String dbKey) { DruidDataSource dataSource = getDbSourceByDbKey(dbKey); return new JdbcTemplate(dataSource); } /** * 根据数据源获取NamedParameterJdbcTemplate * @param dbKey * @return */ private static NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(String dbKey) { DruidDataSource dataSource = getDbSourceByDbKey(dbKey); return new NamedParameterJdbcTemplate(dataSource); } /** * Executes the SQL statement in this <code>PreparedStatement</code> object, * which must be an SQL Data Manipulation Language (DML) statement, such as <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code>; or an SQL statement that returns nothing, * such as a DDL statement. */ public static int update(final String dbKey, String sql, Object... param) { int effectCount; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); if (ArrayUtils.isEmpty(param)) { effectCount = jdbcTemplate.update(sql); } else { effectCount = jdbcTemplate.update(sql, param); } return effectCount; } /** * 支持miniDao语法操作的Update * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static int updateByHash(final String dbKey, String sql, HashMap<String, Object> data) { int effectCount; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); //根据模板获取sql sql = FreemarkerParseFactory.parseTemplateContent(sql, data); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); effectCount = namedParameterJdbcTemplate.update(sql, data); return effectCount; } public static Object findOne(final String dbKey, String sql, Object... param) { List<Map<String, Object>> list; list = findList(dbKey, sql, param); if (oConvertUtils.listIsEmpty(list)) { log.error("Except one, but not find actually"); return null; } if (list.size() > 1) { log.error("Except one, but more than one actually"); } return list.get(0); } /** * 支持miniDao语法操作的查询 返回HashMap * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static Object findOneByHash(final String dbKey, String sql, HashMap<String, Object> data) { List<Map<String, Object>> list; list = findListByHash(dbKey, sql, data); if (oConvertUtils.listIsEmpty(list)) { log.error("Except one, but not find actually"); } if (list.size() > 1) { log.error("Except one, but more than one actually"); } return list.get(0); } /** * 直接sql查询 根据clazz返回单个实例 * * @param dbKey 数据源标识 * @param sql 执行sql语句 * @param clazz 返回实例的Class * @param param * @return */ @SuppressWarnings("unchecked") public static <T> Object findOne(final String dbKey, String sql, Class<T> clazz, Object... param) { Map<String, Object> map = (Map<String, Object>) findOne(dbKey, sql, param); return ReflectHelper.setAll(clazz, map); } /** * 支持miniDao语法操作的查询 返回单个实例 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 返回实例的Class * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ @SuppressWarnings("unchecked") public static <T> Object findOneByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { Map<String, Object> map = (Map<String, Object>) findOneByHash(dbKey, sql, data); return ReflectHelper.setAll(clazz, map); } public static List<Map<String, Object>> findList(final String dbKey, String sql, Object... param) { List<Map<String, Object>> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); if (ArrayUtils.isEmpty(param)) { list = jdbcTemplate.queryForList(sql); } else { list = jdbcTemplate.queryForList(sql, param); } return list; } /** * 查询数量 * @param dbKey * @param sql * @param param * @return */ public static Map<String, Object> queryCount(String dbKey, String sql, Map<String, Object> param){ NamedParameterJdbcTemplate npJdbcTemplate = getNamedParameterJdbcTemplate(dbKey); return npJdbcTemplate.queryForMap(sql, param); } /** * 查询列表数据 * @param dbKey * @param sql * @param param * @return */ public static List<Map<String, Object>> findListByNamedParam(final String dbKey, String sql, Map<String, Object> param) { NamedParameterJdbcTemplate npJdbcTemplate = getNamedParameterJdbcTemplate(dbKey); List<Map<String, Object>> list = npJdbcTemplate.queryForList(sql, param); return list; } /** * 支持miniDao语法操作的查询 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static List<Map<String, Object>> findListByHash(final String dbKey, String sql, HashMap<String, Object> data) { List<Map<String, Object>> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); //根据模板获取sql sql = FreemarkerParseFactory.parseTemplateContent(sql, data); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); list = namedParameterJdbcTemplate.queryForList(sql, data); return list; } /** * 此方法只能返回单列,不能返回实体类 * @param dbKey 数据源的key * @param sql sal * @param clazz 类 * @param param 参数 * @param <T> * @return */ public static <T> List<T> findList(final String dbKey, String sql, Class<T> clazz, Object... param) { List<T> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); if (ArrayUtils.isEmpty(param)) { list = jdbcTemplate.queryForList(sql, clazz); } else { list = jdbcTemplate.queryForList(sql, clazz, param); } return list; } /** * 支持miniDao语法操作的查询 返回单列数据list * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 类型Long、String等 * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { List<T> list; JdbcTemplate jdbcTemplate = getJdbcTemplate(dbKey); //根据模板获取sql sql = FreemarkerParseFactory.parseTemplateContent(sql, data); NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()); list = namedParameterJdbcTemplate.queryForList(sql, data, clazz); return list; } /** * 直接sql查询 返回实体类列表 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持 minidao 语法逻辑 * @param clazz 返回实体类列表的class * @param param sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListEntities(final String dbKey, String sql, Class<T> clazz, Object... param) { List<Map<String, Object>> queryList = findList(dbKey, sql, param); return ReflectHelper.transList2Entrys(queryList, clazz); } /** * 支持miniDao语法操作的查询 返回实体类列表 * * @param dbKey 数据源标识 * @param sql 执行sql语句,sql支持minidao语法逻辑 * @param clazz 返回实体类列表的class * @param data sql语法中需要判断的数据及sql拼接注入中需要的数据 * @return */ public static <T> List<T> findListEntitiesByHash(final String dbKey, String sql, Class<T> clazz, HashMap<String, Object> data) { List<Map<String, Object>> queryList = findListByHash(dbKey, sql, data); return ReflectHelper.transList2Entrys(queryList, clazz); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/DataSourceCachePool.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/dynamic/db/DataSourceCachePool.java
package org.jeecg.common.util.dynamic.db; import com.alibaba.druid.pool.DruidDataSource; import org.jeecg.common.api.CommonAPI; import org.jeecg.common.constant.CacheConstant; import org.jeecg.common.system.vo.DynamicDataSourceModel; import org.jeecg.common.util.SpringContextUtils; import org.springframework.data.redis.core.RedisTemplate; import java.util.HashMap; import java.util.Map; /** * 数据源缓存池 * @author: jeecg-boot */ public class DataSourceCachePool { /** 数据源连接池缓存【本地 class缓存 - 不支持分布式】 */ private static Map<String, DruidDataSource> dbSources = new HashMap<>(); private static RedisTemplate<String, Object> redisTemplate; private static RedisTemplate<String, Object> getRedisTemplate() { if (redisTemplate == null) { redisTemplate = (RedisTemplate<String, Object>) SpringContextUtils.getBean("redisTemplate"); } return redisTemplate; } /** * 获取多数据源缓存 * * @param dbKey * @return */ public static DynamicDataSourceModel getCacheDynamicDataSourceModel(String dbKey) { String redisCacheKey = CacheConstant.SYS_DYNAMICDB_CACHE + dbKey; if (getRedisTemplate().hasKey(redisCacheKey)) { return (DynamicDataSourceModel) getRedisTemplate().opsForValue().get(redisCacheKey); } CommonAPI commonApi = SpringContextUtils.getBean(CommonAPI.class); DynamicDataSourceModel dbSource = commonApi.getDynamicDbSourceByCode(dbKey); if (dbSource != null) { getRedisTemplate().opsForValue().set(redisCacheKey, dbSource); } return dbSource; } public static DruidDataSource getCacheBasicDataSource(String dbKey) { return dbSources.get(dbKey); } /** * put 数据源缓存 * * @param dbKey * @param db */ public static void putCacheBasicDataSource(String dbKey, DruidDataSource db) { dbSources.put(dbKey, db); } /** * 清空数据源缓存 */ public static void cleanAllCache() { //关闭数据源连接 for(Map.Entry<String, DruidDataSource> entry : dbSources.entrySet()){ String dbkey = entry.getKey(); DruidDataSource druidDataSource = entry.getValue(); if(druidDataSource!=null && druidDataSource.isEnable()){ druidDataSource.close(); } //清空redis缓存 getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbkey); } //清空缓存 dbSources.clear(); } public static void removeCache(String dbKey) { //关闭数据源连接 DruidDataSource druidDataSource = dbSources.get(dbKey); if(druidDataSource!=null && druidDataSource.isEnable()){ druidDataSource.close(); } //清空redis缓存 getRedisTemplate().delete(CacheConstant.SYS_DYNAMICDB_CACHE + dbKey); //清空缓存 dbSources.remove(dbKey); } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/sqlparse/JSqlParserUtils.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/sqlparse/JSqlParserUtils.java
//package org.jeecg.common.util.sqlparse; // //import lombok.extern.slf4j.Slf4j; //import net.sf.jsqlparser.JSQLParserException; //import net.sf.jsqlparser.expression.*; //import net.sf.jsqlparser.parser.CCJSqlParserManager; //import net.sf.jsqlparser.schema.Column; //import net.sf.jsqlparser.schema.Table; //import net.sf.jsqlparser.statement.Statement; //import net.sf.jsqlparser.statement.select.*; //import org.jeecg.common.exception.JeecgBootException; //import org.jeecg.common.util.oConvertUtils; //import org.jeecg.common.util.sqlparse.vo.SelectSqlInfo; // //import java.io.StringReader; //import java.util.List; //import java.util.Map; // //@Slf4j //public class JSqlParserUtils { // // /** // * 解析 查询(select)sql的信息, // * 此方法会展开所有子查询到一个map里, // * key只存真实的表名,如果查询的没有真实的表名,则会被忽略。 // * value只存真实的字段名,如果查询的没有真实的字段名,则会被忽略。 // * <p> // * 例如:SELECT a.*,d.age,(SELECT count(1) FROM sys_depart) AS count FROM (SELECT username AS foo, realname FROM sys_user) a, demo d // * 解析后的结果为:{sys_user=[username, realname], demo=[age], sys_depart=[]} // * // * @param selectSql // * @return // */ // public static Map<String, SelectSqlInfo> parseAllSelectTable(String selectSql) throws JSQLParserException { // if (oConvertUtils.isEmpty(selectSql)) { // return null; // } // // log.info("解析查询Sql:{}", selectSql); // JSqlParserAllTableManager allTableManager = new JSqlParserAllTableManager(selectSql); // return allTableManager.parse(); // } // // /** // * 解析 查询(select)sql的信息,子查询嵌套 // * // * @param selectSql // * @return // */ // public static SelectSqlInfo parseSelectSqlInfo(String selectSql) throws JSQLParserException { // if (oConvertUtils.isEmpty(selectSql)) { // return null; // } // // log.info("解析查询Sql:{}", selectSql); // // 使用 JSqlParer 解析sql // // 1、创建解析器 // CCJSqlParserManager mgr = new CCJSqlParserManager(); // // 2、使用解析器解析sql生成具有层次结构的java类 // Statement stmt = mgr.parse(new StringReader(selectSql)); // if (stmt instanceof Select) { // Select selectStatement = (Select) stmt; // // 3、解析select查询sql的信息 // return JSqlParserUtils.parseBySelectBody(selectStatement.getSelectBody()); // } else { // // 非 select 查询sql,不做处理 // throw new JeecgBootException("非 select 查询sql,不做处理"); // } // } // // /** // * 解析 select 查询sql的信息 // * // * @param selectBody // * @return // */ // private static SelectSqlInfo parseBySelectBody(SelectBody selectBody) { // // 判断是否使用了union等操作 // if (selectBody instanceof SetOperationList) { // // 如果使用了union等操作,则只解析第一个查询 // List<SelectBody> selectBodyList = ((SetOperationList) selectBody).getSelects(); // return JSqlParserUtils.parseBySelectBody(selectBodyList.get(0)); // } // // 简单的select查询 // if (selectBody instanceof PlainSelect) { // SelectSqlInfo sqlInfo = new SelectSqlInfo(selectBody); // PlainSelect plainSelect = (PlainSelect) selectBody; // FromItem fromItem = plainSelect.getFromItem(); // // 解析 aliasName // if (fromItem.getAlias() != null) { // sqlInfo.setFromTableAliasName(fromItem.getAlias().getName()); // } // // 解析 表名 // if (fromItem instanceof Table) { // // 通过表名的方式from // Table fromTable = (Table) fromItem; // sqlInfo.setFromTableName(fromTable.getName()); // } else if (fromItem instanceof SubSelect) { // // 通过子查询的方式from // SubSelect fromSubSelect = (SubSelect) fromItem; // SelectSqlInfo subSqlInfo = JSqlParserUtils.parseBySelectBody(fromSubSelect.getSelectBody()); // sqlInfo.setFromSubSelect(subSqlInfo); // } // // 解析 selectFields // List<SelectItem> selectItems = plainSelect.getSelectItems(); // for (SelectItem selectItem : selectItems) { // if (selectItem instanceof AllColumns || selectItem instanceof AllTableColumns) { // // 全部字段 // sqlInfo.setSelectAll(true); // sqlInfo.setSelectFields(null); // sqlInfo.setRealSelectFields(null); // break; // } else if (selectItem instanceof SelectExpressionItem) { // // 获取单个查询字段名 // SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem; // Expression expression = selectExpressionItem.getExpression(); // Alias alias = selectExpressionItem.getAlias(); // JSqlParserUtils.handleExpression(sqlInfo, expression, alias); // } // } // return sqlInfo; // } else { // log.warn("暂时尚未处理该类型的 SelectBody: {}", selectBody.getClass().getName()); // throw new JeecgBootException("暂时尚未处理该类型的 SelectBody"); // } // } // // /** // * 处理查询字段表达式 // * // * @param sqlInfo // * @param expression // * @param alias 是否有别名,无传null // */ // private static void handleExpression(SelectSqlInfo sqlInfo, Expression expression, Alias alias) { // // 处理函数式字段 CONCAT(name,'(',age,')') // if (expression instanceof Function) { // JSqlParserUtils.handleFunctionExpression((Function) expression, sqlInfo); // return; // } // // 处理字段上的子查询 // if (expression instanceof SubSelect) { // SubSelect subSelect = (SubSelect) expression; // SelectSqlInfo subSqlInfo = JSqlParserUtils.parseBySelectBody(subSelect.getSelectBody()); // // 注:字段上的子查询,必须只查询一个字段,否则会报错,所以可以放心合并 // sqlInfo.getSelectFields().addAll(subSqlInfo.getSelectFields()); // sqlInfo.getRealSelectFields().addAll(subSqlInfo.getAllRealSelectFields()); // return; // } // // 不处理字面量 // if (expression instanceof StringValue || // expression instanceof NullValue || // expression instanceof LongValue || // expression instanceof DoubleValue || // expression instanceof HexValue || // expression instanceof DateValue || // expression instanceof TimestampValue || // expression instanceof TimeValue // ) { // return; // } // // // 查询字段名 // String selectField = expression.toString(); // // 实际查询字段名 // String realSelectField = selectField; // // 判断是否有别名 // if (alias != null) { // selectField = alias.getName(); // } // // 获取真实字段名 // if (expression instanceof Column) { // Column column = (Column) expression; // realSelectField = column.getColumnName(); // } // sqlInfo.addSelectField(selectField, realSelectField); // } // // /** // * 处理函数式字段 // * // * @param functionExp // * @param sqlInfo // */ // private static void handleFunctionExpression(Function functionExp, SelectSqlInfo sqlInfo) { // List<Expression> expressions = functionExp.getParameters().getExpressions(); // for (Expression expression : expressions) { // JSqlParserUtils.handleExpression(sqlInfo, expression, null); // } // } // //}
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/sqlparse/JSqlParserAllTableManager.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/sqlparse/JSqlParserAllTableManager.java
//package org.jeecg.common.util.sqlparse; // //import lombok.extern.slf4j.Slf4j; //import net.sf.jsqlparser.JSQLParserException; //import net.sf.jsqlparser.expression.*; //import net.sf.jsqlparser.parser.CCJSqlParserManager; //import net.sf.jsqlparser.schema.Column; //import net.sf.jsqlparser.schema.Table; //import net.sf.jsqlparser.statement.Statement; //import net.sf.jsqlparser.statement.select.*; //import org.jeecg.common.exception.JeecgBootException; //import org.jeecg.common.util.sqlparse.vo.SelectSqlInfo; // //import java.io.StringReader; //import java.util.ArrayList; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // ///** // * 解析所有表名和字段的类 // */ //@Slf4j //public class JSqlParserAllTableManager { // // private final String sql; // private final Map<String, SelectSqlInfo> allTableMap = new HashMap<>(); // /** // * 别名对应实际表名 // */ // private final Map<String, String> tableAliasMap = new HashMap<>(); // // /** // * 解析后的sql // */ // private String parsedSql = null; // // JSqlParserAllTableManager(String selectSql) { // this.sql = selectSql; // } // // /** // * 开始解析 // * // * @return // * @throws JSQLParserException // */ // public Map<String, SelectSqlInfo> parse() throws JSQLParserException { // // 1. 创建解析器 // CCJSqlParserManager mgr = new CCJSqlParserManager(); // // 2. 使用解析器解析sql生成具有层次结构的java类 // Statement stmt = mgr.parse(new StringReader(this.sql)); // if (stmt instanceof Select) { // Select selectStatement = (Select) stmt; // SelectBody selectBody = selectStatement.getSelectBody(); // this.parsedSql = selectBody.toString(); // // 3. 解析select查询sql的信息 // if (selectBody instanceof PlainSelect) { // PlainSelect plainSelect = (PlainSelect) selectBody; // // 4. 合并 fromItems // List<FromItem> fromItems = new ArrayList<>(); // fromItems.add(plainSelect.getFromItem()); // // 4.1 处理join的表 // List<Join> joins = plainSelect.getJoins(); // if (joins != null) { // joins.forEach(join -> fromItems.add(join.getRightItem())); // } // // 5. 处理 fromItems // for (FromItem fromItem : fromItems) { // // 5.1 通过表名的方式from // if (fromItem instanceof Table) { // this.addSqlInfoByTable((Table) fromItem); // } // // 5.2 通过子查询的方式from // else if (fromItem instanceof SubSelect) { // this.handleSubSelect((SubSelect) fromItem); // } // } // // 6. 解析 selectFields // List<SelectItem> selectItems = plainSelect.getSelectItems(); // for (SelectItem selectItem : selectItems) { // // 6.1 查询的是全部字段 // if (selectItem instanceof AllColumns) { // // 当 selectItem 为 AllColumns 时,fromItem 必定为 Table // String tableName = plainSelect.getFromItem(Table.class).getName(); // // 此处必定不为空,因为在解析 fromItem 时,已经将表名添加到 allTableMap 中 // SelectSqlInfo sqlInfo = this.allTableMap.get(tableName); // assert sqlInfo != null; // // 设置为查询全部字段 // sqlInfo.setSelectAll(true); // sqlInfo.setSelectFields(null); // sqlInfo.setRealSelectFields(null); // } // // 6.2 查询的是带表别名( u.* )的全部字段 // else if (selectItem instanceof AllTableColumns) { // AllTableColumns allTableColumns = (AllTableColumns) selectItem; // String aliasName = allTableColumns.getTable().getName(); // // 通过别名获取表名 // String tableName = this.tableAliasMap.get(aliasName); // if (tableName == null) { // tableName = aliasName; // } // SelectSqlInfo sqlInfo = this.allTableMap.get(tableName); // // 如果此处为空,则说明该字段是通过子查询获取的,所以可以不处理,只有实际表才需要处理 // if (sqlInfo != null) { // // 设置为查询全部字段 // sqlInfo.setSelectAll(true); // sqlInfo.setSelectFields(null); // sqlInfo.setRealSelectFields(null); // } // } // // 6.3 各种字段表达式处理 // else if (selectItem instanceof SelectExpressionItem) { // SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem; // Expression expression = selectExpressionItem.getExpression(); // Alias alias = selectExpressionItem.getAlias(); // this.handleExpression(expression, alias, plainSelect.getFromItem()); // } // } // } else { // log.warn("暂时尚未处理该类型的 SelectBody: {}", selectBody.getClass().getName()); // throw new JeecgBootException("暂时尚未处理该类型的 SelectBody"); // } // } else { // // 非 select 查询sql,不做处理 // throw new JeecgBootException("非 select 查询sql,不做处理"); // } // return this.allTableMap; // } // // /** // * 处理子查询 // * // * @param subSelect // */ // private void handleSubSelect(SubSelect subSelect) { // try { // String subSelectSql = subSelect.getSelectBody().toString(); // // 递归调用解析 // Map<String, SelectSqlInfo> map = JSqlParserUtils.parseAllSelectTable(subSelectSql); // if (map != null) { // this.assignMap(map); // } // } catch (Exception e) { // log.error("解析子查询出错", e); // } // } // // /** // * 处理查询字段表达式 // * // * @param expression // */ // private void handleExpression(Expression expression, Alias alias, FromItem fromItem) { // // 处理函数式字段 CONCAT(name,'(',age,')') // if (expression instanceof Function) { // Function functionExp = (Function) expression; // List<Expression> expressions = functionExp.getParameters().getExpressions(); // for (Expression expItem : expressions) { // this.handleExpression(expItem, null, fromItem); // } // return; // } // // 处理字段上的子查询 // if (expression instanceof SubSelect) { // this.handleSubSelect((SubSelect) expression); // return; // } // // 不处理字面量 // if (expression instanceof StringValue || // expression instanceof NullValue || // expression instanceof LongValue || // expression instanceof DoubleValue || // expression instanceof HexValue || // expression instanceof DateValue || // expression instanceof TimestampValue || // expression instanceof TimeValue // ) { // return; // } // // // 处理字段 // if (expression instanceof Column) { // Column column = (Column) expression; // // 查询字段名 // String fieldName = column.getColumnName(); // String aliasName = fieldName; // if (alias != null) { // aliasName = alias.getName(); // } // String tableName; // if (column.getTable() != null) { // // 通过列的表名获取 sqlInfo // // 例如 user.name,这里的 tableName 就是 user // tableName = column.getTable().getName(); // // 有可能是别名,需要转换为真实表名 // if (this.tableAliasMap.get(tableName) != null) { // tableName = this.tableAliasMap.get(tableName); // } // } else { // // 当column的table为空时,说明是 fromItem 中的字段 // tableName = ((Table) fromItem).getName(); // } // SelectSqlInfo $sqlInfo = this.allTableMap.get(tableName); // if ($sqlInfo != null) { // $sqlInfo.addSelectField(aliasName, fieldName); // } else { // log.warn("发生意外情况,未找到表名为 {} 的 SelectSqlInfo", tableName); // } // } // } // // /** // * 根据表名添加sqlInfo // * // * @param table // */ // private void addSqlInfoByTable(Table table) { // String tableName = table.getName(); // // 解析 aliasName // if (table.getAlias() != null) { // this.tableAliasMap.put(table.getAlias().getName(), tableName); // } // SelectSqlInfo sqlInfo = new SelectSqlInfo(this.parsedSql); // sqlInfo.setFromTableName(table.getName()); // this.allTableMap.put(sqlInfo.getFromTableName(), sqlInfo); // } // // /** // * 合并map // * // * @param source // */ // private void assignMap(Map<String, SelectSqlInfo> source) { // for (Map.Entry<String, SelectSqlInfo> entry : source.entrySet()) { // SelectSqlInfo sqlInfo = this.allTableMap.get(entry.getKey()); // if (sqlInfo == null) { // this.allTableMap.put(entry.getKey(), entry.getValue()); // } else { // // 合并 // if (sqlInfo.getSelectFields() == null) { // sqlInfo.setSelectFields(entry.getValue().getSelectFields()); // } else { // sqlInfo.getSelectFields().addAll(entry.getValue().getSelectFields()); // } // if (sqlInfo.getRealSelectFields() == null) { // sqlInfo.setRealSelectFields(entry.getValue().getRealSelectFields()); // } else { // sqlInfo.getRealSelectFields().addAll(entry.getValue().getRealSelectFields()); // } // } // } // } // //}
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/sqlparse/vo/SelectSqlInfo.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/sqlparse/vo/SelectSqlInfo.java
//package org.jeecg.common.util.sqlparse.vo; // //import lombok.Data; //import net.sf.jsqlparser.statement.select.SelectBody; // //import java.util.HashSet; //import java.util.Set; // ///** // * select 查询 sql 的信息 // */ //@Data //public class SelectSqlInfo { // // /** // * 查询的表名,如果是子查询,则此处为null // */ // private String fromTableName; // /** // * 表别名 // */ // private String fromTableAliasName; // /** // * 通过子查询获取的表信息,例如:select name from (select * from user) u // * 如果不是子查询,则为null // */ // private SelectSqlInfo fromSubSelect; // /** // * 查询的字段集合,如果是 * 则为null,如果设了别名则为别名 // */ // private Set<String> selectFields; // /** // * 真实的查询字段集合,如果是 * 则为null,如果设了别名则为原始字段名 // */ // private Set<String> realSelectFields; // /** // * 是否是查询所有字段 // */ // private boolean selectAll; // // /** // * 解析之后的 SQL (关键字都是大写) // */ // private final String parsedSql; // // public SelectSqlInfo(String parsedSql) { // this.parsedSql = parsedSql; // } // // public SelectSqlInfo(SelectBody selectBody) { // this.parsedSql = selectBody.toString(); // } // // public void addSelectField(String selectField, String realSelectField) { // if (this.selectFields == null) { // this.selectFields = new HashSet<>(); // } // if (this.realSelectFields == null) { // this.realSelectFields = new HashSet<>(); // } // this.selectFields.add(selectField); // this.realSelectFields.add(realSelectField); // } // // /** // * 获取所有字段,包括子查询里的。 // * // * @return // */ // public Set<String> getAllRealSelectFields() { // Set<String> fields = new HashSet<>(); // // 递归获取所有字段,起个直观的方法名为: // this.recursiveGetAllFields(this, fields); // return fields; // } // // /** // * 递归获取所有字段 // */ // private void recursiveGetAllFields(SelectSqlInfo sqlInfo, Set<String> fields) { // if (!sqlInfo.isSelectAll() && sqlInfo.getRealSelectFields() != null) { // fields.addAll(sqlInfo.getRealSelectFields()); // } // if (sqlInfo.getFromSubSelect() != null) { // recursiveGetAllFields(sqlInfo.getFromSubSelect(), fields); // } // } // // @Override // public String toString() { // return "SelectSqlInfo{" + // "fromTableName='" + fromTableName + '\'' + // ", fromSubSelect=" + fromSubSelect + // ", aliasName='" + fromTableAliasName + '\'' + // ", selectFields=" + selectFields + // ", realSelectFields=" + realSelectFields + // ", selectAll=" + selectAll + // "}"; // } // //}
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/AbstractQueryBlackListHandler.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/AbstractQueryBlackListHandler.java
package org.jeecg.common.util.security; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.jeecg.common.exception.JeecgSqlInjectionException; import org.jeecg.common.util.SqlInjectionUtil; import org.jeecg.common.util.oConvertUtils; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 查询表/字段 黑名单处理 * @Author taoYan * @Date 2022/3/17 11:21 **/ @Slf4j public abstract class AbstractQueryBlackListHandler { /** * key-表名 * value-字段名,多个逗号隔开 * 两种配置方式-- 全部配置成小写 * ruleMap.put("sys_user", "*")sys_user所有的字段不支持查询 * ruleMap.put("sys_user", "username,password")sys_user中的username和password不支持查询 */ public static Map<String, String> ruleMap = new HashMap<>(); /** * 以下字符不能出现在表名中或是字段名中 */ public static final Pattern ILLEGAL_NAME_REG = Pattern.compile("[-]{2,}"); static { ruleMap.put("sys_user", "password,salt"); } /** * 根据 sql语句 获取表和字段信息,需要到具体的实现类重写此方法- * 不同的场景 处理可能不太一样 需要自定义,但是返回值确定 * @param sql * @return */ protected abstract List<QueryTable> getQueryTableInfo(String sql); /** * 校验sql语句 成功返回true * @param sql * @return */ public boolean isPass(String sql) { List<QueryTable> list = null; //【jeecg-boot/issues/4040】在线报表不支持子查询,解析报错 #4040 try { list = this.getQueryTableInfo(sql.toLowerCase()); } catch (Exception e) { log.warn("校验sql语句,解析报错:{}",e.getMessage()); } if(list==null){ return true; } log.debug(" 获取sql信息 :{} ", list.toString()); boolean flag = checkTableAndFieldsName(list); if(flag == false){ return false; } Set<String> xssTableSet = new HashSet<>(Arrays.asList(SqlInjectionUtil.XSS_STR_TABLE.split("\\|"))); for (QueryTable table : list) { String name = table.getName(); String fieldRule = ruleMap.get(name); // 有没有配置这张表 if (fieldRule != null) { if ("*".equals(fieldRule) || table.isAll()) { flag = false; log.warn("sql黑名单校验,表【"+name+"】禁止查询"); break; } else if (table.existSameField(fieldRule)) { flag = false; break; } } // 判断是否调用了黑名单数据库 String dbName = table.getDbName(); if (oConvertUtils.isNotEmpty(dbName)) { dbName = dbName.toLowerCase().trim(); if (xssTableSet.contains(dbName)) { flag = false; log.warn("sql黑名单校验,数据库【" + dbName + "】禁止查询"); break; } } } // 返回黑名单校验结果(不合法直接抛出异常) if(!flag){ log.error(this.getError()); throw new JeecgSqlInjectionException(this.getError()); } return flag; } /** * 校验表名和字段名是否有效,或是是否会带些特殊的字符串进行sql注入 * issues/4983 SQL Injection in 3.5.1 #4983 * @return */ private boolean checkTableAndFieldsName(List<QueryTable> list){ boolean flag = true; for(QueryTable queryTable: list){ String tableName = queryTable.getName(); if(hasSpecialString(tableName)){ flag = false; log.warn("sql黑名单校验,表名【"+tableName+"】包含特殊字符"); break; } Set<String> fields = queryTable.getFields(); for(String name: fields){ if(hasSpecialString(name)){ flag = false; log.warn("sql黑名单校验,字段名【"+name+"】包含特殊字符"); break; } } } return flag; } /** * 是否包含特殊的字符串 * @param name * @return */ private boolean hasSpecialString(String name){ Matcher m = ILLEGAL_NAME_REG.matcher(name); if (m.find()) { return true; } return false; } /** * 查询的表的信息 */ protected class QueryTable { //数据库名 private String dbName; //表名 private String name; //表的别名 private String alias; // 字段名集合 private Set<String> fields; // 是否查询所有字段 private boolean all; public QueryTable() { } public QueryTable(String name, String alias) { this.name = name; this.alias = alias; this.all = false; this.fields = new HashSet<>(); } public void addField(String field) { this.fields.add(field); } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public String getName() { return name; } public Set<String> getFields() { return new HashSet<>(fields); } public void setName(String name) { this.name = name; } public void setFields(Set<String> fields) { this.fields = fields; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public boolean isAll() { return all; } public void setAll(boolean all) { this.all = all; } /** * 判断是否有相同字段 * * @param fieldString * @return */ public boolean existSameField(String fieldString) { String[] controlFields = fieldString.split(","); for (String sqlField : fields) { for (String controlField : controlFields) { if (sqlField.equals(controlField)) { // 非常明确的列直接比较 log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询"); return true; } else { // 使用表达式的列 只能判读字符串包含了 String aliasColumn = controlField; if (StringUtils.isNotBlank(alias)) { aliasColumn = alias + "." + controlField; } if (sqlField.indexOf(aliasColumn) != -1) { log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询"); return true; } } } } return false; } @Override public String toString() { return "QueryTable{" + "name='" + name + '\'' + ", alias='" + alias + '\'' + ", fields=" + fields + ", all=" + all + '}'; } } public String getError(){ // TODO return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!"; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/JdbcSecurityUtil.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/JdbcSecurityUtil.java
package org.jeecg.common.util.security; import org.jeecg.common.exception.JeecgBootException; import org.jeecg.common.util.oConvertUtils; /** * jdbc连接校验 * @Author taoYan * @Date 2022/8/10 18:15 **/ public class JdbcSecurityUtil { /** * 连接驱动漏洞 最新版本修复后,可删除相应的key * postgre:authenticationPluginClassName, sslhostnameverifier, socketFactory, sslfactory, sslpasswordcallback * https://github.com/pgjdbc/pgjdbc/security/advisories/GHSA-v7wg-cpwc-24m4 * */ public static final String[] notAllowedProps = new String[]{"authenticationPluginClassName", "sslhostnameverifier", "socketFactory", "sslfactory", "sslpasswordcallback"}; /** * 校验sql是否有特定的key * @param jdbcUrl * @return */ public static void validate(String jdbcUrl){ if(oConvertUtils.isEmpty(jdbcUrl)){ return; } String urlConcatChar = "?"; if(jdbcUrl.indexOf(urlConcatChar)<0){ return; } String argString = jdbcUrl.substring(jdbcUrl.indexOf(urlConcatChar)+1); String[] keyAndValues = argString.split("&"); for(String temp: keyAndValues){ String key = temp.split("=")[0]; for(String prop: notAllowedProps){ if(prop.equalsIgnoreCase(key)){ throw new JeecgBootException("连接地址有安全风险,【"+key+"】"); } } } } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/SecurityTools.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/SecurityTools.java
package org.jeecg.common.util.security; import cn.hutool.core.codec.Base64Decoder; import cn.hutool.core.codec.Base64Encoder; import cn.hutool.crypto.SecureUtil; import cn.hutool.crypto.asymmetric.KeyType; import cn.hutool.crypto.asymmetric.RSA; import cn.hutool.crypto.asymmetric.Sign; import cn.hutool.crypto.asymmetric.SignAlgorithm; import cn.hutool.crypto.symmetric.AES; import org.jeecg.common.util.security.entity.*; import com.alibaba.fastjson.JSONObject; import javax.crypto.SecretKey; import java.security.KeyPair; /** * @Description: SecurityTools * @author: jeecg-boot */ public class SecurityTools { public static final String ALGORITHM = "AES/ECB/PKCS5Padding"; public static SecurityResp valid(SecurityReq req) { SecurityResp resp=new SecurityResp(); String pubKey=req.getPubKey(); String aesKey=req.getAesKey(); String data=req.getData(); String signData=req.getSignData(); RSA rsa=new RSA(null, Base64Decoder.decode(pubKey)); Sign sign= new Sign(SignAlgorithm.SHA1withRSA,null,pubKey); byte[] decryptAes = rsa.decrypt(aesKey, KeyType.PublicKey); //log.info("rsa解密后的秘钥"+ Base64Encoder.encode(decryptAes)); AES aes = SecureUtil.aes(decryptAes); String dencrptValue =aes.decryptStr(data); //log.info("解密后报文"+dencrptValue); resp.setData(JSONObject.parseObject(dencrptValue)); boolean verify = sign.verify(dencrptValue.getBytes(), Base64Decoder.decode(signData)); resp.setSuccess(verify); return resp; } public static SecuritySignResp sign(SecuritySignReq req) { SecretKey secretKey = SecureUtil.generateKey(ALGORITHM); byte[] key= secretKey.getEncoded(); String prikey=req.getPrikey(); String data=req.getData(); AES aes = SecureUtil.aes(key); aes.getSecretKey().getEncoded(); String encrptData =aes.encryptBase64(data); RSA rsa=new RSA(prikey,null); byte[] encryptAesKey = rsa.encrypt(secretKey.getEncoded(), KeyType.PrivateKey); //log.info(("rsa加密过的秘钥=="+Base64Encoder.encode(encryptAesKey)); Sign sign= new Sign(SignAlgorithm.SHA1withRSA,prikey,null); byte[] signed = sign.sign(data.getBytes()); //log.info(("签名数据===》》"+Base64Encoder.encode(signed)); SecuritySignResp resp=new SecuritySignResp(); resp.setAesKey(Base64Encoder.encode(encryptAesKey)); resp.setData(encrptData); resp.setSignData(Base64Encoder.encode(signed)); return resp; } public static MyKeyPair generateKeyPair(){ KeyPair keyPair= SecureUtil.generateKeyPair(SignAlgorithm.SHA1withRSA.getValue(),2048); String priKey= Base64Encoder.encode(keyPair.getPrivate().getEncoded()); String pubkey= Base64Encoder.encode(keyPair.getPublic().getEncoded()); MyKeyPair resp=new MyKeyPair(); resp.setPriKey(priKey); resp.setPubKey(pubkey); return resp; } }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/entity/SecuritySignResp.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/entity/SecuritySignResp.java
package org.jeecg.common.util.security.entity; import lombok.Data; /** * @Description: SecuritySignResp * @author: jeecg-boot */ @Data public class SecuritySignResp { private String data; private String signData; private String aesKey; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false
jeecgboot/JeecgBoot
https://github.com/jeecgboot/JeecgBoot/blob/e533af285c68b205f4ee8cf059d34fbb21d222d3/jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/entity/SecurityReq.java
jeecg-boot/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/entity/SecurityReq.java
package org.jeecg.common.util.security.entity; import lombok.Data; /** * @Description: SecurityReq * @author: jeecg-boot */ @Data public class SecurityReq { private String data; private String pubKey; private String signData; private String aesKey; }
java
Apache-2.0
e533af285c68b205f4ee8cf059d34fbb21d222d3
2026-01-04T14:45:57.045651Z
false