diff --git a/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/ThreadPoolAdapterScheduler.java b/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/ThreadPoolAdapterScheduler.java index 41f5db22..d71cf267 100644 --- a/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/ThreadPoolAdapterScheduler.java +++ b/hippo4j-adapter/hippo4j-adapter-hystrix/src/main/java/cn/hippo4j/adapter/hystrix/ThreadPoolAdapterScheduler.java @@ -17,7 +17,7 @@ package cn.hippo4j.adapter.hystrix; -import cn.hutool.core.thread.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ScheduledExecutorService; @@ -36,8 +36,8 @@ public class ThreadPoolAdapterScheduler { public ThreadPoolAdapterScheduler() { scheduler = new ScheduledThreadPoolExecutor(2, new ThreadFactoryBuilder() - .setNamePrefix("threadPoolAdapter") - .setDaemon(true) + .prefix("threadPoolAdapter") + .daemon(true) .build()); } diff --git a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/TomcatWebThreadPoolHandler.java b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/TomcatWebThreadPoolHandler.java index 70057a9d..c15cf7a6 100644 --- a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/TomcatWebThreadPoolHandler.java +++ b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/TomcatWebThreadPoolHandler.java @@ -24,12 +24,13 @@ import cn.hippo4j.common.model.ThreadPoolParameterInfo; import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.common.toolkit.CalculateUtil; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; -import cn.hutool.core.date.DateUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.web.embedded.tomcat.TomcatWebServer; import org.springframework.boot.web.server.WebServer; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; @@ -138,7 +139,7 @@ public class TomcatWebThreadPoolHandler extends AbstractWebThreadPoolService { runStateInfo.setQueueRemainingCapacity(remainingCapacity); runStateInfo.setLargestPoolSize(largestPoolSize); runStateInfo.setCompletedTaskCount(completedTaskCount); - runStateInfo.setClientLastRefreshTime(DateUtil.formatDateTime(new Date())); + runStateInfo.setClientLastRefreshTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); runStateInfo.setTimestamp(System.currentTimeMillis()); String rejectedExecutionHandlerName = executor instanceof ThreadPoolExecutor ? ((ThreadPoolExecutor) executor).getRejectedExecutionHandler().getClass().getSimpleName() : tomcatThreadPoolExecutor.getRejectedExecutionHandler().getClass().getSimpleName(); diff --git a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/UndertowWebThreadPoolHandler.java b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/UndertowWebThreadPoolHandler.java index 13038842..731b094a 100644 --- a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/UndertowWebThreadPoolHandler.java +++ b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/UndertowWebThreadPoolHandler.java @@ -24,7 +24,6 @@ import cn.hippo4j.common.model.ThreadPoolParameterInfo; import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.common.toolkit.CalculateUtil; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; -import cn.hutool.core.date.DateUtil; import io.undertow.Undertow; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServer; @@ -35,6 +34,8 @@ import org.xnio.XnioWorker; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Objects; import java.util.concurrent.Executor; @@ -128,7 +129,7 @@ public class UndertowWebThreadPoolHandler extends AbstractWebThreadPoolService { ? ((DynamicThreadPoolExecutor) fieldObject).getRejectCountNum() : -1L; stateInfo.setRejectCount(rejectCount); - stateInfo.setClientLastRefreshTime(DateUtil.formatDateTime(new Date())); + stateInfo.setClientLastRefreshTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); stateInfo.setTimestamp(System.currentTimeMillis()); return stateInfo; } diff --git a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolRunStateHandler.java b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolRunStateHandler.java index b5442300..2cee24ef 100644 --- a/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolRunStateHandler.java +++ b/hippo4j-adapter/hippo4j-adapter-web/src/main/java/cn/hippo4j/adapter/web/WebThreadPoolRunStateHandler.java @@ -20,10 +20,12 @@ package cn.hippo4j.adapter.web; import cn.hippo4j.common.model.ThreadPoolRunStateInfo; import cn.hippo4j.common.toolkit.ByteConvertUtil; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; -import cn.hutool.core.util.StrUtil; -import cn.hutool.system.RuntimeInfo; import lombok.extern.slf4j.Slf4j; +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryMXBean; +import java.lang.management.MemoryUsage; + /** * Web thread pool run state handler. */ @@ -32,16 +34,20 @@ public class WebThreadPoolRunStateHandler extends AbstractThreadPoolRuntime { @Override public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) { - RuntimeInfo runtimeInfo = new RuntimeInfo(); - String memoryProportion = StrUtil.builder( - "已分配: ", - ByteConvertUtil.getPrintSize(runtimeInfo.getTotalMemory()), - " / 最大可用: ", - ByteConvertUtil.getPrintSize(runtimeInfo.getMaxMemory())).toString(); + MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); + long used = heapMemoryUsage.getUsed(); + long max = heapMemoryUsage.getMax(); + String memoryProportion = new StringBuilder() + .append("已分配: ") + .append(ByteConvertUtil.getPrintSize(used)) + .append(" / 最大可用: ") + .append(ByteConvertUtil.getPrintSize(max)) + .toString(); poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%"); poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%"); poolRunStateInfo.setMemoryProportion(memoryProportion); - poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(runtimeInfo.getFreeMemory())); + poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(Math.subtractExact(max, used))); return poolRunStateInfo; } } diff --git a/hippo4j-auth/pom.xml b/hippo4j-auth/pom.xml index c44bcffb..9a2d1212 100644 --- a/hippo4j-auth/pom.xml +++ b/hippo4j-auth/pom.xml @@ -46,11 +46,6 @@ spring-boot-starter-web - - cn.hutool - hutool-all - - org.springframework.boot spring-boot-starter-security diff --git a/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthenticationFilter.java b/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthenticationFilter.java index f6456ba8..0f93e918 100644 --- a/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthenticationFilter.java +++ b/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthenticationFilter.java @@ -21,8 +21,8 @@ import cn.hippo4j.auth.model.biz.user.JwtUser; import cn.hippo4j.auth.model.biz.user.LoginUser; import cn.hippo4j.auth.toolkit.JwtTokenUtil; import cn.hippo4j.auth.toolkit.ReturnT; +import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.web.base.Results; -import cn.hutool.json.JSONUtil; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationManager; @@ -34,7 +34,6 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -100,7 +99,7 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte Map maps = new HashMap(MAP_INITIAL_CAPACITY); maps.put("data", JwtTokenUtil.TOKEN_PREFIX + token); maps.put("roles", role.split(SPLIT_COMMA)); - response.getWriter().write(JSONUtil.toJsonStr(Results.success(maps))); + response.getWriter().write(JSONUtil.toJSONString(Results.success(maps))); } finally { rememberMe.remove(); } @@ -109,6 +108,6 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException { response.setCharacterEncoding("UTF-8"); - response.getWriter().write(JSONUtil.toJsonStr(new ReturnT(-1, "Server Error"))); + response.getWriter().write(JSONUtil.toJSONString(new ReturnT(-1, "Server Error"))); } } diff --git a/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthorizationFilter.java b/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthorizationFilter.java index 7ec3c66b..3b6cf69e 100644 --- a/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthorizationFilter.java +++ b/hippo4j-auth/src/main/java/cn/hippo4j/auth/filter/JWTAuthorizationFilter.java @@ -20,10 +20,10 @@ package cn.hippo4j.auth.filter; import cn.hippo4j.auth.security.JwtTokenManager; import cn.hippo4j.auth.toolkit.JwtTokenUtil; import cn.hippo4j.common.toolkit.JSONUtil; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.UserContext; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.common.web.exception.ServiceException; -import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -61,7 +61,7 @@ public class JWTAuthorizationFilter extends BasicAuthenticationFilter { FilterChain chain) throws IOException, ServletException { // Token when verifying client interaction. String accessToken = request.getParameter(ACCESS_TOKEN); - if (StrUtil.isNotBlank(accessToken)) { + if (StringUtil.isNotBlank(accessToken)) { tokenManager.validateToken(accessToken); Authentication authentication = this.tokenManager.getAuthentication(accessToken); SecurityContextHolder.getContext().setAuthentication(authentication); diff --git a/hippo4j-auth/src/main/java/cn/hippo4j/auth/security/JwtTokenManager.java b/hippo4j-auth/src/main/java/cn/hippo4j/auth/security/JwtTokenManager.java index 84160cc9..17f52aaa 100644 --- a/hippo4j-auth/src/main/java/cn/hippo4j/auth/security/JwtTokenManager.java +++ b/hippo4j-auth/src/main/java/cn/hippo4j/auth/security/JwtTokenManager.java @@ -17,7 +17,7 @@ package cn.hippo4j.auth.security; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.StringUtil; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; @@ -64,7 +64,7 @@ public class JwtTokenManager { Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody(); List authorities = AuthorityUtils .commaSeparatedStringToAuthorityList((String) claims.get(AUTHORITIES_KEY)); - User principal = new User(claims.getSubject(), StrUtil.EMPTY, authorities); - return new UsernamePasswordAuthenticationToken(principal, StrUtil.EMPTY, authorities); + User principal = new User(claims.getSubject(), StringUtil.EMPTY, authorities); + return new UsernamePasswordAuthenticationToken(principal, StringUtil.EMPTY, authorities); } } diff --git a/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/PermissionServiceImpl.java b/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/PermissionServiceImpl.java index b53b1c6a..83787200 100644 --- a/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/PermissionServiceImpl.java +++ b/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/PermissionServiceImpl.java @@ -21,8 +21,8 @@ import cn.hippo4j.auth.mapper.PermissionMapper; import cn.hippo4j.auth.model.biz.permission.PermissionQueryPageReqDTO; import cn.hippo4j.auth.model.biz.permission.PermissionRespDTO; import cn.hippo4j.auth.service.PermissionService; -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.StringUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; @@ -44,8 +44,7 @@ public class PermissionServiceImpl implements PermissionService { public IPage listPermission(int pageNo, int pageSize) { PermissionQueryPageReqDTO queryPage = new PermissionQueryPageReqDTO(pageNo, pageSize); IPage selectPage = permissionMapper.selectPage(queryPage, null); - - return selectPage.convert(each -> BeanUtil.toBean(each, PermissionRespDTO.class)); + return selectPage.convert(each -> BeanUtil.convert(each, PermissionRespDTO.class)); } @Override @@ -68,9 +67,9 @@ public class PermissionServiceImpl implements PermissionService { @Override public void deletePermission(String role, String resource, String action) { LambdaUpdateWrapper updateWrapper = Wrappers.lambdaUpdate(PermissionInfo.class) - .eq(StrUtil.isNotBlank(role), PermissionInfo::getRole, role) - .eq(StrUtil.isNotBlank(resource), PermissionInfo::getResource, resource) - .eq(StrUtil.isNotBlank(action), PermissionInfo::getAction, action); + .eq(StringUtil.isNotBlank(role), PermissionInfo::getRole, role) + .eq(StringUtil.isNotBlank(resource), PermissionInfo::getResource, resource) + .eq(StringUtil.isNotBlank(action), PermissionInfo::getAction, action); permissionMapper.delete(updateWrapper); } } diff --git a/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/RoleServiceImpl.java b/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/RoleServiceImpl.java index dd45b56c..b298bb70 100644 --- a/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/RoleServiceImpl.java +++ b/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/RoleServiceImpl.java @@ -22,9 +22,9 @@ import cn.hippo4j.auth.model.biz.role.RoleQueryPageReqDTO; import cn.hippo4j.auth.model.biz.role.RoleRespDTO; import cn.hippo4j.auth.service.PermissionService; import cn.hippo4j.auth.service.RoleService; -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.StringUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; @@ -51,7 +51,7 @@ public class RoleServiceImpl implements RoleService { public IPage listRole(int pageNo, int pageSize) { RoleQueryPageReqDTO queryPage = new RoleQueryPageReqDTO(pageNo, pageSize); IPage selectPage = roleMapper.selectPage(queryPage, null); - return selectPage.convert(each -> BeanUtil.toBean(each, RoleRespDTO.class)); + return selectPage.convert(each -> BeanUtil.convert(each, RoleRespDTO.class)); } @Override @@ -70,14 +70,14 @@ public class RoleServiceImpl implements RoleService { @Override public void deleteRole(String role, String userName) { - List roleStrList = CollUtil.toList(role); - if (StrUtil.isBlank(role)) { + List roleStrList = CollectionUtil.toList(role); + if (StringUtil.isBlank(role)) { LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(RoleInfo.class).eq(RoleInfo::getUserName, userName); roleStrList = roleMapper.selectList(queryWrapper).stream().map(RoleInfo::getRole).collect(Collectors.toList()); } LambdaUpdateWrapper updateWrapper = Wrappers.lambdaUpdate(RoleInfo.class) - .eq(StrUtil.isNotBlank(role), RoleInfo::getRole, role) - .eq(StrUtil.isNotBlank(userName), RoleInfo::getUserName, userName); + .eq(StringUtil.isNotBlank(role), RoleInfo::getRole, role) + .eq(StringUtil.isNotBlank(userName), RoleInfo::getUserName, userName); roleMapper.delete(updateWrapper); roleStrList.forEach(each -> permissionService.deletePermission(each, "", "")); } diff --git a/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/UserServiceImpl.java b/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/UserServiceImpl.java index f94df6a2..b500fa06 100644 --- a/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/UserServiceImpl.java +++ b/hippo4j-auth/src/main/java/cn/hippo4j/auth/service/impl/UserServiceImpl.java @@ -24,10 +24,9 @@ import cn.hippo4j.auth.model.biz.user.UserReqDTO; import cn.hippo4j.auth.model.biz.user.UserRespDTO; import cn.hippo4j.auth.service.RoleService; import cn.hippo4j.auth.service.UserService; +import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.exception.ServiceException; -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; @@ -59,7 +58,7 @@ public class UserServiceImpl implements UserService { LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(UserInfo.class) .eq(StringUtil.isNotBlank(reqDTO.getUserName()), UserInfo::getUserName, reqDTO.getUserName()); IPage selectPage = userMapper.selectPage(reqDTO, queryWrapper); - return selectPage.convert(each -> BeanUtil.toBean(each, UserRespDTO.class)); + return selectPage.convert(each -> BeanUtil.convert(each, UserRespDTO.class)); } @Override @@ -71,16 +70,16 @@ public class UserServiceImpl implements UserService { throw new RuntimeException("用户名重复"); } reqDTO.setPassword(bCryptPasswordEncoder.encode(reqDTO.getPassword())); - UserInfo insertUser = BeanUtil.toBean(reqDTO, UserInfo.class); + UserInfo insertUser = BeanUtil.convert(reqDTO, UserInfo.class); userMapper.insert(insertUser); } @Override public void updateUser(UserReqDTO reqDTO) { - if (StrUtil.isNotBlank(reqDTO.getPassword())) { + if (StringUtil.isNotBlank(reqDTO.getPassword())) { reqDTO.setPassword(bCryptPasswordEncoder.encode(reqDTO.getPassword())); } - UserInfo updateUser = BeanUtil.toBean(reqDTO, UserInfo.class); + UserInfo updateUser = BeanUtil.convert(reqDTO, UserInfo.class); LambdaUpdateWrapper updateWrapper = Wrappers.lambdaUpdate(UserInfo.class) .eq(UserInfo::getUserName, reqDTO.getUserName()); userMapper.update(updateUser, updateWrapper); @@ -108,7 +107,7 @@ public class UserServiceImpl implements UserService { Wrapper queryWrapper = Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserName, reqDTO.getUserName()); UserInfo userInfo = userMapper.selectOne(queryWrapper); UserRespDTO respUser = Optional.ofNullable(userInfo) - .map(each -> BeanUtil.toBean(each, UserRespDTO.class)) + .map(each -> BeanUtil.convert(each, UserRespDTO.class)) .orElseThrow(() -> new ServiceException("查询无此用户, 可以尝试清空缓存或退出登录.")); return respUser; } diff --git a/hippo4j-common/pom.xml b/hippo4j-common/pom.xml index 44b46e4d..320c0fba 100644 --- a/hippo4j-common/pom.xml +++ b/hippo4j-common/pom.xml @@ -61,11 +61,6 @@ spring-boot-starter-json - - cn.hutool - hutool-all - - org.springframework.boot spring-boot-starter-test @@ -76,6 +71,11 @@ com.github.ben-manes.caffeine caffeine + + + com.github.dozermapper + dozer-core + diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadFactoryBuilder.java b/hippo4j-common/src/main/java/cn/hippo4j/common/design/builder/ThreadFactoryBuilder.java similarity index 97% rename from hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadFactoryBuilder.java rename to hippo4j-common/src/main/java/cn/hippo4j/common/design/builder/ThreadFactoryBuilder.java index ff78da04..6a9323fb 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/ThreadFactoryBuilder.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/design/builder/ThreadFactoryBuilder.java @@ -15,9 +15,7 @@ * limitations under the License. */ -package cn.hippo4j.core.executor.support; - -import cn.hippo4j.common.design.builder.Builder; +package cn.hippo4j.common.design.builder; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Assert.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Assert.java index 1bff8abf..327152a0 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Assert.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Assert.java @@ -91,6 +91,16 @@ public class Assert { } } + public static void notBlank(String str, String message) { + if (StringUtil.isBlank(str)) { + throw new IllegalArgumentException(message); + } + } + + public static void notBlank(String str) { + notBlank(str, "[Assertion failed] - this string must not be blank"); + } + public static void hasText(String text, String message) { if (!StringUtils.hasText(text)) { throw new IllegalArgumentException(message); diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java new file mode 100644 index 00000000..523f56a9 --- /dev/null +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BeanUtil.java @@ -0,0 +1,152 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 cn.hippo4j.common.toolkit; + +import cn.hippo4j.common.web.exception.IllegalException; +import com.github.dozermapper.core.DozerBeanMapperBuilder; +import com.github.dozermapper.core.Mapper; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import org.springframework.beans.BeanUtils; + +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; +import java.lang.reflect.Method; +import java.util.*; + +/** + * Bean util. + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class BeanUtil { + + protected static Mapper BEAN_MAPPER_BUILDER; + + static { + BEAN_MAPPER_BUILDER = DozerBeanMapperBuilder.buildDefault(); + } + + public static T convert(S source, Class clazz) { + return Optional.ofNullable(source) + .map(each -> BEAN_MAPPER_BUILDER.map(each, clazz)) + .orElse(null); + } + + public static T convert(S source, T target) { + Optional.ofNullable(source) + .ifPresent(each -> BEAN_MAPPER_BUILDER.map(each, target)); + return target; + } + + public static List convert(List sources, Class clazz) { + return Optional.ofNullable(sources) + .map(each -> { + List targetList = new ArrayList(each.size()); + each.forEach(item -> targetList.add(BEAN_MAPPER_BUILDER.map(item, clazz))); + return targetList; + }) + .orElse(null); + } + + public static Set convert(Set sources, Class clazz) { + return Optional.ofNullable(sources) + .map(each -> { + Set targetSize = new HashSet(each.size()); + each.forEach(item -> targetSize.add(BEAN_MAPPER_BUILDER.map(item, clazz))); + return targetSize; + }) + .orElse(null); + } + + public static T mapToBean(Map map, Class clazz, boolean toCamelCase) { + if (clazz == null) { + return null; + } + try { + T newInstance = clazz.newInstance(); + return mapToBean(map, newInstance, toCamelCase); + } catch (InstantiationException | IllegalAccessException e) { + throw new IllegalException("do not create instance for " + clazz.getName(), e); + } + } + + /** + * map to bean + * + * @param map map + * @param bean obj bean + * @param toCamelCase format to camel case + * @param bean type + * @return T + */ + public static T mapToBean(Map map, T bean, boolean toCamelCase) { + if (bean == null) { + return null; + } + if (map.isEmpty()) { + return bean; + } + Class clazz = bean.getClass(); + map.forEach((s, o) -> { + String name = toCamelCase ? StringUtil.toCamelCase(s, StringUtil.UNDERLINE) : s; + Method method = setter(clazz, name); + if (method != null) { + ReflectUtil.invoke(bean, method, o); + } + }); + return bean; + } + + /** + * getter for properties + * + * @param o obj + * @param propertiesName name + * @return Method for get + */ + public static Method getter(Class o, String propertiesName) { + if (o == null) { + return null; + } + try { + PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o); + return descriptor.getReadMethod(); + } catch (IntrospectionException e) { + throw new IllegalException("not find getter for" + propertiesName + "in" + o.getName(), e); + } + } + + /** + * setter for properties + * + * @param o obj + * @param propertiesName name + * @return Method for set + */ + public static Method setter(Class o, String propertiesName) { + if (o == null) { + return null; + } + try { + PropertyDescriptor descriptor = new PropertyDescriptor(propertiesName, o); + return descriptor.getWriteMethod(); + } catch (IntrospectionException e) { + throw new IllegalException("not find setter for" + propertiesName + "in" + o.getName(), e); + } + } +} diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BooleanUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BooleanUtil.java index 7d98a0fa..8885aab5 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BooleanUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/BooleanUtil.java @@ -17,8 +17,6 @@ package cn.hippo4j.common.toolkit; -import cn.hutool.core.util.StrUtil; - import java.util.HashSet; import java.util.Set; @@ -42,7 +40,7 @@ public class BooleanUtil { * @return */ public static boolean toBoolean(String valueStr) { - if (StrUtil.isNotBlank(valueStr)) { + if (StringUtil.isNotBlank(valueStr)) { valueStr = valueStr.trim().toLowerCase(); return TREE_SET.contains(valueStr); } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java index 0177dca4..baa5a02f 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/CollectionUtil.java @@ -18,6 +18,7 @@ package cn.hippo4j.common.toolkit; import java.util.*; +import java.util.stream.Collectors; /** * Collection util. @@ -121,6 +122,21 @@ public class CollectionUtil { return !isEmpty(collection); } + /** + * to list + * + * @param ts elements + * @param type + * @return List + */ + public static List toList(T... ts) { + if (ts == null || ts.length == 0) { + return new ArrayList<>(); + } + return Arrays.stream(ts) + .collect(Collectors.toList()); + } + /** * reference google guava * diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/DateUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/DateUtil.java new file mode 100644 index 00000000..7db6d7c5 --- /dev/null +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/DateUtil.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 cn.hippo4j.common.toolkit; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +/** + * date and time util + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class DateUtil { + + /** + * get time zone for this JVM + */ + private static final TimeZone TIME_ZONE = TimeZone.getDefault(); + + public static final String NORM_DATE_PATTERN = "yyyy-MM-dd"; + + public static final String NORM_TIME_PATTERN = "HH:mm:ss"; + + public static final String NORM_DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + /** + * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT + * represented by this Date object. + * + * @return the number of milliseconds since January 1, 1970, 00:00:00 GMT + * represented by this date. + */ + public static long getTime(LocalDateTime date) { + return getTime(date, TIME_ZONE.toZoneId()); + } + + public static long getTime(LocalDateTime date, ZoneId zoneId) { + return date.atZone(zoneId).toInstant().toEpochMilli(); + + } + + /** + * modify format to date + * + * @param date date + * @param normTimePattern PATTERN + * @return String + */ + public static String format(Date date, String normTimePattern) { + SimpleDateFormat zoneFormat = new SimpleDateFormat(normTimePattern); + return zoneFormat.format(date); + + } +} diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java index 6361c767..1e7d971f 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/FileUtil.java @@ -17,12 +17,15 @@ package cn.hippo4j.common.toolkit; +import cn.hippo4j.common.web.exception.IllegalException; import lombok.SneakyThrows; import org.springframework.core.io.ClassPathResource; -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; +import java.io.*; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; /** * File util; @@ -48,4 +51,38 @@ public class FileUtil { } return resultReadStr; } + + public static List readLines(String path, Charset charset) { + List strList = new ArrayList<>(); + InputStreamReader inputStreamReader = null; + BufferedReader bufferedReader = null; + ClassPathResource classPathResource = new ClassPathResource(path); + try { + inputStreamReader = new InputStreamReader(classPathResource.getInputStream(), charset); + bufferedReader = new BufferedReader(inputStreamReader); + String line; + while ((line = bufferedReader.readLine()) != null) { + strList.add(line); + } + } catch (IOException e) { + e.printStackTrace(); + throw new IllegalException("file read error"); + } finally { + if (inputStreamReader != null) { + try { + inputStreamReader.close(); + } catch (IOException e) { + throw new IllegalException("file read error"); + } + } + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException e) { + throw new IllegalException("file read error"); + } + } + } + return strList; + } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java new file mode 100644 index 00000000..e9bf9a50 --- /dev/null +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/IdUtil.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 cn.hippo4j.common.toolkit; + +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +/** + * id and uuid util,{@link UUID} + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class IdUtil { + + /** + * get a random UUID + * + * @return UUID + */ + public static String randomUUID() { + return toString(UUID.randomUUID(), false); + } + + /** + * get a simple random UUID + * + * @return a simple UUID + */ + public static String simpleUUID() { + return toString(UUID.randomUUID(), true); + } + + /** + * toString + * + * @param uuid UUID + * @return UUID String + */ + public static String toString(UUID uuid, boolean isSimple) { + long mostSigBits = uuid.getMostSignificantBits(); + long leastSigBits = uuid.getLeastSignificantBits(); + if (isSimple) { + return (digits(mostSigBits >> 32, 8) + + digits(mostSigBits >> 16, 4) + + digits(mostSigBits, 4) + + digits(leastSigBits >> 48, 4) + + digits(leastSigBits, 12)); + } else { + return (digits(mostSigBits >> 32, 8) + "-" + + digits(mostSigBits >> 16, 4) + "-" + + digits(mostSigBits, 4) + "-" + + digits(leastSigBits >> 48, 4) + "-" + + digits(leastSigBits, 12)); + } + } + + /** + * Returns val represented by the specified number of hex digits.
+ * {@link UUID#digits(long, int)} + * + * @param val value + * @param digits position + * @return hex value + */ + private static String digits(long val, int digits) { + long hi = 1L << (digits * 4); + return Long.toHexString(hi | (val & (hi - 1))).substring(1); + } +} diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MessageConvert.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MessageConvert.java index fdf529f9..3be85745 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MessageConvert.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/MessageConvert.java @@ -41,7 +41,7 @@ public class MessageConvert { MessageWrapper wrapper = new MessageWrapper(); wrapper.setResponseClass(message.getClass()); wrapper.setMessageType(message.getMessageType()); - List> messageMapList = new ArrayList(); + List> messageMapList = new ArrayList<>(); List messages = message.getMessages(); messages.forEach(each -> { String eachVal = JSONUtil.toJSONString(each); diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java index faca0979..4683ab3c 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/ReflectUtil.java @@ -17,22 +17,27 @@ package cn.hippo4j.common.toolkit; -import cn.hutool.core.convert.Convert; -import cn.hutool.core.exceptions.UtilException; -import cn.hutool.core.util.ClassUtil; +import cn.hippo4j.common.web.exception.IllegalException; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ThreadPoolExecutor; /** * Reflect util. */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class ReflectUtil { - private static final Map, Field[]> FIELDS_CACHE = new ConcurrentHashMap(); + private static final Map, Field[]> FIELDS_CACHE = new ConcurrentHashMap<>(); public static Object getFieldValue(Object obj, String fieldName) { if (null == obj || StringUtil.isBlank(fieldName)) { @@ -55,7 +60,7 @@ public class ReflectUtil { result = field.get(obj); } catch (IllegalAccessException e) { String exceptionMsg = String.format("IllegalAccess for %s.%s", field.getDeclaringClass(), field.getName()); - throw new RuntimeException(exceptionMsg, e); + throw new IllegalException(exceptionMsg, e); } return result; } @@ -69,7 +74,7 @@ public class ReflectUtil { public static Field getField(Class beanClass, String name) throws SecurityException { final Field[] fields = getFields(beanClass); - return ArrayUtil.firstMatch((field) -> name.equals(getFieldName(field)), fields); + return ArrayUtil.firstMatch(field -> name.equals(getFieldName(field)), fields); } public static Field[] getFields(Class beanClass) throws SecurityException { @@ -109,32 +114,114 @@ public class ReflectUtil { return field.getName(); } - public static void setFieldValue(Object obj, String fieldName, Object value) throws UtilException { - cn.hutool.core.lang.Assert.notNull(obj); - cn.hutool.core.lang.Assert.notBlank(fieldName); + public static void setFieldValue(Object obj, String fieldName, Object value) throws IllegalException { + Assert.notNull(obj); + Assert.notBlank(fieldName); final Field field = getField((obj instanceof Class) ? (Class) obj : obj.getClass(), fieldName); - cn.hutool.core.lang.Assert.notNull(field, "Field [{}] is not exist in [{}]", fieldName, obj.getClass().getName()); + Assert.notNull(field, "Field [" + fieldName + "] is not exist in [" + obj.getClass().getName() + "]"); setFieldValue(obj, field, value); } - public static void setFieldValue(Object obj, Field field, Object value) throws UtilException { - cn.hutool.core.lang.Assert.notNull(field, "Field in [{}] not exist !", obj); + public static void setFieldValue(Object obj, Field field, Object value) throws IllegalException { + Assert.notNull(field, "Field in [" + obj + "] not exist !"); final Class fieldType = field.getType(); if (null != value) { if (!fieldType.isAssignableFrom(value.getClass())) { - final Object targetValue = Convert.convert(fieldType, value); + final Object targetValue = cast(fieldType, value); if (null != targetValue) { value = targetValue; } } } else { - value = ClassUtil.getDefaultValue(fieldType); + value = getDefaultValue(fieldType); } setAccessible(field); try { field.set(obj instanceof Class ? null : obj, value); } catch (IllegalAccessException e) { - throw new UtilException(e, "IllegalAccess for {}.{}", obj, field.getName()); + throw new IllegalException("IllegalAccess for " + obj + "." + field.getName(), e); + } + } + + /** + * find the method associated with the method name + * + * @param clazz the class + * @param methodName retrieves the method name + * @param arguments matched parameters class + * @return find method + */ + public static Method getMethodByName(Class clazz, String methodName, Class... arguments) { + try { + if (Objects.nonNull(clazz) && Objects.nonNull(methodName)) { + return clazz.getMethod(methodName, arguments); + } + } catch (NoSuchMethodException e) { + throw new IllegalException(e); + } + return null; + } + + /** + * Cast the value to the type
+ * If a ClassCastException occurs, return null + * + * @param clazz Cast class + * @param value The cast value + * @return The value after the cast is completed + */ + public static Object cast(Class clazz, Object value) { + try { + return clazz.cast(value); + } catch (ClassCastException e) { + return null; + } + } + + /** + * the default value is obtained if it is a primitive type, and NULL if it is not + * + * @param clazz clazz + * @return default value + */ + public static Object getDefaultValue(Class clazz) { + if (Objects.isNull(clazz) || !clazz.isPrimitive()) { + return null; + } + if (long.class.isAssignableFrom(clazz)) { + return 0L; + } else if (int.class.isAssignableFrom(clazz)) { + return 0; + } else if (short.class.isAssignableFrom(clazz)) { + return (short) 0; + } else if (char.class.isAssignableFrom(clazz)) { + return (char) 0; + } else if (byte.class.isAssignableFrom(clazz)) { + return (byte) 0; + } else if (double.class.isAssignableFrom(clazz)) { + return 0D; + } else if (float.class.isAssignableFrom(clazz)) { + return 0f; + } else if (boolean.class.isAssignableFrom(clazz)) { + return false; + } + return null; + } + + /** + * invoke + * + * @param obj the obj + * @param method the method + * @param arguments parameters + * @return result for zhe method + */ + @SuppressWarnings("unchecked") + public static T invoke(Object obj, Method method, Object... arguments) { + try { + return (T) method.invoke(obj, arguments); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new IllegalException(e); } } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Singleton.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Singleton.java index fa36a77a..03633e46 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Singleton.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/Singleton.java @@ -29,7 +29,7 @@ import java.util.function.Supplier; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class Singleton { - private static final ConcurrentHashMap SINGLE_OBJECT_POOL = new ConcurrentHashMap(); + private static final ConcurrentHashMap SINGLE_OBJECT_POOL = new ConcurrentHashMap<>(); /** * Get a singleton object by key. diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/StringUtil.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/StringUtil.java index 74cccf9d..553d2acb 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/StringUtil.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/StringUtil.java @@ -17,6 +17,9 @@ package cn.hippo4j.common.toolkit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** * String util. */ @@ -192,4 +195,84 @@ public class StringUtil { return sb.toString(); } + /** + * to camel case + * + * @param str CharSequence + * @param symbol symbol + * @return toCamelCase String + */ + public static String toCamelCase(CharSequence str, char symbol) { + if (null == str || str.length() == 0) { + return null; + } + int length = str.length(); + StringBuilder sb = new StringBuilder(length); + boolean upperCase = false; + for (int i = 0; i < length; ++i) { + char c = str.charAt(i); + if (c == symbol) { + upperCase = true; + } else if (upperCase) { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } else { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * Replace a portion of the string, replacing all found + * + * @param str A string to operate on + * @param searchStr The replaced string + * @param replaceStr The replaced string + * @return Replace the result + */ + public static String replace(String str, String searchStr, String replaceStr) { + return Pattern + .compile(searchStr, Pattern.LITERAL) + .matcher(str) + .replaceAll(Matcher.quoteReplacement(replaceStr)); + } + + /** + * Tests if this string starts with the specified prefix. + * + * @param str this str + * @param prefix the suffix + * @return Whether the prefix exists + */ + public static boolean startWith(String str, String prefix) { + if (isEmpty(str)) { + return false; + } + return str.startsWith(prefix); + } + + /** + * get the string before the delimiter + * + * @param str string + * @param symbol separator + * @return String + */ + public static String subBefore(String str, String symbol) { + if (isEmpty(str) || symbol == null) { + return str; + } + if (symbol.isEmpty()) { + return EMPTY; + } + int pos = str.indexOf(symbol); + if (-1 == pos) { + return str; + } + if (0 == pos) { + return EMPTY; + } + return str.substring(0, pos); + } } diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/UserContext.java b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/UserContext.java index 67df6909..22c1a286 100644 --- a/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/UserContext.java +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/toolkit/UserContext.java @@ -28,7 +28,7 @@ import java.util.Optional; */ public class UserContext { - private static final ThreadLocal USER_THREAD_LOCAL = new ThreadLocal(); + private static final ThreadLocal USER_THREAD_LOCAL = new ThreadLocal<>(); public static void setUserInfo(String username, String userRole) { USER_THREAD_LOCAL.set(new User(username, userRole)); diff --git a/hippo4j-common/src/main/java/cn/hippo4j/common/web/exception/IllegalException.java b/hippo4j-common/src/main/java/cn/hippo4j/common/web/exception/IllegalException.java new file mode 100644 index 00000000..86250b4a --- /dev/null +++ b/hippo4j-common/src/main/java/cn/hippo4j/common/web/exception/IllegalException.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 cn.hippo4j.common.web.exception; + +/** + * A generic exception to handle illegal operations + */ +public class IllegalException extends RuntimeException { + + private static final long serialVersionUID = 8247610319171014183L; + + public IllegalException() { + super(); + } + + public IllegalException(String message) { + super(message); + } + + public IllegalException(Throwable e) { + super(e.getMessage(), e); + } + + public IllegalException(String message, Throwable throwable) { + super(message, throwable); + } + + public IllegalException(String message, Throwable throwable, boolean enableSuppression, boolean writableStackTrace) { + super(message, throwable, enableSuppression, writableStackTrace); + } + +} diff --git a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/BeanUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BeanUtilTest.java similarity index 67% rename from hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/BeanUtilTest.java rename to hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BeanUtilTest.java index 2c393a03..05caeaf0 100644 --- a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/BeanUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BeanUtilTest.java @@ -15,18 +15,16 @@ * limitations under the License. */ -package cn.hippo4j.config.toolkit; +package cn.hippo4j.common.toolkit; -import cn.hippo4j.common.toolkit.Assert; import com.github.dozermapper.core.converters.ConversionException; import lombok.*; +import org.junit.Assert; import org.junit.Test; +import java.lang.reflect.Method; import java.util.*; -/** - * BeanUtil Test - */ public class BeanUtilTest { @Test @@ -38,10 +36,10 @@ public class BeanUtilTest { person.setAddress("hippo4j.cn"); person.setSize(999); final Map convert = BeanUtil.convert(person, Map.class); - Assert.isTrue(Objects.equals("Hippo4j", convert.get("name"))); - Assert.isTrue(Objects.equals(1, convert.get("age"))); - Assert.isTrue(Objects.equals("hippo4j.cn", convert.get("address"))); - Assert.isTrue(Objects.equals(999, convert.get("size"))); + Assert.assertEquals("Hippo4j", convert.get("name")); + Assert.assertEquals(1, convert.get("age")); + Assert.assertEquals("hippo4j.cn", convert.get("address")); + Assert.assertEquals(999, convert.get("size")); } @Test @@ -53,10 +51,10 @@ public class BeanUtilTest { map.put("address", "hippo4j.cn"); map.put("size", 999); final Person person = BeanUtil.convert(map, Person.class); - Assert.isTrue(Objects.equals("Hippo4j", person.getName())); - Assert.isTrue(Objects.equals(1, person.getAge())); - Assert.isTrue(Objects.equals("hippo4j.cn", person.getAddress())); - Assert.isTrue(Objects.equals(999, person.getSize())); + Assert.assertEquals("Hippo4j", person.getName()); + Assert.assertEquals(1, person.getAge()); + Assert.assertEquals("hippo4j.cn", person.getAddress()); + Assert.assertEquals(999, (int) person.getSize()); } @Test @@ -67,7 +65,7 @@ public class BeanUtilTest { list.add(Person.builder().name("three").age(3).build()); final List persons = BeanUtil.convert(list, PersonVo.class); - Assert.isTrue(Objects.equals(list.size(), persons.size())); + Assert.assertEquals(list.size(), persons.size()); } @Test @@ -78,7 +76,7 @@ public class BeanUtilTest { sets.add(Person.builder().name("three").age(3).build()); final Set persons = BeanUtil.convert(sets, PersonVo.class); - Assert.isTrue(Objects.equals(sets.size(), persons.size())); + Assert.assertEquals(sets.size(), persons.size()); } @Test @@ -88,10 +86,10 @@ public class BeanUtilTest { person.setName("Hippo4j"); final Map convert = BeanUtil.convert(person, Map.class); - Assert.isTrue(Objects.equals("Hippo4j", convert.get("name"))); + Assert.assertEquals("Hippo4j", convert.get("name")); // static属性应被忽略 - Assert.isTrue(!convert.containsKey("STATIC_NAME")); + Assert.assertFalse(convert.containsKey("STATIC_NAME")); } /** @@ -106,6 +104,28 @@ public class BeanUtilTest { // ----------------------------------------------------------------------------------------------------------------- + @Test + public void testMapToBean() { + Map map = new HashMap<>(); + map.put("name", "Test"); + map.put("status_code", 12); + Customer customer = BeanUtil.mapToBean(map, Customer.class, true); + Assert.assertEquals("Test", customer.getName()); + Assert.assertEquals(Integer.valueOf(12), customer.getStatusCode()); + } + + @Test + public void testGetter() { + Method name = BeanUtil.getter(Customer.class, "name"); + Assert.assertEquals("getName", name.getName()); + } + + @Test + public void testSetter() { + Method name = BeanUtil.setter(Customer.class, "name"); + Assert.assertEquals("setName", name.getName()); + } + @Getter @Setter @Builder @@ -127,4 +147,20 @@ public class BeanUtilTest { private String name; private int age; } + + @Getter + @Setter + static class Customer { + + String name; + Integer statusCode; + } + + @Getter + @Setter + static class PreCustomer { + + String name; + Integer statusCode; + } } diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BooleanUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BooleanUtilTest.java index e8112b89..85ff30f5 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BooleanUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/BooleanUtilTest.java @@ -17,19 +17,20 @@ package cn.hippo4j.common.toolkit; +import org.junit.Assert; import org.junit.Test; public class BooleanUtilTest { @Test public void assertToBoolean() { - Assert.isTrue(BooleanUtil.toBoolean("true")); - Assert.isTrue(BooleanUtil.toBoolean("yes")); - Assert.isTrue(BooleanUtil.toBoolean("1")); + Assert.assertTrue(BooleanUtil.toBoolean("true")); + Assert.assertTrue(BooleanUtil.toBoolean("yes")); + Assert.assertTrue(BooleanUtil.toBoolean("1")); } @Test public void assertIsTrue() { - Assert.isTrue(BooleanUtil.isTrue(true)); + Assert.assertTrue(BooleanUtil.isTrue(true)); } } diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/FileUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/FileUtilTest.java index 75b5edf4..b3b15b2e 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/FileUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/FileUtilTest.java @@ -18,6 +18,10 @@ package cn.hippo4j.common.toolkit; import org.junit.Test; +import org.junit.Assert; + +import java.nio.charset.StandardCharsets; +import java.util.List; public class FileUtilTest { @@ -25,7 +29,7 @@ public class FileUtilTest { public void assertReadUtf8String() { String testFilePath = "test/test_utf8.txt"; String contentByFileUtil = FileUtil.readUtf8String(testFilePath); - Assert.notEmpty(contentByFileUtil); + Assert.assertFalse(contentByFileUtil.isEmpty()); } @Test @@ -36,6 +40,13 @@ public class FileUtilTest { "empty line next" + linebreaks; String testFilePath = "test/test_utf8.txt"; String contentByFileUtil = FileUtil.readUtf8String(testFilePath); - Assert.isTrue(testText.equals(contentByFileUtil)); + Assert.assertTrue(testText.equals(contentByFileUtil)); + } + + @Test + public void assertReadLines() { + String testFilePath = "test/test_utf8.txt"; + List readLines = FileUtil.readLines(testFilePath, StandardCharsets.UTF_8); + Assert.assertEquals(3, readLines.size()); } } diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/IdUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/IdUtilTest.java new file mode 100644 index 00000000..79700086 --- /dev/null +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/IdUtilTest.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 cn.hippo4j.common.toolkit; + +import org.junit.Assert; +import org.junit.Test; + +public class IdUtilTest { + + @Test + public void randomUUIDTest() { + String randomUUID = IdUtil.randomUUID(); + Assert.assertNotNull(randomUUID); + } + + @Test + public void simpleUUIDTest() { + String simpleUUID = IdUtil.simpleUUID(); + Assert.assertNotNull(simpleUUID); + Assert.assertFalse(simpleUUID.contains("-")); + } +} \ No newline at end of file diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java index 8f065ab8..104155be 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ReflectUtilTest.java @@ -18,10 +18,12 @@ package cn.hippo4j.common.toolkit; import lombok.Getter; +import lombok.Setter; import org.junit.Test; +import org.junit.Assert; import java.lang.reflect.Field; -import java.util.Objects; +import java.lang.reflect.Method; public class ReflectUtilTest { @@ -29,10 +31,10 @@ public class ReflectUtilTest { public void getFieldValueTest() { TestSubClass testSubClass = new TestSubClass(); Object privateField = ReflectUtil.getFieldValue(testSubClass, "privateField"); - Assert.isTrue(Objects.equals("privateField", privateField)); + Assert.assertEquals("privateField", privateField); Object field = ReflectUtil.getFieldValue(testSubClass, "field"); - Assert.isTrue(Objects.equals("field", field)); + Assert.assertEquals("field", field); } @@ -42,57 +44,99 @@ public class ReflectUtilTest { Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField"); Object privateFieldVal = ReflectUtil.getFieldValue(testSubClass, privateField); - Assert.isTrue(Objects.equals("privateField", privateFieldVal)); + Assert.assertEquals("privateField", privateFieldVal); } @Test public void getFieldTest() { Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField"); - Assert.notNull(privateField); + Assert.assertNotNull(privateField); Field field = ReflectUtil.getField(TestSubClass.class, "field"); - Assert.notNull(field); + Assert.assertNotNull(field); } @Test public void getFieldsTest() { Field[] fields = ReflectUtil.getFields(TestSubClass.class); - Assert.isTrue(Objects.equals(4, fields.length)); + Assert.assertEquals(4, fields.length); } @Test public void getFieldsDirectlyTest() { Field[] fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, false); - Assert.isTrue(Objects.equals(2, fields.length)); + Assert.assertEquals(2, fields.length); fields = ReflectUtil.getFieldsDirectly(TestSubClass.class, true); - Assert.isTrue(Objects.equals(4, fields.length)); + Assert.assertEquals(4, fields.length); } @Test public void getFieldNameTest() { Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField"); String fieldName = ReflectUtil.getFieldName(privateField); - Assert.notNull(fieldName); + Assert.assertNotNull(fieldName); Field subField = ReflectUtil.getField(TestSubClass.class, "subField"); String subfieldName = ReflectUtil.getFieldName(subField); - Assert.notNull(subfieldName); + Assert.assertNotNull(subfieldName); } @Test public void setFieldValueTest() { TestClass testClass = new TestClass(); ReflectUtil.setFieldValue(testClass, "field", "fieldVal"); - Assert.isTrue(Objects.equals("fieldVal", testClass.getField())); + Assert.assertEquals("fieldVal", testClass.getField()); Field privateField = ReflectUtil.getField(TestSubClass.class, "privateField"); ReflectUtil.setFieldValue(testClass, privateField, "privateFieldVal"); - Assert.isTrue(Objects.equals("privateFieldVal", testClass.getPrivateField())); + Assert.assertEquals("privateFieldVal", testClass.getPrivateField()); } + @Test + public void castTest() { + TestClass testClass = new TestSubClass(); + Object cast = ReflectUtil.cast(TestSubClass.class, testClass); + Assert.assertTrue(cast instanceof TestSubClass); + } + + @Test + public void getDefaultValueTest() { + Object defaultValue = ReflectUtil.getDefaultValue(Long.class); + Assert.assertNull(defaultValue); + Object primitiveValueLong = ReflectUtil.getDefaultValue(long.class); + Assert.assertEquals(0L, primitiveValueLong); + Object primitiveValueInt = ReflectUtil.getDefaultValue(int.class); + Assert.assertEquals(0, primitiveValueInt); + Object primitiveValueFloat = ReflectUtil.getDefaultValue(float.class); + Assert.assertEquals(0f, primitiveValueFloat); + Object primitiveValueShort = ReflectUtil.getDefaultValue(short.class); + Assert.assertEquals((short) 0, primitiveValueShort); + Object primitiveValueChar = ReflectUtil.getDefaultValue(char.class); + Assert.assertEquals((char) 0, primitiveValueChar); + Object primitiveValueDouble = ReflectUtil.getDefaultValue(double.class); + Assert.assertEquals(0D, primitiveValueDouble); + Object primitiveValueBoolean = ReflectUtil.getDefaultValue(boolean.class); + Assert.assertEquals(false, primitiveValueBoolean); + } + + @Test + public void getMethodByNameTest() { + Method field = ReflectUtil.getMethodByName(TestClass.class, "setPrivateField", String.class); + Assert.assertNotNull(field); + } + + @Test + public void invokeTest() { + TestClass testClass = new TestClass(); + Method method = ReflectUtil.getMethodByName(TestClass.class, "getPrivateField"); + String invoke = ReflectUtil.invoke(testClass, method); + Assert.assertEquals(invoke, "privateField"); + } + @Getter + @Setter static class TestClass { private String privateField; diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java index 7c0067ff..d2f9173c 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/StringUtilTest.java @@ -90,4 +90,11 @@ public class StringUtilTest { String s = StringUtil.toSymbolCase(string, StringUtil.UNDERLINE); Assert.isTrue(Objects.equals(s, "str")); } + + @Test + public void toCamelCase() { + String string = "str_str"; + String s = StringUtil.toCamelCase(string, StringUtil.UNDERLINE); + Assert.isTrue(Objects.equals(s, "strStr")); + } } diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ThreadUtilTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ThreadUtilTest.java index e428a733..88c2890a 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ThreadUtilTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/ThreadUtilTest.java @@ -18,8 +18,7 @@ package cn.hippo4j.common.toolkit; import org.junit.Test; - -import static org.junit.Assert.assertTrue; +import org.junit.Assert; public class ThreadUtilTest { @@ -32,11 +31,11 @@ public class ThreadUtilTest { final Thread result = ThreadUtil.newThread(runnable, "name", false); // Verify the results - Assert.notNull(result); + Assert.assertNotNull(result); } @Test public void testSleep() { - assertTrue(ThreadUtil.sleep(0L)); + Assert.assertTrue(ThreadUtil.sleep(0L)); } } diff --git a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/UserContextTest.java b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/UserContextTest.java index 83543573..a361d139 100644 --- a/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/UserContextTest.java +++ b/hippo4j-common/src/test/java/cn/hippo4j/common/toolkit/UserContextTest.java @@ -17,11 +17,8 @@ package cn.hippo4j.common.toolkit; -import cn.hutool.core.util.ReflectUtil; import org.junit.jupiter.api.Test; -import java.lang.reflect.Field; - public class UserContextTest { private static final String USERNAME = "test"; diff --git a/hippo4j-config/pom.xml b/hippo4j-config/pom.xml index c145134f..e999ccdd 100644 --- a/hippo4j-config/pom.xml +++ b/hippo4j-config/pom.xml @@ -49,22 +49,6 @@ runtime - - cn.hutool - hutool-all - - - - cn.hippo4j - hippo4j-common - ${revision} - - - - com.github.dozermapper - dozer-core - - org.projectlombok lombok @@ -80,6 +64,11 @@ netty-all + + org.apache.httpcomponents + httpclient + + org.hibernate.validator hibernate-validator diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/controller/ConfigController.java b/hippo4j-config/src/main/java/cn/hippo4j/config/controller/ConfigController.java index 5c0fe84f..25543ee8 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/controller/ConfigController.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/controller/ConfigController.java @@ -19,6 +19,7 @@ package cn.hippo4j.config.controller; import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.model.register.DynamicThreadPoolRegisterWrapper; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.config.model.ConfigAllInfo; @@ -27,7 +28,6 @@ import cn.hippo4j.config.service.ConfigCacheService; import cn.hippo4j.config.service.ConfigServletInner; import cn.hippo4j.config.service.biz.ConfigService; import cn.hippo4j.config.toolkit.Md5ConfigUtil; -import cn.hutool.core.util.StrUtil; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import org.springframework.util.StringUtils; @@ -87,7 +87,7 @@ public class ConfigController { @PostMapping("/remove/config/cache") public Result removeConfigCache(@RequestBody Map bodyMap) { String groupKey = bodyMap.get(Constants.GROUP_KEY); - if (StrUtil.isNotBlank(groupKey)) { + if (StringUtil.isNotBlank(groupKey)) { ConfigCacheService.removeConfigCache(groupKey); } return Results.success(); diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java b/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java index 6aa4df3f..f97fe5d0 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/monitor/TimeCleanHistoryDataTask.java @@ -18,11 +18,10 @@ package cn.hippo4j.config.monitor; import cn.hippo4j.common.executor.ExecutorFactory; +import cn.hippo4j.common.toolkit.DateUtil; import cn.hippo4j.config.config.ServerBootstrapProperties; import cn.hippo4j.config.model.HisRunDataInfo; import cn.hippo4j.config.service.biz.HisRunDataService; -import cn.hutool.core.date.DateTime; -import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.NonNull; @@ -30,6 +29,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; +import java.time.LocalDateTime; import java.util.Date; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -53,10 +53,9 @@ public class TimeCleanHistoryDataTask implements Runnable, InitializingBean { @Override public void run() { - Date currentDate = new Date(); - DateTime offsetMinuteDateTime = DateUtil.offsetMinute(currentDate, -properties.getCleanHistoryDataPeriod()); + LocalDateTime offsetMinuteDateTime = LocalDateTime.now().plusMinutes(-properties.getCleanHistoryDataPeriod()); LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(HisRunDataInfo.class) - .le(HisRunDataInfo::getTimestamp, offsetMinuteDateTime.getTime()); + .le(HisRunDataInfo::getTimestamp, DateUtil.getTime(offsetMinuteDateTime)); hisRunDataService.remove(queryWrapper); } diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultPublisher.java b/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultPublisher.java index 6c2860ff..7b8f67e6 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultPublisher.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultPublisher.java @@ -18,11 +18,13 @@ package cn.hippo4j.config.notify; import cn.hippo4j.config.event.AbstractEvent; -import cn.hutool.core.collection.ConcurrentHashSet; import cn.hippo4j.config.notify.listener.AbstractSubscriber; import lombok.extern.slf4j.Slf4j; import org.springframework.util.CollectionUtils; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; @@ -34,7 +36,7 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; @Slf4j public class DefaultPublisher extends Thread implements EventPublisher { - protected final ConcurrentHashSet subscribers = new ConcurrentHashSet(); + protected final Set subscribers = Collections.synchronizedSet(new HashSet<>()); private BlockingQueue queue; diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultSharePublisher.java b/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultSharePublisher.java index b877bfbb..185a6352 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultSharePublisher.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/notify/DefaultSharePublisher.java @@ -18,10 +18,11 @@ package cn.hippo4j.config.notify; import cn.hippo4j.config.event.AbstractEvent; -import cn.hutool.core.collection.ConcurrentHashSet; import cn.hippo4j.config.notify.listener.AbstractSubscriber; import cn.hippo4j.config.event.AbstractSlowEvent; +import java.util.Collections; +import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -35,7 +36,7 @@ public class DefaultSharePublisher extends DefaultPublisher { private final Map, Set> subMappings = new ConcurrentHashMap(); - protected final ConcurrentHashSet subscribers = new ConcurrentHashSet(); + protected final Set subscribers = Collections.synchronizedSet(new HashSet<>()); private final Lock lock = new ReentrantLock(); @@ -46,7 +47,7 @@ public class DefaultSharePublisher extends DefaultPublisher { try { Set sets = subMappings.get(subSlowEventType); if (sets == null) { - Set newSet = new ConcurrentHashSet(); + Set newSet = Collections.synchronizedSet(new HashSet<>()); newSet.add(subscriber); subMappings.put(subSlowEventType, newSet); return; diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java index 3d154c72..edeb7ef2 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/ConfigCacheService.java @@ -26,14 +26,13 @@ import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.Joiner; import cn.hippo4j.common.toolkit.Md5Util; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.event.LocalDataChangeEvent; import cn.hippo4j.config.model.CacheItem; import cn.hippo4j.config.model.ConfigAllInfo; import cn.hippo4j.config.notify.NotifyCenter; import cn.hippo4j.config.service.biz.ConfigService; import cn.hippo4j.config.toolkit.MapUtil; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; @@ -79,7 +78,7 @@ public class ConfigCacheService { private synchronized static String getContentMd5IsNullPut(String groupKey, String clientIdentify) { Map cacheItemMap = Optional.ofNullable(CLIENT_CONFIG_CACHE.get(groupKey)).orElse(new HashMap<>()); CacheItem cacheItem = null; - if (CollUtil.isNotEmpty(cacheItemMap) && (cacheItem = cacheItemMap.get(clientIdentify)) != null) { + if (CollectionUtil.isNotEmpty(cacheItemMap) && (cacheItem = cacheItemMap.get(clientIdentify)) != null) { return cacheItem.md5; } if (CONFIG_SERVICE == null) { @@ -87,7 +86,7 @@ public class ConfigCacheService { } String[] params = groupKey.split(GROUP_KEY_DELIMITER_TRANSLATION); ConfigAllInfo config = CONFIG_SERVICE.findConfigRecentInfo(params); - if (config != null && StrUtil.isNotBlank(config.getTpId())) { + if (config != null && StringUtil.isNotBlank(config.getTpId())) { cacheItem = new CacheItem(groupKey, config); cacheItemMap.put(clientIdentify, cacheItem); CLIENT_CONFIG_CACHE.put(groupKey, cacheItemMap); diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java index c56a9242..5e8fd0fd 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/LongPollingService.java @@ -20,6 +20,7 @@ package cn.hippo4j.config.service; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.Md5Util; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.config.event.AbstractEvent; import cn.hippo4j.config.event.LocalDataChangeEvent; @@ -29,8 +30,6 @@ import cn.hippo4j.config.toolkit.ConfigExecutor; import cn.hippo4j.config.toolkit.MapUtil; import cn.hippo4j.config.toolkit.Md5ConfigUtil; import cn.hippo4j.config.toolkit.RequestUtil; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.StrUtil; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -118,7 +117,7 @@ public class LongPollingService { ClientLongPolling clientSub = iter.next(); String identity = groupKey + GROUP_KEY_DELIMITER + identify; List parseMapForFilter = CollectionUtil.newArrayList(identity); - if (StrUtil.isBlank(identify)) { + if (StringUtil.isBlank(identify)) { parseMapForFilter = MapUtil.parseMapForFilter(clientSub.clientMd5Map, groupKey); } parseMapForFilter.forEach(each -> { @@ -274,7 +273,7 @@ public class LongPollingService { * @param changedGroups Changed thread pool group key */ private void generateResponse(HttpServletResponse response, List changedGroups) { - if (CollUtil.isNotEmpty(changedGroups)) { + if (CollectionUtil.isNotEmpty(changedGroups)) { try { String respStr = buildRespStr(changedGroups); response.setHeader("Pragma", "no-cache"); diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java index 4744a3ee..d94cc2e6 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/ThreadPoolAdapterService.java @@ -28,11 +28,11 @@ import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO; -import cn.hutool.core.text.StrBuilder; -import cn.hutool.http.HttpUtil; import com.fasterxml.jackson.core.type.TypeReference; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -98,12 +98,18 @@ public class ThreadPoolAdapterService { List addressList = actual.stream().map(ThreadPoolAdapterState::getClientAddress).collect(Collectors.toList()); List result = new ArrayList<>(addressList.size()); addressList.forEach(each -> { - String urlString = StrBuilder.create("http://", each, "/adapter/thread-pool/info").toString(); + String urlString = new StringBuilder() + .append("http://") + .append(each) + .append("/adapter/thread-pool/info") + .toString(); Map param = new HashMap<>(); param.put("mark", requestParameter.getMark()); param.put("threadPoolKey", requestParameter.getThreadPoolKey()); try { - String resultStr = HttpUtil.get(urlString, param, HTTP_EXECUTE_TIMEOUT); + + RestTemplate template = new RestTemplate(); + String resultStr = template.getForObject(urlString, String.class, param); if (StringUtil.isNotBlank(resultStr)) { Result restResult = JSONUtil.parseObject(resultStr, new TypeReference>() { }); diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java index 14bd700c..bf70a5b9 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ConfigServiceImpl.java @@ -35,8 +35,7 @@ import cn.hippo4j.config.model.biz.notify.NotifyReqDTO; import cn.hippo4j.config.service.ConfigCacheService; import cn.hippo4j.config.service.ConfigChangePublisher; import cn.hippo4j.config.service.biz.*; -import cn.hippo4j.config.toolkit.BeanUtil; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; @@ -72,9 +71,9 @@ public class ConfigServiceImpl implements ConfigService { @Override public ConfigAllInfo findConfigAllInfo(String tpId, String itemId, String tenantId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ConfigAllInfo.class) - .eq(StrUtil.isNotBlank(tpId), ConfigAllInfo::getTpId, tpId) - .eq(StrUtil.isNotBlank(itemId), ConfigAllInfo::getItemId, itemId) - .eq(StrUtil.isNotBlank(tenantId), ConfigAllInfo::getTenantId, tenantId); + .eq(StringUtil.isNotBlank(tpId), ConfigAllInfo::getTpId, tpId) + .eq(StringUtil.isNotBlank(itemId), ConfigAllInfo::getItemId, itemId) + .eq(StringUtil.isNotBlank(tenantId), ConfigAllInfo::getTenantId, tenantId); ConfigAllInfo configAllInfo = configInfoMapper.selectOne(wrapper); return configAllInfo; } @@ -84,7 +83,7 @@ public class ConfigServiceImpl implements ConfigService { ConfigAllInfo resultConfig; ConfigAllInfo configInstance = null; String instanceId = params[3]; - if (StrUtil.isNotBlank(instanceId)) { + if (StringUtil.isNotBlank(instanceId)) { LambdaQueryWrapper instanceQueryWrapper = Wrappers.lambdaQuery(ConfigInstanceInfo.class) .eq(ConfigInstanceInfo::getTpId, params[0]) .eq(ConfigInstanceInfo::getItemId, params[1]) diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/HisRunDataServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/HisRunDataServiceImpl.java index a22eb9ed..1c4c93af 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/HisRunDataServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/HisRunDataServiceImpl.java @@ -20,6 +20,7 @@ package cn.hippo4j.config.service.biz.impl; import cn.hippo4j.common.monitor.Message; import cn.hippo4j.common.monitor.MessageWrapper; import cn.hippo4j.common.monitor.RuntimeMessage; +import cn.hippo4j.common.toolkit.DateUtil; import cn.hippo4j.common.toolkit.GroupKey; import cn.hippo4j.common.toolkit.MessageConvert; import cn.hippo4j.common.web.base.Result; @@ -32,21 +33,20 @@ import cn.hippo4j.config.model.biz.monitor.MonitorQueryReqDTO; import cn.hippo4j.config.model.biz.monitor.MonitorRespDTO; import cn.hippo4j.config.monitor.QueryMonitorExecuteChoose; import cn.hippo4j.config.service.biz.HisRunDataService; -import cn.hippo4j.config.toolkit.BeanUtil; -import cn.hutool.core.date.DateTime; -import cn.hutool.core.date.DateUtil; +import cn.hippo4j.common.toolkit.BeanUtil; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.AllArgsConstructor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -import static cn.hutool.core.date.DatePattern.NORM_TIME_PATTERN; +import static cn.hippo4j.common.toolkit.DateUtil.NORM_TIME_PATTERN; /** * His run data service impl. @@ -63,15 +63,15 @@ public class HisRunDataServiceImpl extends ServiceImpl query(MonitorQueryReqDTO reqDTO) { - Date currentDate = new Date(); - DateTime dateTime = DateUtil.offsetMinute(currentDate, -properties.getCleanHistoryDataPeriod()); - long startTime = dateTime.getTime(); + LocalDateTime currentDate = LocalDateTime.now(); + LocalDateTime dateTime = currentDate.plusMinutes(-properties.getCleanHistoryDataPeriod()); + long startTime = DateUtil.getTime(dateTime); List hisRunDataInfos = this.lambdaQuery() .eq(HisRunDataInfo::getTenantId, reqDTO.getTenantId()) .eq(HisRunDataInfo::getItemId, reqDTO.getItemId()) .eq(HisRunDataInfo::getTpId, reqDTO.getTpId()) .eq(HisRunDataInfo::getInstanceId, reqDTO.getInstanceId()) - .between(HisRunDataInfo::getTimestamp, startTime, currentDate.getTime()) + .between(HisRunDataInfo::getTimestamp, startTime, DateUtil.getTime(currentDate)) .orderByAsc(HisRunDataInfo::getTimestamp) .list(); return BeanUtil.convert(hisRunDataInfos, MonitorRespDTO.class); @@ -79,15 +79,15 @@ public class HisRunDataServiceImpl extends ServiceImpl hisRunDataInfos = this.lambdaQuery() .eq(HisRunDataInfo::getTenantId, reqDTO.getTenantId()) .eq(HisRunDataInfo::getItemId, reqDTO.getItemId()) .eq(HisRunDataInfo::getTpId, reqDTO.getTpId()) .eq(HisRunDataInfo::getInstanceId, reqDTO.getInstanceId()) - .between(HisRunDataInfo::getTimestamp, startTime, currentDate.getTime()) + .between(HisRunDataInfo::getTimestamp, startTime, DateUtil.getTime(currentDate)) .orderByAsc(HisRunDataInfo::getTimestamp) .list(); List times = new ArrayList<>(); @@ -127,16 +127,16 @@ public class HisRunDataServiceImpl extends ServiceImpl { String[] parseKey = GroupKey.parseKey(each); List notifyInfos = listNotifyCommon("CONFIG", parseKey); - if (CollUtil.isNotEmpty(notifyInfos)) { - notifyListRespList.add(new NotifyListRespDTO(StrUtil.builder(parseKey[0], "+", "CONFIG").toString(), notifyInfos)); + if (CollectionUtil.isNotEmpty(notifyInfos)) { + notifyListRespList.add(new NotifyListRespDTO(parseKey[0] + "+" + "CONFIG", notifyInfos)); } List alarmInfos = listNotifyCommon("ALARM", parseKey); - if (CollUtil.isNotEmpty(alarmInfos)) { - notifyListRespList.add(new NotifyListRespDTO(StrUtil.builder(parseKey[0], "+", "ALARM").toString(), alarmInfos)); + if (CollectionUtil.isNotEmpty(alarmInfos)) { + notifyListRespList.add(new NotifyListRespDTO(parseKey[0] + "+" + "ALARM", alarmInfos)); } }); return notifyListRespList; @@ -72,9 +72,9 @@ public class NotifyServiceImpl implements NotifyService { @Override public IPage queryPage(NotifyQueryReqDTO reqDTO) { LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(NotifyInfo.class) - .eq(StrUtil.isNotBlank(reqDTO.getTenantId()), NotifyInfo::getTenantId, reqDTO.getTenantId()) - .eq(StrUtil.isNotBlank(reqDTO.getItemId()), NotifyInfo::getItemId, reqDTO.getItemId()) - .eq(StrUtil.isNotBlank(reqDTO.getTpId()), NotifyInfo::getTpId, reqDTO.getTpId()) + .eq(StringUtil.isNotBlank(reqDTO.getTenantId()), NotifyInfo::getTenantId, reqDTO.getTenantId()) + .eq(StringUtil.isNotBlank(reqDTO.getItemId()), NotifyInfo::getItemId, reqDTO.getItemId()) + .eq(StringUtil.isNotBlank(reqDTO.getTpId()), NotifyInfo::getTpId, reqDTO.getTpId()) .orderByDesc(NotifyInfo::getGmtCreate); IPage resultPage = notifyInfoMapper.selectPage(reqDTO, queryWrapper); return resultPage.convert(each -> { @@ -173,7 +173,7 @@ public class NotifyServiceImpl implements NotifyService { .eq(NotifyInfo::getPlatform, requestParam.getPlatform()) .eq(NotifyInfo::getType, type); List existNotifyInfos = notifyInfoMapper.selectList(queryWrapper); - if (CollUtil.isNotEmpty(existNotifyInfos)) { + if (CollectionUtil.isNotEmpty(existNotifyInfos)) { throw new ServiceException(String.format("%s 新增通知报警配置重复", type)); } } diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/OperationLogServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/OperationLogServiceImpl.java index 10276d72..7cadd49e 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/OperationLogServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/OperationLogServiceImpl.java @@ -17,13 +17,13 @@ package cn.hippo4j.config.service.biz.impl; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.mapper.OperationLogMapper; import cn.hippo4j.config.model.LogRecordInfo; import cn.hippo4j.config.model.biz.log.LogRecordQueryReqDTO; import cn.hippo4j.config.model.biz.log.LogRecordRespDTO; import cn.hippo4j.config.service.biz.OperationLogService; -import cn.hippo4j.config.toolkit.BeanUtil; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; @@ -42,9 +42,9 @@ public class OperationLogServiceImpl implements OperationLogService { @Override public IPage queryPage(LogRecordQueryReqDTO pageQuery) { LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(LogRecordInfo.class) - .eq(StrUtil.isNotBlank(pageQuery.getBizNo()), LogRecordInfo::getBizNo, pageQuery.getBizNo()) - .eq(StrUtil.isNotBlank(pageQuery.getCategory()), LogRecordInfo::getCategory, pageQuery.getCategory()) - .eq(StrUtil.isNotBlank(pageQuery.getOperator()), LogRecordInfo::getOperator, pageQuery.getOperator()) + .eq(StringUtil.isNotBlank(pageQuery.getBizNo()), LogRecordInfo::getBizNo, pageQuery.getBizNo()) + .eq(StringUtil.isNotBlank(pageQuery.getCategory()), LogRecordInfo::getCategory, pageQuery.getCategory()) + .eq(StringUtil.isNotBlank(pageQuery.getOperator()), LogRecordInfo::getOperator, pageQuery.getOperator()) .orderByDesc(LogRecordInfo::getCreateTime); IPage selectPage = operationLogMapper.selectPage(pageQuery, queryWrapper); return selectPage.convert(each -> BeanUtil.convert(each, LogRecordRespDTO.class)); diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/TenantServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/TenantServiceImpl.java index f3a0baa6..1945562d 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/TenantServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/TenantServiceImpl.java @@ -29,7 +29,7 @@ import cn.hippo4j.config.model.biz.tenant.TenantSaveReqDTO; import cn.hippo4j.config.model.biz.tenant.TenantUpdateReqDTO; import cn.hippo4j.config.service.biz.ItemService; import cn.hippo4j.config.service.biz.TenantService; -import cn.hippo4j.config.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ThreadPoolServiceImpl.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ThreadPoolServiceImpl.java index b26016b9..8c58e935 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ThreadPoolServiceImpl.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/biz/impl/ThreadPoolServiceImpl.java @@ -30,7 +30,7 @@ import cn.hippo4j.config.model.biz.threadpool.ThreadPoolSaveOrUpdateReqDTO; import cn.hippo4j.config.service.biz.ConfigService; import cn.hippo4j.config.service.biz.OperationLogService; import cn.hippo4j.config.service.biz.ThreadPoolService; -import cn.hippo4j.config.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.BeanUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.StringUtils; diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/service/handler/ClientCloseHookRemoveConfigCache.java b/hippo4j-config/src/main/java/cn/hippo4j/config/service/handler/ClientCloseHookRemoveConfigCache.java index d67ab517..7f8e8ca1 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/service/handler/ClientCloseHookRemoveConfigCache.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/service/handler/ClientCloseHookRemoveConfigCache.java @@ -19,8 +19,8 @@ package cn.hippo4j.config.service.handler; import cn.hippo4j.common.api.ClientCloseHookExecute; import cn.hippo4j.common.toolkit.JSONUtil; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.service.ConfigCacheService; -import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @@ -36,7 +36,7 @@ public class ClientCloseHookRemoveConfigCache implements ClientCloseHookExecute log.info("Remove Config Cache, Execute client hook function. Request: {}", JSONUtil.toJSONString(requestParam)); try { String groupKey = requestParam.getGroupKey(); - if (StrUtil.isNotBlank(groupKey)) { + if (StringUtil.isNotBlank(groupKey)) { ConfigCacheService.removeConfigCache(groupKey); } } catch (Exception ex) { diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/BeanUtil.java b/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/BeanUtil.java deleted file mode 100644 index ad4c3879..00000000 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/BeanUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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 cn.hippo4j.config.toolkit; - -import com.github.dozermapper.core.DozerBeanMapperBuilder; -import com.github.dozermapper.core.Mapper; - -import java.util.*; - -/** - * Bean util. - */ -public class BeanUtil { - - private BeanUtil() { - - } - - protected static Mapper BEAN_MAPPER_BUILDER; - - static { - BEAN_MAPPER_BUILDER = DozerBeanMapperBuilder.buildDefault(); - } - - public static T convert(S source, Class clazz) { - return Optional.ofNullable(source) - .map(each -> BEAN_MAPPER_BUILDER.map(each, clazz)) - .orElse(null); - } - - public static List convert(List sources, Class clazz) { - return Optional.ofNullable(sources) - .map(each -> { - List targetList = new ArrayList(each.size()); - each.stream() - .forEach(item -> targetList.add(BEAN_MAPPER_BUILDER.map(item, clazz))); - return targetList; - }) - .orElse(null); - } - - public static Set convert(Set sources, Class clazz) { - return Optional.ofNullable(sources) - .map(each -> { - Set targetSize = new HashSet(each.size()); - each.stream() - .forEach(item -> targetSize.add(BEAN_MAPPER_BUILDER.map(item, clazz))); - return targetSize; - }) - .orElse(null); - } -} diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/MapUtil.java b/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/MapUtil.java index 613ec640..f66aef67 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/MapUtil.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/MapUtil.java @@ -17,7 +17,7 @@ package cn.hippo4j.config.toolkit; -import cn.hutool.core.collection.CollUtil; +import cn.hippo4j.common.toolkit.CollectionUtil; import java.util.ArrayList; import java.util.List; @@ -54,7 +54,7 @@ public class MapUtil { */ public static List parseMapForFilter(Map sourceMap, String filters) { List resultList = new ArrayList<>(); - if (CollUtil.isEmpty(sourceMap)) { + if (CollectionUtil.isEmpty(sourceMap)) { return resultList; } sourceMap.forEach((key, val) -> { diff --git a/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/RequestUtil.java b/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/RequestUtil.java index 85d369cf..cf79e888 100644 --- a/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/RequestUtil.java +++ b/hippo4j-config/src/main/java/cn/hippo4j/config/toolkit/RequestUtil.java @@ -17,7 +17,7 @@ package cn.hippo4j.config.toolkit; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.StringUtil; import javax.servlet.http.HttpServletRequest; @@ -36,6 +36,6 @@ public class RequestUtil { public static String getClientIdentify(HttpServletRequest request) { String identify = request.getHeader(LONG_PULLING_CLIENT_IDENTIFICATION); - return StrUtil.isBlank(identify) ? "" : identify; + return StringUtil.isBlank(identify) ? "" : identify; } } diff --git a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/ClassUtilTest.java b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/ClassUtilTest.java index cffb82b1..66a0f5ea 100644 --- a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/ClassUtilTest.java +++ b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/ClassUtilTest.java @@ -18,7 +18,6 @@ package cn.hippo4j.config.toolkit; import cn.hippo4j.common.toolkit.Assert; -import cn.hutool.core.lang.caller.CallerUtil; import org.junit.Test; import java.util.Objects; diff --git a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/EnvUtilTest.java b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/EnvUtilTest.java index 109ee0ba..f65e9c5b 100644 --- a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/EnvUtilTest.java +++ b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/EnvUtilTest.java @@ -18,7 +18,7 @@ package cn.hippo4j.config.toolkit; import cn.hippo4j.common.toolkit.Assert; -import cn.hutool.core.util.StrUtil; +import cn.hippo4j.common.toolkit.StringUtil; import org.junit.Test; /** @@ -29,7 +29,7 @@ public class EnvUtilTest { @Test public void getHippo4JHomeTest() { String hippo4JHome = EnvUtil.getHippo4JHome(); - Assert.isTrue(StrUtil.isNotBlank(hippo4JHome)); + Assert.isTrue(StringUtil.isNotBlank(hippo4JHome)); } @Test diff --git a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/MapUtilTest.java b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/MapUtilTest.java index 58980692..440b84dd 100644 --- a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/MapUtilTest.java +++ b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/MapUtilTest.java @@ -18,7 +18,7 @@ package cn.hippo4j.config.toolkit; import cn.hippo4j.common.toolkit.Assert; -import cn.hutool.core.collection.CollectionUtil; +import cn.hippo4j.common.toolkit.CollectionUtil; import org.junit.Test; import java.util.HashMap; diff --git a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/Md5ConfigUtilTest.java b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/Md5ConfigUtilTest.java index 5bfd5055..867b13d7 100644 --- a/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/Md5ConfigUtilTest.java +++ b/hippo4j-config/src/test/java/cn/hippo4j/config/toolkit/Md5ConfigUtilTest.java @@ -18,8 +18,8 @@ package cn.hippo4j.config.toolkit; import cn.hippo4j.common.toolkit.Assert; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.model.ConfigAllInfo; -import cn.hutool.core.util.StrUtil; import org.assertj.core.util.Lists; import org.junit.Test; @@ -67,7 +67,7 @@ public class Md5ConfigUtilTest { } catch (IOException ignored) { } - Assert.isTrue(Objects.equals(StrUtil.EMPTY, key)); + Assert.isTrue(Objects.equals(StringUtil.EMPTY, key)); } @Test @@ -86,7 +86,7 @@ public class Md5ConfigUtilTest { ConfigAllInfo configAllInfo = new ConfigAllInfo(); configAllInfo.setDesc("hippo4j config"); String tpContentMd5 = Md5ConfigUtil.getTpContentMd5(configAllInfo); - Assert.isTrue(StrUtil.isNotEmpty(tpContentMd5)); + Assert.isTrue(StringUtil.isNotEmpty(tpContentMd5)); } } diff --git a/hippo4j-console/pom.xml b/hippo4j-console/pom.xml index dbadd05e..3d9a8b08 100644 --- a/hippo4j-console/pom.xml +++ b/hippo4j-console/pom.xml @@ -37,10 +37,6 @@ hibernate-validator - - cn.hutool - hutool-all - diff --git a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java index f743ae85..8937a004 100644 --- a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java +++ b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolAdapterController.java @@ -23,14 +23,14 @@ import cn.hippo4j.common.web.base.Results; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterReqDTO; import cn.hippo4j.config.model.biz.adapter.ThreadPoolAdapterRespDTO; import cn.hippo4j.config.service.ThreadPoolAdapterService; -import cn.hutool.core.text.StrBuilder; -import cn.hutool.http.HttpUtil; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; +import java.util.HashMap; import java.util.List; import java.util.Set; @@ -46,6 +46,8 @@ public class ThreadPoolAdapterController { private final ThreadPoolAdapterService threadPoolAdapterService; + private final RestTemplate restTemplate = new RestTemplate(); + @GetMapping(REGISTER_ADAPTER_BASE_PATH + "/query") public Result> queryAdapterThreadPool(ThreadPoolAdapterReqDTO requestParameter) { List result = threadPoolAdapterService.query(requestParameter); @@ -61,8 +63,12 @@ public class ThreadPoolAdapterController { @PostMapping(REGISTER_ADAPTER_BASE_PATH + "/update") public Result updateAdapterThreadPool(@RequestBody ThreadPoolAdapterReqDTO requestParameter) { for (String each : requestParameter.getClientAddressList()) { - String urlString = StrBuilder.create("http://", each, "/adapter/thread-pool/update").toString(); - HttpUtil.post(urlString, JSONUtil.toJSONString(requestParameter), HTTP_EXECUTE_TIMEOUT); + String urlString = new StringBuilder() + .append("http://") + .append(each) + .append("/adapter/thread-pool/update") + .toString(); + restTemplate.postForObject(urlString, JSONUtil.toJSONString(requestParameter), Object.class); } return Results.success(); } diff --git a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java index 909ec0e8..f0da644b 100644 --- a/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java +++ b/hippo4j-console/src/main/java/cn/hippo4j/console/controller/ThreadPoolController.java @@ -19,6 +19,7 @@ package cn.hippo4j.console.controller; import cn.hippo4j.common.constant.Constants; import cn.hippo4j.common.model.InstanceInfo; +import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.base.Result; @@ -31,21 +32,19 @@ import cn.hippo4j.config.model.biz.threadpool.ThreadPoolRespDTO; import cn.hippo4j.config.model.biz.threadpool.ThreadPoolSaveOrUpdateReqDTO; import cn.hippo4j.config.service.ConfigCacheService; import cn.hippo4j.config.service.biz.ThreadPoolService; -import cn.hippo4j.config.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.console.model.ThreadPoolInstanceInfo; import cn.hippo4j.console.model.WebThreadPoolReqDTO; import cn.hippo4j.console.model.WebThreadPoolRespDTO; import cn.hippo4j.discovery.core.BaseInstanceRegistry; import cn.hippo4j.discovery.core.Lease; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.text.StrBuilder; -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import lombok.AllArgsConstructor; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.client.RestTemplate; +import java.util.HashMap; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -66,6 +65,8 @@ public class ThreadPoolController { private final BaseInstanceRegistry baseInstanceRegistry; + private final RestTemplate restTemplate = new RestTemplate(); + @PostMapping("/query/page") public Result> queryNameSpacePage(@RequestBody ThreadPoolQueryReqDTO reqDTO) { return Results.success(threadPoolService.queryThreadPoolPage(reqDTO)); @@ -86,7 +87,7 @@ public class ThreadPoolController { @DeleteMapping("/delete") public Result deletePool(@RequestBody ThreadPoolDelReqDTO reqDTO) { List> leases = baseInstanceRegistry.listInstance(reqDTO.getItemId()); - Lease first = CollUtil.getFirst(leases); + Lease first = CollectionUtil.getFirst(leases); if (first == null) { threadPoolService.deletePool(reqDTO); return Results.success(); @@ -111,8 +112,13 @@ public class ThreadPoolController { @GetMapping("/run/state/{tpId}") public Result runState(@PathVariable("tpId") String tpId, @RequestParam(value = "clientAddress") String clientAddress) { - String urlString = StrBuilder.create("http://", clientAddress, "/run/state/", tpId).toString(); - String data = HttpUtil.get(urlString, HTTP_EXECUTE_TIMEOUT); + String urlString = new StringBuilder() + .append("http://") + .append(clientAddress) + .append("/run/state/") + .append(tpId) + .toString(); + String data = restTemplate.getForObject(urlString, String.class, new HashMap<>()); Result result = JSONUtil.parseObject(data, Result.class); return result; } @@ -120,8 +126,13 @@ public class ThreadPoolController { @GetMapping("/run/thread/state/{tpId}") public Result runThreadState(@PathVariable("tpId") String tpId, @RequestParam(value = "clientAddress") String clientAddress) { - String urlString = StrBuilder.create("http://", clientAddress, "/run/thread/state/", tpId).toString(); - String data = HttpUtil.get(urlString, HTTP_EXECUTE_TIMEOUT); + String urlString = new StringBuilder() + .append("http://") + .append(clientAddress) + .append("/run/thread/state/") + .append(tpId) + .toString(); + String data = restTemplate.getForObject(urlString, String.class, new HashMap<>()); Result result = JSONUtil.parseObject(data, Result.class); return result; } @@ -129,7 +140,7 @@ public class ThreadPoolController { @GetMapping("/list/client/instance/{itemId}") public Result listClientInstance(@PathVariable("itemId") String itemId) { List> leases = baseInstanceRegistry.listInstance(itemId); - Lease first = CollUtil.getFirst(leases); + Lease first = CollectionUtil.getFirst(leases); if (first == null) { return Results.success(new ArrayList<>()); } @@ -156,16 +167,24 @@ public class ThreadPoolController { @GetMapping("/web/base/info") public Result getPoolBaseState(@RequestParam(value = "clientAddress") String clientAddress) { - String urlString = StrBuilder.create("http://", clientAddress, "/web/base/info").toString(); - String data = HttpUtil.get(urlString, HTTP_EXECUTE_TIMEOUT); + String urlString = new StringBuilder() + .append("http://") + .append(clientAddress) + .append("/web/base/info") + .toString(); + String data = restTemplate.getForObject(urlString, String.class, new HashMap<>()); Result result = JSONUtil.parseObject(data, Result.class); return result; } @GetMapping("/web/run/state") public Result getPoolRunState(@RequestParam(value = "clientAddress") String clientAddress) { - String urlString = StrBuilder.create("http://", clientAddress, "/web/run/state").toString(); - String data = HttpUtil.get(urlString, HTTP_EXECUTE_TIMEOUT); + String urlString = new StringBuilder() + .append("http://") + .append(clientAddress) + .append("/web/run/state") + .toString(); + String data = restTemplate.getForObject(urlString, String.class, new HashMap<>()); Result result = JSONUtil.parseObject(data, Result.class); return result; } @@ -173,8 +192,12 @@ public class ThreadPoolController { @PostMapping("/web/update/pool") public Result updateWebThreadPool(@RequestBody WebThreadPoolReqDTO requestParam) { for (String each : requestParam.getClientAddressList()) { - String urlString = StrBuilder.create("http://", each, "/web/update/pool").toString(); - HttpUtil.post(urlString, JSONUtil.toJSONString(requestParam), HTTP_EXECUTE_TIMEOUT); + String urlString = new StringBuilder() + .append("http://") + .append(each) + .append("/web/update/pool") + .toString(); + restTemplate.postForObject(urlString, JSONUtil.toJSONString(requestParam), Object.class); } return Results.success(); } @@ -183,7 +206,7 @@ public class ThreadPoolController { public Result> listInstance(@PathVariable("itemId") String itemId, @PathVariable("tpId") String tpId) { List> leases = baseInstanceRegistry.listInstance(itemId); - Lease first = CollUtil.getFirst(leases); + Lease first = CollectionUtil.getFirst(leases); if (first == null) { return Results.success(new ArrayList<>()); } @@ -192,16 +215,16 @@ public class ThreadPoolController { String groupKey = getGroupKey(tpId, itemTenantKey); Map content = ConfigCacheService.getContent(groupKey); Map activeMap = - leases.stream().map(each -> each.getHolder()).filter(each -> StringUtil.isNotBlank(each.getActive())) + leases.stream().map(Lease::getHolder).filter(each -> StringUtil.isNotBlank(each.getActive())) .collect(Collectors.toMap(InstanceInfo::getIdentify, InstanceInfo::getActive)); - Map clientBasePathMap = leases.stream().map(each -> each.getHolder()) + Map clientBasePathMap = leases.stream().map(Lease::getHolder) .filter(each -> StringUtil.isNotBlank(each.getClientBasePath())) .collect(Collectors.toMap(InstanceInfo::getIdentify, InstanceInfo::getClientBasePath)); List returnThreadPool = new ArrayList<>(); content.forEach((key, val) -> { ThreadPoolInstanceInfo threadPoolInstanceInfo = BeanUtil.convert(val.configAllInfo, ThreadPoolInstanceInfo.class); - threadPoolInstanceInfo.setClientAddress(StrUtil.subBefore(key, Constants.IDENTIFY_SLICER_SYMBOL, false)); + threadPoolInstanceInfo.setClientAddress(StringUtil.subBefore(key, Constants.IDENTIFY_SLICER_SYMBOL)); threadPoolInstanceInfo.setActive(activeMap.get(key)); threadPoolInstanceInfo.setIdentify(key); threadPoolInstanceInfo.setClientBasePath(clientBasePathMap.get(key)); diff --git a/hippo4j-console/src/main/java/cn/hippo4j/console/service/impl/DashboardServiceImpl.java b/hippo4j-console/src/main/java/cn/hippo4j/console/service/impl/DashboardServiceImpl.java index 110a5589..b67960c7 100644 --- a/hippo4j-console/src/main/java/cn/hippo4j/console/service/impl/DashboardServiceImpl.java +++ b/hippo4j-console/src/main/java/cn/hippo4j/console/service/impl/DashboardServiceImpl.java @@ -20,6 +20,7 @@ package cn.hippo4j.console.service.impl; import cn.hippo4j.common.enums.DelEnum; import cn.hippo4j.common.model.InstanceInfo; import cn.hippo4j.common.toolkit.CollectionUtil; +import cn.hippo4j.common.toolkit.DateUtil; import cn.hippo4j.common.toolkit.GroupKey; import cn.hippo4j.config.mapper.ConfigInfoMapper; import cn.hippo4j.config.mapper.HisRunDataMapper; @@ -31,19 +32,13 @@ import cn.hippo4j.console.model.*; import cn.hippo4j.console.service.DashboardService; import cn.hippo4j.discovery.core.BaseInstanceRegistry; import cn.hippo4j.discovery.core.Lease; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.date.DateTime; -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.lang.Dict; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; +import java.time.LocalDateTime; +import java.util.*; import java.util.stream.Collectors; import static cn.hippo4j.common.toolkit.ContentUtil.getGroupKey; @@ -80,9 +75,11 @@ public class DashboardServiceImpl implements DashboardService { @Override public LineChartInfo getLineChatInfo() { - Date currentDate = new Date(); - DateTime startTime = DateUtil.offsetMinute(currentDate, -10); - List threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolMaxRanking(startTime.getTime(), currentDate.getTime()); + LocalDateTime currentDate = LocalDateTime.now(); + LocalDateTime startDate = currentDate.plusMinutes(-10); + long currentTime = DateUtil.getTime(currentDate); + long startTime = DateUtil.getTime(startDate); + List threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolMaxRanking(startTime, currentTime); List oneList = new ArrayList<>(); List twoList = new ArrayList<>(); List threeList = new ArrayList<>(); @@ -115,7 +112,9 @@ public class DashboardServiceImpl implements DashboardService { Integer threadPoolCount = configInfoMapper.selectCount(threadPoolQueryWrapper); tenantThreadPoolNum += threadPoolCount; } - Dict dict = Dict.create().set("name", tenant.getTenantId()).set("value", tenantThreadPoolNum); + Map dict = new LinkedHashMap<>(); + dict.put("name", tenant.getTenantId()); + dict.put("value", tenantThreadPoolNum); tenantChartList.add(dict); } List> resultTenantChartList = tenantChartList.stream() @@ -136,7 +135,9 @@ public class DashboardServiceImpl implements DashboardService { .eq(ConfigAllInfo::getDelFlag, DelEnum.NORMAL.getIntCode()); Integer threadPoolCount = configInfoMapper.selectCount(threadPoolQueryWrapper); if (threadPoolCount != null) { - Dict dict = Dict.create().set("name", each).set("value", threadPoolCount); + Map dict = new LinkedHashMap<>(); + dict.put("name", each); + dict.put("value", threadPoolCount); pieDataList.add(dict); } } @@ -154,15 +155,17 @@ public class DashboardServiceImpl implements DashboardService { @Override public RankingChart getRankingChart() { - Date currentDate = new Date(); - DateTime tenTime = DateUtil.offsetMinute(currentDate, -10); + LocalDateTime currentDate = LocalDateTime.now(); + LocalDateTime startDate = currentDate.plusMinutes(-10); + long currentTime = DateUtil.getTime(currentDate); + long startTime = DateUtil.getTime(startDate); List resultList = new ArrayList<>(); - List threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolTaskSumRanking(tenTime.getTime(), currentDate.getTime()); + List threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolTaskSumRanking(startTime, currentTime); threadPoolTaskRankings.forEach(each -> { RankingChart.RankingChartInfo rankingChartInfo = new RankingChart.RankingChartInfo(); rankingChartInfo.setMaxCompletedTaskCount(each.getMaxCompletedTaskCount()); List> leases = baseInstanceRegistry.listInstance(each.getItemId()); - Lease first = CollUtil.getFirst(leases); + Lease first = CollectionUtil.getFirst(leases); if (first == null) { rankingChartInfo.setInst(0); } else { diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/ThreadPoolNotifyAlarmHandler.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/ThreadPoolNotifyAlarmHandler.java index b5588613..53489a23 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/ThreadPoolNotifyAlarmHandler.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/ThreadPoolNotifyAlarmHandler.java @@ -29,7 +29,6 @@ import cn.hippo4j.message.enums.NotifyTypeEnum; import cn.hippo4j.message.service.ThreadPoolNotifyAlarm; import cn.hippo4j.message.request.AlarmNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; -import cn.hutool.core.util.StrUtil; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -198,7 +197,7 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner */ public void sendPoolConfigChange(ChangeParameterNotifyRequest request) { request.setActive(active.toUpperCase()); - String appName = StrUtil.isBlank(itemId) ? applicationName : itemId; + String appName = StringUtil.isBlank(itemId) ? applicationName : itemId; request.setAppName(appName); request.setIdentify(IdentifyUtil.getIdentify()); hippo4jSendMessageService.sendChangeMessage(request); @@ -218,8 +217,8 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner long rejectCount = threadPoolExecutor instanceof DynamicThreadPoolExecutor ? ((DynamicThreadPoolExecutor) threadPoolExecutor).getRejectCountNum() : -1L; - AlarmNotifyRequest alarmNotifyRequest = AlarmNotifyRequest.builder() - .appName(StrUtil.isBlank(itemId) ? applicationName : itemId) + return AlarmNotifyRequest.builder() + .appName(StringUtil.isBlank(itemId) ? applicationName : itemId) .active(active.toUpperCase()) .identify(IdentifyUtil.getIdentify()) .corePoolSize(threadPoolExecutor.getCorePoolSize()) @@ -235,6 +234,5 @@ public class ThreadPoolNotifyAlarmHandler implements Runnable, CommandLineRunner .rejectedExecutionHandlerName(rejectedExecutionHandler.getClass().getSimpleName()) .rejectCountNum(rejectCount) .build(); - return alarmNotifyRequest; } } diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/AbstractThreadPoolRuntime.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/AbstractThreadPoolRuntime.java index d584b1d6..6287b24a 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/AbstractThreadPoolRuntime.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/AbstractThreadPoolRuntime.java @@ -22,9 +22,9 @@ import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.common.toolkit.CalculateUtil; -import cn.hutool.core.date.DateUtil; -import java.util.Date; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @@ -105,7 +105,7 @@ public abstract class AbstractThreadPoolRuntime { long rejectCount = pool instanceof DynamicThreadPoolExecutor ? ((DynamicThreadPoolExecutor) pool).getRejectCountNum() : -1L; stateInfo.setRejectCount(rejectCount); - stateInfo.setClientLastRefreshTime(DateUtil.formatDateTime(new Date())); + stateInfo.setClientLastRefreshTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); stateInfo.setTimestamp(System.currentTimeMillis()); return supplement(stateInfo); } diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandler.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandler.java index 94265d22..62b9b1ab 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandler.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolRunStateHandler.java @@ -19,19 +19,20 @@ package cn.hippo4j.core.executor.state; import cn.hippo4j.common.model.ManyThreadPoolRunStateInfo; import cn.hippo4j.common.model.ThreadPoolRunStateInfo; +import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.common.toolkit.ByteConvertUtil; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.support.AbstractDynamicExecutorSupport; import cn.hippo4j.core.toolkit.inet.InetUtils; -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.system.RuntimeInfo; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.env.ConfigurableEnvironment; +import java.lang.management.ManagementFactory; +import java.lang.management.MemoryMXBean; +import java.lang.management.MemoryUsage; import java.util.concurrent.ThreadPoolExecutor; import static cn.hippo4j.core.toolkit.IdentifyUtil.CLIENT_IDENTIFICATION_VALUE; @@ -49,18 +50,22 @@ public class ThreadPoolRunStateHandler extends AbstractThreadPoolRuntime { @Override public ThreadPoolRunStateInfo supplement(ThreadPoolRunStateInfo poolRunStateInfo) { - RuntimeInfo runtimeInfo = new RuntimeInfo(); - String memoryProportion = StrUtil.builder( - "已分配: ", - ByteConvertUtil.getPrintSize(runtimeInfo.getTotalMemory()), - " / 最大可用: ", - ByteConvertUtil.getPrintSize(runtimeInfo.getMaxMemory())).toString(); + MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); + MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage(); + long used = heapMemoryUsage.getUsed(); + long max = heapMemoryUsage.getMax(); + String memoryProportion = new StringBuilder() + .append("已分配: ") + .append(ByteConvertUtil.getPrintSize(used)) + .append(" / 最大可用: ") + .append(ByteConvertUtil.getPrintSize(max)) + .toString(); poolRunStateInfo.setCurrentLoad(poolRunStateInfo.getCurrentLoad() + "%"); poolRunStateInfo.setPeakLoad(poolRunStateInfo.getPeakLoad() + "%"); String ipAddress = hippo4JInetUtils.findFirstNonLoopBackHostInfo().getIpAddress(); poolRunStateInfo.setHost(ipAddress); poolRunStateInfo.setMemoryProportion(memoryProportion); - poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(runtimeInfo.getFreeMemory())); + poolRunStateInfo.setFreeMemory(ByteConvertUtil.getPrintSize(Math.subtractExact(max, used))); String threadPoolId = poolRunStateInfo.getTpId(); DynamicThreadPoolWrapper executorService = GlobalThreadPoolManage.getExecutorService(threadPoolId); ThreadPoolExecutor pool = executorService.getExecutor(); @@ -71,7 +76,7 @@ public class ThreadPoolRunStateHandler extends AbstractThreadPoolRuntime { rejectedName = pool.getRejectedExecutionHandler().getClass().getSimpleName(); } poolRunStateInfo.setRejectedName(rejectedName); - ManyThreadPoolRunStateInfo manyThreadPoolRunStateInfo = BeanUtil.toBean(poolRunStateInfo, ManyThreadPoolRunStateInfo.class); + ManyThreadPoolRunStateInfo manyThreadPoolRunStateInfo = BeanUtil.convert(poolRunStateInfo, ManyThreadPoolRunStateInfo.class); manyThreadPoolRunStateInfo.setIdentify(CLIENT_IDENTIFICATION_VALUE); String active = environment.getProperty("spring.profiles.active", "UNKNOWN"); manyThreadPoolRunStateInfo.setActive(active.toUpperCase()); diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolStatusHandler.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolStatusHandler.java index 9f25413a..fc9c8f2e 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolStatusHandler.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/state/ThreadPoolStatusHandler.java @@ -17,7 +17,7 @@ package cn.hippo4j.core.executor.state; -import cn.hutool.core.util.ReflectUtil; +import cn.hippo4j.common.toolkit.ReflectUtil; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.Method; @@ -49,7 +49,7 @@ public class ThreadPoolStatusHandler { if (EXCEPTION_FLAG.get()) { try { Method runStateLessThan = ReflectUtil.getMethodByName(ThreadPoolExecutor.class, "runStateLessThan"); - cn.hippo4j.common.toolkit.ReflectUtil.setAccessible(runStateLessThan); + ReflectUtil.setAccessible(runStateLessThan); AtomicInteger ctl = (AtomicInteger) ReflectUtil.getFieldValue(executor, "ctl"); int shutdown = (int) ReflectUtil.getFieldValue(executor, "SHUTDOWN"); boolean runStateLessThanBool = ReflectUtil.invoke(executor, runStateLessThan, ctl.get(), shutdown); diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java index a1d1975b..4d002f8c 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/executor/support/AbstractBuildThreadPoolTemplate.java @@ -17,6 +17,7 @@ package cn.hippo4j.core.executor.support; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.common.toolkit.Assert; import cn.hippo4j.core.executor.DynamicThreadPoolExecutor; import lombok.Data; diff --git a/hippo4j-core/src/main/java/cn/hippo4j/core/toolkit/IdentifyUtil.java b/hippo4j-core/src/main/java/cn/hippo4j/core/toolkit/IdentifyUtil.java index c4e18963..0975b773 100644 --- a/hippo4j-core/src/main/java/cn/hippo4j/core/toolkit/IdentifyUtil.java +++ b/hippo4j-core/src/main/java/cn/hippo4j/core/toolkit/IdentifyUtil.java @@ -18,15 +18,12 @@ package cn.hippo4j.core.toolkit; import cn.hippo4j.common.config.ApplicationContextHolder; -import cn.hippo4j.common.toolkit.CollectionUtil; -import cn.hippo4j.common.toolkit.Joiner; -import cn.hippo4j.common.toolkit.ThreadUtil; +import cn.hippo4j.common.toolkit.*; import cn.hippo4j.core.toolkit.inet.InetUtils; -import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.StrUtil; import org.springframework.core.env.ConfigurableEnvironment; import java.util.ArrayList; +import java.util.UUID; import static cn.hippo4j.common.constant.Constants.GROUP_KEY_DELIMITER; import static cn.hippo4j.common.constant.Constants.IDENTIFY_SLICER_SYMBOL; @@ -48,16 +45,18 @@ public class IdentifyUtil { * @return */ public static synchronized String generate(ConfigurableEnvironment environment, InetUtils hippo4JInetUtils) { - if (StrUtil.isNotBlank(IDENTIFY)) { + if (StringUtil.isNotBlank(IDENTIFY)) { return IDENTIFY; } String ip = hippo4JInetUtils.findFirstNonLoopBackHostInfo().getIpAddress(); String port = environment.getProperty("server.port", "8080"); - String identification = StrUtil.builder(ip, - ":", - port, - IDENTIFY_SLICER_SYMBOL, - CLIENT_IDENTIFICATION_VALUE).toString(); + String identification = new StringBuilder() + .append(ip) + .append(":") + .append(port) + .append(IDENTIFY_SLICER_SYMBOL) + .append(CLIENT_IDENTIFICATION_VALUE) + .toString(); IDENTIFY = identification; return identification; } @@ -68,7 +67,7 @@ public class IdentifyUtil { * @return */ public static String getIdentify() { - while (StrUtil.isBlank(IDENTIFY)) { + while (StringUtil.isBlank(IDENTIFY)) { ConfigurableEnvironment environment = ApplicationContextHolder.getBean(ConfigurableEnvironment.class); InetUtils inetUtils = ApplicationContextHolder.getBean(InetUtils.class); if (environment != null && inetUtils != null) { diff --git a/hippo4j-discovery/src/main/java/cn/hippo4j/discovery/core/BaseInstanceRegistry.java b/hippo4j-discovery/src/main/java/cn/hippo4j/discovery/core/BaseInstanceRegistry.java index 66dcc6bd..ad6ed740 100644 --- a/hippo4j-discovery/src/main/java/cn/hippo4j/discovery/core/BaseInstanceRegistry.java +++ b/hippo4j-discovery/src/main/java/cn/hippo4j/discovery/core/BaseInstanceRegistry.java @@ -17,10 +17,10 @@ package cn.hippo4j.discovery.core; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.common.design.observer.AbstractSubjectCenter; import cn.hippo4j.common.model.InstanceInfo; import cn.hippo4j.common.model.InstanceInfo.InstanceStatus; -import cn.hutool.core.thread.ThreadFactoryBuilder; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; @@ -189,8 +189,8 @@ public class BaseInstanceRegistry implements InstanceRegistry { new ScheduledThreadPoolExecutor( SCHEDULED_THREAD_CORE_NUM, new ThreadFactoryBuilder() - .setNamePrefix("registry-eviction") - .setDaemon(true) + .prefix("registry-eviction") + .daemon(true) .build()); private final AtomicReference evictionTaskRef = new AtomicReference(); diff --git a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/AlarmSendMessageTest.java b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/AlarmSendMessageTest.java index 5fee289d..a7ac1ec8 100644 --- a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/AlarmSendMessageTest.java +++ b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/AlarmSendMessageTest.java @@ -18,7 +18,6 @@ package cn.hippo4j.example.core.inittest; import cn.hippo4j.example.core.constant.GlobalTestConstant; -import cn.hutool.core.thread.ThreadUtil; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; import lombok.extern.slf4j.Slf4j; @@ -47,7 +46,13 @@ public class AlarmSendMessageTest { DynamicThreadPoolWrapper poolWrapper = GlobalThreadPoolManage.getExecutorService(GlobalTestConstant.MESSAGE_PRODUCE); ThreadPoolExecutor poolExecutor = poolWrapper.getExecutor(); try { - poolExecutor.execute(() -> ThreadUtil.sleep(10240124)); + poolExecutor.execute(() -> { + try { + Thread.sleep(10240124); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + }); } catch (Exception ex) { log.error("Throw reject policy.", ex.getMessage()); } diff --git a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/RunStateHandlerTest.java b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/RunStateHandlerTest.java index c6cdb011..049d6d51 100644 --- a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/RunStateHandlerTest.java +++ b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/RunStateHandlerTest.java @@ -17,7 +17,6 @@ package cn.hippo4j.example.core.inittest; -import cn.hutool.core.thread.ThreadUtil; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; import org.springframework.stereotype.Component; @@ -83,7 +82,11 @@ public class RunStateHandlerTest { * When the execution of the thread pool task times out, the Trace flag is put into the MDC, and it is printed out when an alarm occurs. */ MDC.put(EXECUTE_TIMEOUT_TRACE, "39948722194639841.251.16612352194691531"); - ThreadUtil.sleep(5000); + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } for (int i = 0; i < Integer.MAX_VALUE; i++) { try { executor.execute(() -> { @@ -102,7 +105,11 @@ public class RunStateHandlerTest { }); } catch (Exception ignored) { } - ThreadUtil.sleep(500); + try { + Thread.sleep(500); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } }); } diff --git a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/TaskDecoratorTest.java b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/TaskDecoratorTest.java index 4e08a080..0d69bdcb 100644 --- a/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/TaskDecoratorTest.java +++ b/hippo4j-example/hippo4j-example-core/src/main/java/cn/hippo4j/example/core/inittest/TaskDecoratorTest.java @@ -20,7 +20,6 @@ package cn.hippo4j.example.core.inittest; import cn.hippo4j.example.core.constant.GlobalTestConstant; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.DynamicThreadPoolWrapper; -import cn.hutool.core.thread.ThreadUtil; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; import org.springframework.core.task.TaskDecorator; @@ -60,12 +59,14 @@ public class TaskDecoratorTest { public void taskDecoratorTest() { taskDecoratorTestExecutor.execute(() -> { MDC.put(PLACEHOLDER, "View the official website: https://www.hippo4j.cn"); - ThreadUtil.sleep(5000); - DynamicThreadPoolWrapper poolWrapper = GlobalThreadPoolManage.getExecutorService(GlobalTestConstant.MESSAGE_PRODUCE); - ThreadPoolExecutor threadPoolExecutor = poolWrapper.getExecutor(); - threadPoolExecutor.execute(() -> { - log.info("Pass context via taskDecorator MDC: {}", MDC.get(PLACEHOLDER)); - }); + try { + Thread.sleep(5000); + DynamicThreadPoolWrapper poolWrapper = GlobalThreadPoolManage.getExecutorService(GlobalTestConstant.MESSAGE_PRODUCE); + ThreadPoolExecutor threadPoolExecutor = poolWrapper.getExecutor(); + threadPoolExecutor.execute(() -> log.info("Pass context via taskDecorator MDC: {}", MDC.get(PLACEHOLDER))); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } }); } diff --git a/hippo4j-example/hippo4j-spring-boot-starter-adapter-kafka-example/src/main/java/cn/hippo4j/springboot/starter/adapter/kafka/example/produce/KafkaMessageProduce.java b/hippo4j-example/hippo4j-spring-boot-starter-adapter-kafka-example/src/main/java/cn/hippo4j/springboot/starter/adapter/kafka/example/produce/KafkaMessageProduce.java index 04d01c71..9cfbddbd 100644 --- a/hippo4j-example/hippo4j-spring-boot-starter-adapter-kafka-example/src/main/java/cn/hippo4j/springboot/starter/adapter/kafka/example/produce/KafkaMessageProduce.java +++ b/hippo4j-example/hippo4j-spring-boot-starter-adapter-kafka-example/src/main/java/cn/hippo4j/springboot/starter/adapter/kafka/example/produce/KafkaMessageProduce.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.adapter.kafka.example.produce; +import cn.hippo4j.common.toolkit.IdUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.example.core.dto.SendMessageDTO; import lombok.AllArgsConstructor; @@ -26,8 +27,6 @@ import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.UUID; - /** * Kafka message produce. */ @@ -44,7 +43,7 @@ public class KafkaMessageProduce { @GetMapping("/message/send") public String sendMessage(Integer count) { for (int i = 0; i < count; i++) { - String keys = UUID.randomUUID().toString(); + String keys = IdUtil.randomUUID(); SendMessageDTO payload = SendMessageDTO.builder() .receiver("156011xxx91") .uid(keys) diff --git a/hippo4j-example/hippo4j-spring-boot-starter-adapter-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/rabbitmq/example/producer/MessageProduce.java b/hippo4j-example/hippo4j-spring-boot-starter-adapter-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/rabbitmq/example/producer/MessageProduce.java index c0a66817..5113bad8 100644 --- a/hippo4j-example/hippo4j-spring-boot-starter-adapter-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/rabbitmq/example/producer/MessageProduce.java +++ b/hippo4j-example/hippo4j-spring-boot-starter-adapter-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/rabbitmq/example/producer/MessageProduce.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.adapter.rabbitmq.example.producer; +import cn.hippo4j.common.toolkit.IdUtil; import cn.hippo4j.example.core.dto.SendMessageDTO; import cn.hippo4j.springboot.starter.adapter.rabbitmq.example.constants.SimpleMQConstant; import lombok.AllArgsConstructor; @@ -26,8 +27,6 @@ import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.UUID; - /** * Message produce. */ @@ -42,7 +41,7 @@ public class MessageProduce { @GetMapping("/message/send") public String sendMessage(Integer count) { for (int i = 0; i < count; i++) { - String keys = UUID.randomUUID().toString(); + String keys = IdUtil.randomUUID(); SendMessageDTO payload = SendMessageDTO.builder() .receiver("156011xxx91") .uid(keys) diff --git a/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rabbitmq/example/MessageProduce.java b/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rabbitmq/example/MessageProduce.java index bf24a379..eeb2953a 100644 --- a/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rabbitmq/example/MessageProduce.java +++ b/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rabbitmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rabbitmq/example/MessageProduce.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.adapter.springcloud.stream.rabbitmq.example; +import cn.hippo4j.common.toolkit.IdUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.example.core.dto.SendMessageDTO; import lombok.AllArgsConstructor; @@ -26,8 +27,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import java.util.UUID; - /** * Message produce. */ @@ -50,7 +49,7 @@ public class MessageProduce { } private void sendMessage0() { - String keys = UUID.randomUUID().toString(); + String keys = IdUtil.randomUUID(); SendMessageDTO payload = SendMessageDTO.builder() .receiver("156011xxx91") .uid(keys) diff --git a/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rocketmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rocketmq/example/MessageProduce.java b/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rocketmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rocketmq/example/MessageProduce.java index 0255a33d..b7f9d590 100644 --- a/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rocketmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rocketmq/example/MessageProduce.java +++ b/hippo4j-example/hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rocketmq-example/src/main/java/cn/hippo4j/springboot/starter/adapter/springcloud/stream/rocketmq/example/MessageProduce.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.adapter.springcloud.stream.rocketmq.example; +import cn.hippo4j.common.toolkit.IdUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.example.core.dto.SendMessageDTO; import lombok.AllArgsConstructor; @@ -28,8 +29,6 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import java.util.UUID; - /** * Message produce. */ @@ -55,7 +54,7 @@ public class MessageProduce { } private void sendMessage(String tags) { - String keys = UUID.randomUUID().toString(); + String keys = IdUtil.randomUUID(); SendMessageDTO payload = SendMessageDTO.builder() .receiver("156011xxx91") .uid(keys) diff --git a/hippo4j-message/pom.xml b/hippo4j-message/pom.xml index 60de5b82..fe964d3a 100644 --- a/hippo4j-message/pom.xml +++ b/hippo4j-message/pom.xml @@ -39,10 +39,6 @@ commons-codec - - cn.hutool - hutool-all - diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java index 02c2a470..25600ea6 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/LarkSendMessageHandler.java @@ -25,14 +25,15 @@ import cn.hippo4j.message.service.SendMessageHandler; import cn.hippo4j.message.request.AlarmNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; import cn.hippo4j.common.toolkit.StringUtil; -import cn.hutool.core.date.DateUtil; import cn.hippo4j.common.toolkit.FileUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.http.HttpRequest; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Objects; import java.util.stream.Collectors; @@ -66,14 +67,14 @@ public class LarkSendMessageHandler implements SendMessageHandler FileUtil.readUtf8String(larkAlarmTimoutTraceReplaceJsonKey)); if (StringUtil.isNotBlank(executeTimeoutTrace)) { String larkAlarmTimoutTraceReplaceTxt = String.format(larkAlarmTimoutTraceReplaceJson, executeTimeoutTrace); - larkAlarmTimoutReplaceTxt = StrUtil.replace(larkAlarmTimoutReplaceJson, larkAlarmTimoutTraceReplaceJson, larkAlarmTimoutTraceReplaceTxt); + larkAlarmTimoutReplaceTxt = StringUtil.replace(larkAlarmTimoutReplaceJson, larkAlarmTimoutTraceReplaceJson, larkAlarmTimoutTraceReplaceTxt); } else { - larkAlarmTimoutReplaceTxt = StrUtil.replace(larkAlarmTimoutReplaceJson, larkAlarmTimoutTraceReplaceJson, ""); + larkAlarmTimoutReplaceTxt = StringUtil.replace(larkAlarmTimoutReplaceJson, larkAlarmTimoutTraceReplaceJson, ""); } larkAlarmTimoutReplaceTxt = String.format(larkAlarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut()); - larkAlarmTxt = StrUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, larkAlarmTimoutReplaceTxt); + larkAlarmTxt = StringUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, larkAlarmTimoutReplaceTxt); } else { - larkAlarmTxt = StrUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, ""); + larkAlarmTxt = StringUtil.replace(larkAlarmTxt, larkAlarmTimoutReplaceJson, ""); } String text = String.format(larkAlarmTxt, @@ -114,7 +115,7 @@ public class LarkSendMessageHandler implements SendMessageHandler StrUtil.startWith(receive, LARK_OPENID_PREFIX) ? String.format(LARK_AT_FORMAT_OPENID, receive) : String.format(LARK_AT_FORMAT_USERNAME, receive)) + .map(receive -> StringUtil.startWith(receive, LARK_OPENID_PREFIX) ? String.format(LARK_AT_FORMAT_OPENID, receive) : String.format(LARK_AT_FORMAT_USERNAME, receive)) .collect(Collectors.joining(" ")); } private void execute(String secretKey, String text) { String serverUrl = LARK_BOT_URL + secretKey; try { - HttpRequest.post(serverUrl).body(text).execute(); + RestTemplate template = new RestTemplate(); + template.postForObject(serverUrl, text, Object.class); } catch (Exception ex) { log.error("Lark failed to send message", ex); } diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java index 834488d6..38bc9111 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/WeChatSendMessageHandler.java @@ -18,16 +18,16 @@ package cn.hippo4j.message.platform; import cn.hippo4j.common.toolkit.FileUtil; -import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.toolkit.Singleton; import cn.hippo4j.message.enums.NotifyPlatformEnum; import cn.hippo4j.message.platform.base.AbstractRobotSendMessageHandler; import cn.hippo4j.message.platform.base.RobotMessageActualContent; import cn.hippo4j.message.platform.base.RobotMessageExecuteDTO; -import cn.hutool.http.HttpRequest; import lombok.Data; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; import static cn.hippo4j.message.platform.constant.WeChatAlarmConstants.*; @@ -46,7 +46,7 @@ public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler { protected RobotMessageActualContent buildMessageActualContent() { String weChatAlarmTxtKey = "message/robot/dynamic-thread-pool/wechat-alarm.txt"; String weChatConfigTxtKey = "message/robot/dynamic-thread-pool/wechat-config.txt"; - RobotMessageActualContent robotMessageActualContent = RobotMessageActualContent.builder() + return RobotMessageActualContent.builder() .receiveSeparator("><@") .changeSeparator(" ➲ ") .replaceTxt(WE_CHAT_ALARM_TIMOUT_REPLACE_TXT) @@ -54,7 +54,6 @@ public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler { .alarmMessageContent(Singleton.get(weChatAlarmTxtKey, () -> FileUtil.readUtf8String(weChatAlarmTxtKey))) .configMessageContent(Singleton.get(weChatConfigTxtKey, () -> FileUtil.readUtf8String(weChatConfigTxtKey))) .build(); - return robotMessageActualContent; } @Override @@ -66,7 +65,8 @@ public class WeChatSendMessageHandler extends AbstractRobotSendMessageHandler { Markdown markdown = new Markdown(); markdown.setContent(robotMessageExecuteDTO.getText()); weChatReq.setMarkdown(markdown); - HttpRequest.post(serverUrl).body(JSONUtil.toJSONString(weChatReq)).execute(); + RestTemplate template = new RestTemplate(); + template.postForObject(serverUrl, weChatReq, Object.class); } catch (Exception ex) { log.error("WeChat failed to send message", ex); } diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/base/AbstractRobotSendMessageHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/base/AbstractRobotSendMessageHandler.java index c2d2acd2..34f7fd71 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/platform/base/AbstractRobotSendMessageHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/platform/base/AbstractRobotSendMessageHandler.java @@ -24,9 +24,9 @@ import cn.hippo4j.message.enums.NotifyTypeEnum; import cn.hippo4j.message.request.AlarmNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; import cn.hippo4j.message.service.SendMessageHandler; -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.util.StrUtil; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; import java.util.Objects; /** @@ -64,15 +64,15 @@ public abstract class AbstractRobotSendMessageHandler implements SendMessageHand String executeTimeoutTrace = alarmNotifyRequest.getExecuteTimeoutTrace(); if (StringUtil.isNotBlank(executeTimeoutTrace)) { String alarmTimoutTraceReplaceTxt = String.format(traceReplaceTxt, executeTimeoutTrace); - alarmTimoutReplaceTxt = StrUtil.replace(replaceTxt, traceReplaceTxt, alarmTimoutTraceReplaceTxt); + alarmTimoutReplaceTxt = StringUtil.replace(replaceTxt, traceReplaceTxt, alarmTimoutTraceReplaceTxt); } else { - alarmTimoutReplaceTxt = StrUtil.replace(replaceTxt, traceReplaceTxt, ""); + alarmTimoutReplaceTxt = StringUtil.replace(replaceTxt, traceReplaceTxt, ""); } replaceTxt = String.format(alarmTimoutReplaceTxt, alarmNotifyRequest.getExecuteTime(), alarmNotifyRequest.getExecuteTimeOut()); } else { replaceTxt = ""; } - alarmContentTxt = StrUtil.replace(alarmContentTxt, "${timout-content}", replaceTxt); + alarmContentTxt = StringUtil.replace(alarmContentTxt, "${timout-content}", replaceTxt); String text = String.format( alarmContentTxt, // 环境 @@ -114,7 +114,7 @@ public abstract class AbstractRobotSendMessageHandler implements SendMessageHand // 报警频率 notifyConfig.getInterval(), // 当前时间 - DateUtil.now()); + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); execute(RobotMessageExecuteDTO.builder().text(text).notifyConfig(notifyConfig).build()); } @@ -158,7 +158,7 @@ public abstract class AbstractRobotSendMessageHandler implements SendMessageHand // 告警手机号 Joiner.on(robotMessageActualContent.getReceiveSeparator()).join(notifyConfig.getReceives().split(",")), // 当前时间 - DateUtil.now()); + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); execute(RobotMessageExecuteDTO.builder().text(text).notifyConfig(notifyConfig).build()); } } diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/service/AlarmControlHandler.java b/hippo4j-message/src/main/java/cn/hippo4j/message/service/AlarmControlHandler.java index c0f0c500..c85b51ec 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/service/AlarmControlHandler.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/service/AlarmControlHandler.java @@ -18,9 +18,9 @@ package cn.hippo4j.message.service; import cn.hippo4j.common.constant.Constants; +import cn.hippo4j.common.toolkit.IdUtil; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.message.dto.AlarmControlDTO; -import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.StrUtil; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; @@ -52,12 +52,12 @@ public class AlarmControlHandler { return false; } String pkId = cache.getIfPresent(alarmControl.getTypeEnum().name()); - if (StrUtil.isBlank(pkId)) { + if (StringUtil.isBlank(pkId)) { ReentrantLock lock = threadPoolLock.get(threadPoolKey); lock.lock(); try { pkId = cache.getIfPresent(alarmControl.getTypeEnum().name()); - if (StrUtil.isBlank(pkId)) { + if (StringUtil.isBlank(pkId)) { // Val meaningless. cache.put(alarmControl.getTypeEnum().name(), IdUtil.simpleUUID()); return true; @@ -77,7 +77,7 @@ public class AlarmControlHandler { * @param interval */ public void initCacheAndLock(String threadPoolId, String platform, Integer interval) { - String threadPoolKey = StrUtil.builder(threadPoolId, Constants.GROUP_KEY_DELIMITER, platform).toString(); + String threadPoolKey = threadPoolId + Constants.GROUP_KEY_DELIMITER + platform; Cache cache = Caffeine.newBuilder() .expireAfterWrite(interval, TimeUnit.MINUTES) .build(); diff --git a/hippo4j-message/src/main/java/cn/hippo4j/message/service/Hippo4jBaseSendMessageService.java b/hippo4j-message/src/main/java/cn/hippo4j/message/service/Hippo4jBaseSendMessageService.java index c6c98242..ca7af719 100644 --- a/hippo4j-message/src/main/java/cn/hippo4j/message/service/Hippo4jBaseSendMessageService.java +++ b/hippo4j-message/src/main/java/cn/hippo4j/message/service/Hippo4jBaseSendMessageService.java @@ -17,15 +17,14 @@ package cn.hippo4j.message.service; -import cn.hippo4j.common.config.ApplicationContextHolder; +import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.message.api.NotifyConfigBuilder; +import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.message.dto.AlarmControlDTO; import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.enums.NotifyTypeEnum; import cn.hippo4j.message.request.AlarmNotifyRequest; import cn.hippo4j.message.request.ChangeParameterNotifyRequest; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.StrUtil; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -54,9 +53,13 @@ public class Hippo4jBaseSendMessageService implements Hippo4jSendMessageService, @Override public void sendAlarmMessage(NotifyTypeEnum typeEnum, AlarmNotifyRequest alarmNotifyRequest) { String threadPoolId = alarmNotifyRequest.getThreadPoolId(); - String buildKey = StrUtil.builder(threadPoolId, "+", "ALARM").toString(); + String buildKey = new StringBuilder() + .append(threadPoolId) + .append("+") + .append("ALARM") + .toString(); List notifyList = notifyConfigs.get(buildKey); - if (CollUtil.isEmpty(notifyList)) { + if (CollectionUtil.isEmpty(notifyList)) { return; } notifyList.forEach(each -> { @@ -79,9 +82,13 @@ public class Hippo4jBaseSendMessageService implements Hippo4jSendMessageService, @Override public void sendChangeMessage(ChangeParameterNotifyRequest changeParameterNotifyRequest) { String threadPoolId = changeParameterNotifyRequest.getThreadPoolId(); - String buildKey = StrUtil.builder(threadPoolId, "+", "CONFIG").toString(); + String buildKey = new StringBuilder() + .append(threadPoolId) + .append("+") + .append("CONFIG") + .toString(); List notifyList = notifyConfigs.get(buildKey); - if (CollUtil.isEmpty(notifyList)) { + if (CollectionUtil.isEmpty(notifyList)) { log.warn("Please configure alarm notification on the server. key: [{}]", threadPoolId); return; } diff --git a/hippo4j-monitor/hippo4j-monitor-elasticsearch/src/main/java/cn/hippo4j/monitor/es/EsMonitorHandler.java b/hippo4j-monitor/hippo4j-monitor-elasticsearch/src/main/java/cn/hippo4j/monitor/es/EsMonitorHandler.java index b75a4b76..505712c4 100644 --- a/hippo4j-monitor/hippo4j-monitor-elasticsearch/src/main/java/cn/hippo4j/monitor/es/EsMonitorHandler.java +++ b/hippo4j-monitor/hippo4j-monitor-elasticsearch/src/main/java/cn/hippo4j/monitor/es/EsMonitorHandler.java @@ -19,11 +19,11 @@ package cn.hippo4j.monitor.es; import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.common.model.ThreadPoolRunStateInfo; +import cn.hippo4j.common.toolkit.BeanUtil; +import cn.hippo4j.common.toolkit.FileUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.core.executor.state.ThreadPoolRunStateHandler; import cn.hippo4j.monitor.es.model.EsThreadPoolRunStateInfo; -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.io.FileUtil; import cn.hippo4j.monitor.base.AbstractDynamicThreadPoolMonitor; import cn.hippo4j.monitor.base.MonitorTypeEnum; import lombok.extern.slf4j.Slf4j; @@ -40,7 +40,6 @@ import org.elasticsearch.common.xcontent.XContentType; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; -import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; @@ -61,13 +60,12 @@ public class EsMonitorHandler extends AbstractDynamicThreadPoolMonitor { @Override protected void execute(ThreadPoolRunStateInfo poolRunStateInfo) { - EsThreadPoolRunStateInfo esThreadPoolRunStateInfo = new EsThreadPoolRunStateInfo(); - BeanUtil.copyProperties(poolRunStateInfo, esThreadPoolRunStateInfo); + EsThreadPoolRunStateInfo esThreadPoolRunStateInfo = BeanUtil.convert(poolRunStateInfo, EsThreadPoolRunStateInfo.class); Environment environment = ApplicationContextHolder.getInstance().getEnvironment(); String indexName = environment.getProperty("es.thread-pool-state.index.name", "thread-pool-state"); String applicationName = environment.getProperty("spring.application.name", "application"); if (!this.isExists(indexName)) { - List rawMapping = FileUtil.readLines(new File(Thread.currentThread().getContextClassLoader().getResource("mapping.json").getPath()), StandardCharsets.UTF_8); + List rawMapping = FileUtil.readLines(Thread.currentThread().getContextClassLoader().getResource("mapping.json").getPath(), StandardCharsets.UTF_8); String mapping = String.join(" ", rawMapping); // if index doesn't exsit, this function may try to create one, but recommend to create index manually. this.createIndex(indexName, "_doc", mapping, null, null, null); diff --git a/hippo4j-monitor/hippo4j-monitor-micrometer/src/main/java/cn/hippo4j/monitor/micrometer/MicrometerMonitorHandler.java b/hippo4j-monitor/hippo4j-monitor-micrometer/src/main/java/cn/hippo4j/monitor/micrometer/MicrometerMonitorHandler.java index 7c1b930c..844685b7 100644 --- a/hippo4j-monitor/hippo4j-monitor-micrometer/src/main/java/cn/hippo4j/monitor/micrometer/MicrometerMonitorHandler.java +++ b/hippo4j-monitor/hippo4j-monitor-micrometer/src/main/java/cn/hippo4j/monitor/micrometer/MicrometerMonitorHandler.java @@ -19,11 +19,11 @@ package cn.hippo4j.monitor.micrometer; import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.common.model.ThreadPoolRunStateInfo; +import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.core.executor.state.ThreadPoolRunStateHandler; import cn.hippo4j.monitor.base.AbstractDynamicThreadPoolMonitor; import cn.hippo4j.monitor.base.MonitorTypeEnum; -import cn.hutool.core.bean.BeanUtil; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tag; import org.springframework.core.env.Environment; @@ -54,7 +54,7 @@ public class MicrometerMonitorHandler extends AbstractDynamicThreadPoolMonitor { if (stateInfo == null) { RUN_STATE_CACHE.put(poolRunStateInfo.getTpId(), poolRunStateInfo); } else { - BeanUtil.copyProperties(poolRunStateInfo, stateInfo); + BeanUtil.convert(poolRunStateInfo, stateInfo); } Environment environment = ApplicationContextHolder.getInstance().getEnvironment(); String applicationName = environment.getProperty("spring.application.name", "application"); diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/monitor/DynamicThreadPoolMonitorExecutor.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/monitor/DynamicThreadPoolMonitorExecutor.java index 46fa5579..28a5a510 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/monitor/DynamicThreadPoolMonitorExecutor.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/monitor/DynamicThreadPoolMonitorExecutor.java @@ -22,7 +22,7 @@ import cn.hippo4j.common.spi.DynamicThreadPoolServiceLoader; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; -import cn.hippo4j.core.executor.support.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.monitor.base.DynamicThreadPoolMonitor; import cn.hippo4j.monitor.base.ThreadPoolMonitor; import lombok.RequiredArgsConstructor; diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/CoreNotifyConfigBuilder.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/CoreNotifyConfigBuilder.java index d66e994d..9dba54a8 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/CoreNotifyConfigBuilder.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/notify/CoreNotifyConfigBuilder.java @@ -25,7 +25,6 @@ import cn.hippo4j.config.springboot.starter.config.NotifyPlatformProperties; import cn.hippo4j.message.api.NotifyConfigBuilder; import cn.hippo4j.message.dto.NotifyConfigDTO; import cn.hippo4j.message.service.AlarmControlHandler; -import cn.hutool.core.util.StrUtil; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -110,7 +109,7 @@ public class CoreNotifyConfigBuilder implements NotifyConfigBuilder { public void initCacheAndLock(Map> buildSingleNotifyConfig) { buildSingleNotifyConfig.forEach( (key, val) -> val.stream() - .filter(each -> StrUtil.equals("ALARM", each.getType())) + .filter(each -> Objects.equals("ALARM", each.getType())) .forEach(each -> alarmControlHandler.initCacheAndLock(each.getTpId(), each.getPlatform(), each.getInterval()))); } diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/BootstrapConfigPropertiesBinderAdapt.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/BootstrapConfigPropertiesBinderAdapt.java index f5e84f22..9f4c1e0f 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/BootstrapConfigPropertiesBinderAdapt.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/BootstrapConfigPropertiesBinderAdapt.java @@ -17,14 +17,13 @@ package cn.hippo4j.config.springboot.starter.refresher; +import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.config.springboot.starter.config.BootstrapConfigProperties; import cn.hippo4j.config.springboot.starter.config.DynamicThreadPoolNotifyProperties; import cn.hippo4j.config.springboot.starter.config.ExecutorProperties; import cn.hippo4j.config.springboot.starter.config.NotifyPlatformProperties; -import cn.hutool.core.bean.BeanUtil; -import cn.hutool.core.bean.copier.CopyOptions; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; @@ -131,10 +130,10 @@ public class BootstrapConfigPropertiesBinderAdapt { break; } if (CollectionUtil.isNotEmpty(executorSingleMap)) { - ExecutorProperties executorProperties = BeanUtil.mapToBean(executorSingleMap, ExecutorProperties.class, true, CopyOptions.create()); + ExecutorProperties executorProperties = BeanUtil.mapToBean(executorSingleMap, ExecutorProperties.class, true); if (executorProperties != null) { if (CollectionUtil.isNotEmpty(notifySingleMap)) { - DynamicThreadPoolNotifyProperties alarm = BeanUtil.mapToBean(notifySingleMap, DynamicThreadPoolNotifyProperties.class, true, CopyOptions.create()); + DynamicThreadPoolNotifyProperties alarm = BeanUtil.mapToBean(notifySingleMap, DynamicThreadPoolNotifyProperties.class, true); alarm.setReceives(alarm.getReceives()); executorProperties.setNotify(alarm); } @@ -142,7 +141,7 @@ public class BootstrapConfigPropertiesBinderAdapt { } } if (CollectionUtil.isNotEmpty(platformSingleMap)) { - NotifyPlatformProperties notifyPlatformProperties = BeanUtil.mapToBean(platformSingleMap, NotifyPlatformProperties.class, true, CopyOptions.create()); + NotifyPlatformProperties notifyPlatformProperties = BeanUtil.mapToBean(platformSingleMap, NotifyPlatformProperties.class, true); if (notifyPlatformProperties != null) { notifyPropertiesList.add(notifyPlatformProperties); } diff --git a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/AdapterExecutorsRefreshListener.java b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/AdapterExecutorsRefreshListener.java index 552a1f69..e0a2dde2 100644 --- a/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/AdapterExecutorsRefreshListener.java +++ b/hippo4j-spring-boot/hippo4j-config-spring-boot-starter/src/main/java/cn/hippo4j/config/springboot/starter/refresher/event/AdapterExecutorsRefreshListener.java @@ -20,11 +20,12 @@ package cn.hippo4j.config.springboot.starter.refresher.event; import cn.hippo4j.adapter.base.ThreadPoolAdapter; import cn.hippo4j.adapter.base.ThreadPoolAdapterParameter; import cn.hippo4j.common.config.ApplicationContextHolder; +import cn.hippo4j.common.toolkit.BeanUtil; import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.config.springboot.starter.config.AdapterExecutorProperties; import cn.hippo4j.config.springboot.starter.support.DynamicThreadPoolAdapterRegister; -import cn.hutool.core.bean.BeanUtil; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; import org.springframework.core.annotation.Order; import java.util.List; @@ -63,7 +64,7 @@ public class AdapterExecutorsRefreshListener extends AbstractRefreshListener { if (Objects.equals(val.mark(), each.getMark())) { - val.updateThreadPool(BeanUtil.toBean(each, ThreadPoolAdapterParameter.class)); + val.updateThreadPool(BeanUtil.convert(each, ThreadPoolAdapterParameter.class)); DynamicThreadPoolAdapterRegister.ADAPTER_EXECUTORS_MAP.put(buildKey, each); } }); diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DiscoveryConfiguration.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DiscoveryConfiguration.java index 255a28e1..f46f102b 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DiscoveryConfiguration.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/config/DiscoveryConfiguration.java @@ -24,7 +24,6 @@ import cn.hippo4j.core.toolkit.inet.InetUtils; import cn.hippo4j.springboot.starter.toolkit.CloudCommonIdUtil; import cn.hippo4j.springboot.starter.core.DiscoveryClient; import cn.hippo4j.springboot.starter.remote.HttpAgent; -import cn.hutool.core.text.StrBuilder; import lombok.AllArgsConstructor; import lombok.SneakyThrows; import org.springframework.context.annotation.Bean; @@ -57,7 +56,11 @@ public class DiscoveryConfiguration { String active = environment.getProperty("spring.profiles.active", "UNKNOWN"); InstanceInfo instanceInfo = new InstanceInfo(); String instanceId = CloudCommonIdUtil.getDefaultInstanceId(environment, hippo4JInetUtils); - instanceId = StrBuilder.create().append(instanceId).append(IDENTIFY_SLICER_SYMBOL).append(CLIENT_IDENTIFICATION_VALUE).toString(); + instanceId = new StringBuilder() + .append(instanceId) + .append(IDENTIFY_SLICER_SYMBOL) + .append(CLIENT_IDENTIFICATION_VALUE) + .toString(); String contextPath = environment.getProperty("server.servlet.context-path", ""); instanceInfo.setInstanceId(instanceId) .setIpApplicationName(CloudCommonIdUtil.getIpApplicationName(environment, hippo4JInetUtils)) diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java index 9ffb4908..a3840073 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/ClientWorker.java @@ -20,23 +20,18 @@ package cn.hippo4j.springboot.starter.core; import cn.hippo4j.common.model.ThreadPoolParameterInfo; import cn.hippo4j.common.toolkit.ContentUtil; import cn.hippo4j.common.toolkit.GroupKey; +import cn.hippo4j.common.toolkit.IdUtil; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.web.base.Result; -import cn.hippo4j.core.executor.support.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.springboot.starter.remote.HttpAgent; import cn.hippo4j.springboot.starter.remote.ServerHealthCheck; -import cn.hutool.core.util.IdUtil; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java index f9e8824a..0bc94ea3 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/core/DiscoveryClient.java @@ -24,13 +24,12 @@ import cn.hippo4j.common.model.InstanceInfo; import cn.hippo4j.common.web.base.Result; import cn.hippo4j.common.web.base.Results; import cn.hippo4j.common.web.exception.ErrorCodeEnum; -import cn.hippo4j.core.executor.support.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.springboot.starter.remote.HttpAgent; -import cn.hutool.core.text.StrBuilder; -import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.DisposableBean; +import java.util.Objects; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; @@ -93,7 +92,7 @@ public class DiscoveryClient implements DisposableBean { String clientCloseUrlPath = Constants.BASE_PATH + "/client/close"; Result clientCloseResult; try { - String groupKeyIp = StrBuilder.create() + String groupKeyIp = new StringBuilder() .append(instanceInfo.getGroupKey()) .append(Constants.GROUP_KEY_DELIMITER) .append(instanceInfo.getIdentify()) @@ -133,7 +132,7 @@ public class DiscoveryClient implements DisposableBean { .setLastDirtyTimestamp(instanceInfo.getLastDirtyTimestamp().toString()) .setStatus(instanceInfo.getStatus().toString()); renewResult = httpAgent.httpPostByDiscovery(BASE_PATH + "/apps/renew", instanceRenew); - if (StrUtil.equals(ErrorCodeEnum.NOT_FOUND.getCode(), renewResult.getCode())) { + if (Objects.equals(ErrorCodeEnum.NOT_FOUND.getCode(), renewResult.getCode())) { long timestamp = instanceInfo.setIsDirtyWithTime(); boolean success = register(); // TODO Abstract server registration logic diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/ReportingEventExecutor.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/ReportingEventExecutor.java index cbbf8293..6bad05c3 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/ReportingEventExecutor.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/ReportingEventExecutor.java @@ -24,7 +24,7 @@ import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.toolkit.ThreadUtil; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; -import cn.hippo4j.core.executor.support.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.monitor.base.DynamicThreadPoolMonitor; import cn.hippo4j.monitor.base.MonitorTypeEnum; import cn.hippo4j.monitor.base.ThreadPoolMonitor; @@ -32,7 +32,6 @@ import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.springboot.starter.monitor.collect.Collector; import cn.hippo4j.springboot.starter.monitor.send.MessageSender; import cn.hippo4j.springboot.starter.remote.ServerHealthCheck; -import cn.hutool.core.collection.CollUtil; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @@ -162,7 +161,7 @@ public class ReportingEventExecutor implements Runnable, CommandLineRunner, Disp */ private void runTimeGatherTask() { boolean healthStatus = serverHealthCheck.isHealthStatus(); - if (!healthStatus || CollUtil.isEmpty(collectors)) { + if (!healthStatus || CollectionUtil.isEmpty(collectors)) { return; } collectors.forEach((beanName, collector) -> { diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java index c09b57f7..33fc7259 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/monitor/collect/RunTimeInfoCollector.java @@ -22,10 +22,11 @@ import cn.hippo4j.common.monitor.AbstractMessage; import cn.hippo4j.common.monitor.Message; import cn.hippo4j.common.monitor.MessageTypeEnum; import cn.hippo4j.common.monitor.RuntimeMessage; +import cn.hippo4j.common.toolkit.BeanUtil; +import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.core.executor.manage.GlobalThreadPoolManage; import cn.hippo4j.core.executor.state.AbstractThreadPoolRuntime; import cn.hippo4j.springboot.starter.config.BootstrapProperties; -import cn.hutool.core.bean.BeanUtil; import lombok.AllArgsConstructor; import java.util.ArrayList; @@ -48,7 +49,7 @@ public class RunTimeInfoCollector extends AbstractThreadPoolRuntime implements C List listThreadPoolId = GlobalThreadPoolManage.listThreadPoolId(); for (String each : listThreadPoolId) { ThreadPoolRunStateInfo poolRunState = getPoolRunState(each); - RuntimeMessage runtimeMessage = BeanUtil.toBean(poolRunState, RuntimeMessage.class); + RuntimeMessage runtimeMessage = BeanUtil.convert(poolRunState, RuntimeMessage.class); runtimeMessage.setGroupKey(getThreadPoolIdentify(each, properties.getItemId(), properties.getNamespace())); runtimeMessages.add(runtimeMessage); } diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/notify/ServerNotifyConfigBuilder.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/notify/ServerNotifyConfigBuilder.java index 8aeade7a..53ec96fb 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/notify/ServerNotifyConfigBuilder.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/notify/ServerNotifyConfigBuilder.java @@ -17,6 +17,7 @@ package cn.hippo4j.springboot.starter.notify; +import cn.hippo4j.common.toolkit.CollectionUtil; import cn.hippo4j.common.toolkit.GroupKey; import cn.hippo4j.common.toolkit.JSONUtil; import cn.hippo4j.common.web.base.Result; @@ -28,8 +29,6 @@ import cn.hippo4j.message.request.ThreadPoolNotifyRequest; import cn.hippo4j.message.service.AlarmControlHandler; import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.springboot.starter.remote.HttpAgent; -import cn.hutool.core.collection.CollUtil; -import cn.hutool.core.util.StrUtil; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -37,6 +36,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import static cn.hippo4j.common.constant.Constants.BASE_PATH; @@ -56,7 +56,7 @@ public class ServerNotifyConfigBuilder implements NotifyConfigBuilder { @Override public Map> buildNotify() { List threadPoolIds = GlobalThreadPoolManage.listThreadPoolId(); - if (CollUtil.isEmpty(threadPoolIds)) { + if (CollectionUtil.isEmpty(threadPoolIds)) { log.warn("The client does not have a dynamic thread pool instance configured."); return new HashMap<>(); } @@ -81,7 +81,7 @@ public class ServerNotifyConfigBuilder implements NotifyConfigBuilder { List resultData = JSONUtil.parseArray(resultDataStr, ThreadPoolNotifyDTO.class); resultData.forEach(each -> resultMap.put(each.getNotifyKey(), each.getNotifyList())); - resultMap.forEach((key, val) -> val.stream().filter(each -> StrUtil.equals("ALARM", each.getType())) + resultMap.forEach((key, val) -> val.stream().filter(each -> Objects.equals("ALARM", each.getType())) .forEach(each -> alarmControlHandler.initCacheAndLock(each.getTpId(), each.getPlatform(), each.getInterval()))); } return resultMap; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java index 3ca23f0e..b79595b5 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/AbstractHealthCheck.java @@ -20,7 +20,7 @@ package cn.hippo4j.springboot.starter.remote; import cn.hippo4j.common.toolkit.ThreadUtil; import cn.hippo4j.springboot.starter.event.ApplicationCompleteEvent; import cn.hippo4j.springboot.starter.core.ShutdownExecuteException; -import cn.hippo4j.core.executor.support.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.InitializingBean; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerHttpAgent.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerHttpAgent.java index 3a02f4cb..9a2d6bff 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerHttpAgent.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerHttpAgent.java @@ -19,12 +19,12 @@ package cn.hippo4j.springboot.starter.remote; import cn.hippo4j.common.config.ApplicationContextHolder; import cn.hippo4j.common.constant.Constants; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.common.web.base.Result; -import cn.hippo4j.core.executor.support.ThreadFactoryBuilder; +import cn.hippo4j.common.design.builder.ThreadFactoryBuilder; import cn.hippo4j.springboot.starter.config.BootstrapProperties; import cn.hippo4j.springboot.starter.security.SecurityProxy; import cn.hippo4j.springboot.starter.toolkit.HttpClientUtil; -import cn.hutool.core.util.StrUtil; import java.util.HashMap; import java.util.Map; @@ -133,7 +133,7 @@ public class ServerHttpAgent implements HttpAgent { } private Map injectSecurityInfo(Map params) { - if (StrUtil.isNotBlank(securityProxy.getAccessToken())) { + if (StringUtil.isNotBlank(securityProxy.getAccessToken())) { params.put(Constants.ACCESS_TOKEN, securityProxy.getAccessToken()); } return params; diff --git a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java index f3d72823..5166cd9b 100644 --- a/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java +++ b/hippo4j-spring-boot/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/springboot/starter/remote/ServerListManager.java @@ -17,8 +17,8 @@ package cn.hippo4j.springboot.starter.remote; +import cn.hippo4j.common.toolkit.StringUtil; import cn.hippo4j.springboot.starter.config.BootstrapProperties; -import cn.hutool.core.util.StrUtil; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; @@ -56,7 +56,7 @@ public class ServerListManager { List serverAddrList = new ArrayList(); String[] serverAddrListArr = this.serverAddrsStr.split(","); for (String serverAddr : serverAddrListArr) { - boolean whetherJoint = StrUtil.isNotBlank(serverAddr) + boolean whetherJoint = StringUtil.isNotBlank(serverAddr) && !serverAddr.startsWith(HTTPS) && !serverAddr.startsWith(HTTP); if (whetherJoint) { serverAddr = HTTP + serverAddr; diff --git a/pom.xml b/pom.xml index d3955299..d7a593b3 100644 --- a/pom.xml +++ b/pom.xml @@ -32,7 +32,6 @@ 2.9.3 30.0-jre 3.12.0 - 5.4.7 3.12.0 6.1.5.Final 2.12.1 @@ -90,11 +89,6 @@ okhttp ${okhttp3.version} - - cn.hutool - hutool-all - ${hutool-all.version} - org.apache.commons commons-lang3