Globally remove the Hutooltoolkit dependency (#759) (#762)

* fix : global remove hutool(#725)

* fix : update use for hutool(#725)

* fix : Replenish toolkit(#725)

* fix : merge branch conflicts(#725)

* fix : modify code format(#725)

* fix : config BeanUtil merged to common(#725)

* fix : add IdUtil for generate UUID(#725)

* fix : replace method for convert bean(#725)

Co-authored-by: pizihao <hao3073liu@163.com>
pull/764/head
pizihao 2 years ago committed by GitHub
parent 50746f41fe
commit e03d464053
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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());
}

@ -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();

@ -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;
}

@ -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;
}
}

@ -46,11 +46,6 @@
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>

@ -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<String, Object> 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")));
}
}

@ -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);

@ -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<GrantedAuthority> 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);
}
}

@ -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<PermissionRespDTO> listPermission(int pageNo, int pageSize) {
PermissionQueryPageReqDTO queryPage = new PermissionQueryPageReqDTO(pageNo, pageSize);
IPage<PermissionInfo> 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<PermissionInfo> 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);
}
}

@ -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<RoleRespDTO> listRole(int pageNo, int pageSize) {
RoleQueryPageReqDTO queryPage = new RoleQueryPageReqDTO(pageNo, pageSize);
IPage<RoleInfo> 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<String> roleStrList = CollUtil.toList(role);
if (StrUtil.isBlank(role)) {
List<String> roleStrList = CollectionUtil.toList(role);
if (StringUtil.isBlank(role)) {
LambdaQueryWrapper<RoleInfo> queryWrapper = Wrappers.lambdaQuery(RoleInfo.class).eq(RoleInfo::getUserName, userName);
roleStrList = roleMapper.selectList(queryWrapper).stream().map(RoleInfo::getRole).collect(Collectors.toList());
}
LambdaUpdateWrapper<RoleInfo> 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, "", ""));
}

@ -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<UserInfo> queryWrapper = Wrappers.lambdaQuery(UserInfo.class)
.eq(StringUtil.isNotBlank(reqDTO.getUserName()), UserInfo::getUserName, reqDTO.getUserName());
IPage<UserInfo> 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<UserInfo> 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;
}

@ -61,11 +61,6 @@
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -76,6 +71,11 @@
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
</dependency>
</dependencies>
<build>

@ -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;

@ -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);

@ -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, S> T convert(S source, Class<T> clazz) {
return Optional.ofNullable(source)
.map(each -> BEAN_MAPPER_BUILDER.map(each, clazz))
.orElse(null);
}
public static <T, S> T convert(S source, T target) {
Optional.ofNullable(source)
.ifPresent(each -> BEAN_MAPPER_BUILDER.map(each, target));
return target;
}
public static <T, S> List<T> convert(List<S> sources, Class<T> clazz) {
return Optional.ofNullable(sources)
.map(each -> {
List<T> targetList = new ArrayList<T>(each.size());
each.forEach(item -> targetList.add(BEAN_MAPPER_BUILDER.map(item, clazz)));
return targetList;
})
.orElse(null);
}
public static <T, S> Set<T> convert(Set<S> sources, Class<T> clazz) {
return Optional.ofNullable(sources)
.map(each -> {
Set<T> targetSize = new HashSet<T>(each.size());
each.forEach(item -> targetSize.add(BEAN_MAPPER_BUILDER.map(item, clazz)));
return targetSize;
})
.orElse(null);
}
public static <T> T mapToBean(Map<String, Object> map, Class<T> 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 <T> bean type
* @return T
*/
public static <T> T mapToBean(Map<String, Object> 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);
}
}
}

@ -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);
}

@ -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 <T> type
* @return List
*/
public static <T> List<T> toList(T... ts) {
if (ts == null || ts.length == 0) {
return new ArrayList<>();
}
return Arrays.stream(ts)
.collect(Collectors.toList());
}
/**
* reference google guava
*

@ -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 <tt>Date</tt> 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);
}
}

@ -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<String> readLines(String path, Charset charset) {
List<String> 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;
}
}

@ -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. <br>
* {@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);
}
}

@ -41,7 +41,7 @@ public class MessageConvert {
MessageWrapper wrapper = new MessageWrapper();
wrapper.setResponseClass(message.getClass());
wrapper.setMessageType(message.getMessageType());
List<Map<String, Object>> messageMapList = new ArrayList();
List<Map<String, Object>> messageMapList = new ArrayList<>();
List<Message> messages = message.getMessages();
messages.forEach(each -> {
String eachVal = JSONUtil.toJSONString(each);

@ -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<Class<?>, Field[]> FIELDS_CACHE = new ConcurrentHashMap();
private static final Map<Class<?>, 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 <br>
* 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> T invoke(Object obj, Method method, Object... arguments) {
try {
return (T) method.invoke(obj, arguments);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalException(e);
}
}
}

@ -29,7 +29,7 @@ import java.util.function.Supplier;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Singleton {
private static final ConcurrentHashMap<String, Object> SINGLE_OBJECT_POOL = new ConcurrentHashMap();
private static final ConcurrentHashMap<String, Object> SINGLE_OBJECT_POOL = new ConcurrentHashMap<>();
/**
* Get a singleton object by key.

@ -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);
}
}

@ -28,7 +28,7 @@ import java.util.Optional;
*/
public class UserContext {
private static final ThreadLocal<User> USER_THREAD_LOCAL = new ThreadLocal();
private static final ThreadLocal<User> USER_THREAD_LOCAL = new ThreadLocal<>();
public static void setUserInfo(String username, String userRole) {
USER_THREAD_LOCAL.set(new User(username, userRole));

@ -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);
}
}

@ -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<PersonVo> 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<PersonVo> 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<String, Object> 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;
}
}

@ -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));
}
}

@ -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<String> readLines = FileUtil.readLines(testFilePath, StandardCharsets.UTF_8);
Assert.assertEquals(3, readLines.size());
}
}

@ -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("-"));
}
}

@ -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;

@ -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"));
}
}

@ -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));
}
}

@ -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";

@ -49,22 +49,6 @@
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>cn.hippo4j</groupId>
<artifactId>hippo4j-common</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
@ -80,6 +64,11 @@
<artifactId>netty-all</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>

@ -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<String, String> bodyMap) {
String groupKey = bodyMap.get(Constants.GROUP_KEY);
if (StrUtil.isNotBlank(groupKey)) {
if (StringUtil.isNotBlank(groupKey)) {
ConfigCacheService.removeConfigCache(groupKey);
}
return Results.success();

@ -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<HisRunDataInfo> queryWrapper = Wrappers.lambdaQuery(HisRunDataInfo.class)
.le(HisRunDataInfo::getTimestamp, offsetMinuteDateTime.getTime());
.le(HisRunDataInfo::getTimestamp, DateUtil.getTime(offsetMinuteDateTime));
hisRunDataService.remove(queryWrapper);
}

@ -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<AbstractSubscriber> subscribers = new ConcurrentHashSet();
protected final Set<AbstractSubscriber> subscribers = Collections.synchronizedSet(new HashSet<>());
private BlockingQueue<AbstractEvent> queue;

@ -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<Class<? extends AbstractSlowEvent>, Set<AbstractSubscriber>> subMappings = new ConcurrentHashMap();
protected final ConcurrentHashSet<AbstractSubscriber> subscribers = new ConcurrentHashSet();
protected final Set<AbstractSubscriber> subscribers = Collections.synchronizedSet(new HashSet<>());
private final Lock lock = new ReentrantLock();
@ -46,7 +47,7 @@ public class DefaultSharePublisher extends DefaultPublisher {
try {
Set<AbstractSubscriber> sets = subMappings.get(subSlowEventType);
if (sets == null) {
Set<AbstractSubscriber> newSet = new ConcurrentHashSet();
Set<AbstractSubscriber> newSet = Collections.synchronizedSet(new HashSet<>());
newSet.add(subscriber);
subMappings.put(subSlowEventType, newSet);
return;

@ -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<String, CacheItem> 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);

@ -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<String> 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<String> changedGroups) {
if (CollUtil.isNotEmpty(changedGroups)) {
if (CollectionUtil.isNotEmpty(changedGroups)) {
try {
String respStr = buildRespStr(changedGroups);
response.setHeader("Pragma", "no-cache");

@ -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<String> addressList = actual.stream().map(ThreadPoolAdapterState::getClientAddress).collect(Collectors.toList());
List<ThreadPoolAdapterRespDTO> 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<String, Object> 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<ThreadPoolAdapterRespDTO> restResult = JSONUtil.parseObject(resultStr, new TypeReference<Result<ThreadPoolAdapterRespDTO>>() {
});

@ -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<ConfigAllInfo> 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<ConfigInstanceInfo> instanceQueryWrapper = Wrappers.lambdaQuery(ConfigInstanceInfo.class)
.eq(ConfigInstanceInfo::getTpId, params[0])
.eq(ConfigInstanceInfo::getItemId, params[1])

@ -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<HisRunDataMapper, HisRunD
@Override
public List<MonitorRespDTO> 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<HisRunDataInfo> 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<HisRunDataMapper, HisRunD
@Override
public MonitorActiveRespDTO queryInfoThreadPoolMonitor(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<HisRunDataInfo> 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<String> times = new ArrayList<>();
@ -127,16 +127,16 @@ public class HisRunDataServiceImpl extends ServiceImpl<HisRunDataMapper, HisRunD
@Override
public MonitorRespDTO queryThreadPoolLastTaskCount(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);
HisRunDataInfo hisRunDataInfo = this.lambdaQuery()
.eq(HisRunDataInfo::getTenantId, reqDTO.getTenantId())
.eq(HisRunDataInfo::getItemId, reqDTO.getItemId())
.eq(HisRunDataInfo::getTpId, reqDTO.getTpId())
.eq(HisRunDataInfo::getInstanceId, reqDTO.getInstanceId())
.orderByDesc(HisRunDataInfo::getTimestamp)
.between(HisRunDataInfo::getTimestamp, startTime, currentDate.getTime())
.between(HisRunDataInfo::getTimestamp, startTime, DateUtil.getTime(currentDate))
.last("LIMIT 1")
.one();
return BeanUtil.convert(hisRunDataInfo, MonitorRespDTO.class);

@ -28,7 +28,7 @@ import cn.hippo4j.config.model.biz.item.ItemUpdateReqDTO;
import cn.hippo4j.config.model.biz.threadpool.ThreadPoolRespDTO;
import cn.hippo4j.config.service.biz.ItemService;
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.CollectionUtils;

@ -18,8 +18,10 @@
package cn.hippo4j.config.service.biz.impl;
import cn.hippo4j.common.enums.EnableEnum;
import cn.hippo4j.common.toolkit.CollectionUtil;
import cn.hippo4j.common.toolkit.BooleanUtil;
import cn.hippo4j.common.toolkit.GroupKey;
import cn.hippo4j.common.toolkit.StringUtil;
import cn.hippo4j.common.web.exception.ServiceException;
import cn.hippo4j.config.mapper.NotifyInfoMapper;
import cn.hippo4j.config.model.NotifyInfo;
@ -28,9 +30,7 @@ import cn.hippo4j.config.model.biz.notify.NotifyQueryReqDTO;
import cn.hippo4j.config.model.biz.notify.NotifyReqDTO;
import cn.hippo4j.config.model.biz.notify.NotifyRespDTO;
import cn.hippo4j.config.service.biz.NotifyService;
import cn.hippo4j.config.toolkit.BeanUtil;
import cn.hutool.core.collection.CollUtil;
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.metadata.IPage;
@ -58,12 +58,12 @@ public class NotifyServiceImpl implements NotifyService {
reqDTO.getGroupKeys().forEach(each -> {
String[] parseKey = GroupKey.parseKey(each);
List<NotifyInfo> 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<NotifyInfo> 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<NotifyRespDTO> queryPage(NotifyQueryReqDTO reqDTO) {
LambdaQueryWrapper<NotifyInfo> 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<NotifyInfo> 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<NotifyInfo> existNotifyInfos = notifyInfoMapper.selectList(queryWrapper);
if (CollUtil.isNotEmpty(existNotifyInfos)) {
if (CollectionUtil.isNotEmpty(existNotifyInfos)) {
throw new ServiceException(String.format("%s 新增通知报警配置重复", type));
}
}

@ -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<LogRecordRespDTO> queryPage(LogRecordQueryReqDTO pageQuery) {
LambdaQueryWrapper<LogRecordInfo> 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<LogRecordInfo> selectPage = operationLogMapper.selectPage(pageQuery, queryWrapper);
return selectPage.convert(each -> BeanUtil.convert(each, LogRecordRespDTO.class));

@ -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;

@ -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;

@ -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) {

@ -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, S> T convert(S source, Class<T> clazz) {
return Optional.ofNullable(source)
.map(each -> BEAN_MAPPER_BUILDER.map(each, clazz))
.orElse(null);
}
public static <T, S> List<T> convert(List<S> sources, Class<T> clazz) {
return Optional.ofNullable(sources)
.map(each -> {
List<T> targetList = new ArrayList<T>(each.size());
each.stream()
.forEach(item -> targetList.add(BEAN_MAPPER_BUILDER.map(item, clazz)));
return targetList;
})
.orElse(null);
}
public static <T, S> Set<T> convert(Set<S> sources, Class<T> clazz) {
return Optional.ofNullable(sources)
.map(each -> {
Set<T> targetSize = new HashSet<T>(each.size());
each.stream()
.forEach(item -> targetSize.add(BEAN_MAPPER_BUILDER.map(item, clazz)));
return targetSize;
})
.orElse(null);
}
}

@ -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<String> parseMapForFilter(Map<String, ?> sourceMap, String filters) {
List<String> resultList = new ArrayList<>();
if (CollUtil.isEmpty(sourceMap)) {
if (CollectionUtil.isEmpty(sourceMap)) {
return resultList;
}
sourceMap.forEach((key, val) -> {

@ -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;
}
}

@ -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;

@ -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

@ -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;

@ -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));
}
}

@ -37,10 +37,6 @@
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
</dependencies>
<build>

@ -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<List<ThreadPoolAdapterRespDTO>> queryAdapterThreadPool(ThreadPoolAdapterReqDTO requestParameter) {
List<ThreadPoolAdapterRespDTO> result = threadPoolAdapterService.query(requestParameter);
@ -61,8 +63,12 @@ public class ThreadPoolAdapterController {
@PostMapping(REGISTER_ADAPTER_BASE_PATH + "/update")
public Result<Void> 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();
}

@ -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<IPage<ThreadPoolRespDTO>> 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<Lease<InstanceInfo>> leases = baseInstanceRegistry.listInstance(reqDTO.getItemId());
Lease<InstanceInfo> first = CollUtil.getFirst(leases);
Lease<InstanceInfo> 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<Lease<InstanceInfo>> leases = baseInstanceRegistry.listInstance(itemId);
Lease<InstanceInfo> first = CollUtil.getFirst(leases);
Lease<InstanceInfo> 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<Void> 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<List<ThreadPoolInstanceInfo>> listInstance(@PathVariable("itemId") String itemId,
@PathVariable("tpId") String tpId) {
List<Lease<InstanceInfo>> leases = baseInstanceRegistry.listInstance(itemId);
Lease<InstanceInfo> first = CollUtil.getFirst(leases);
Lease<InstanceInfo> 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<String, CacheItem> content = ConfigCacheService.getContent(groupKey);
Map<String, String> 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<String, String> clientBasePathMap = leases.stream().map(each -> each.getHolder())
Map<String, String> clientBasePathMap = leases.stream().map(Lease::getHolder)
.filter(each -> StringUtil.isNotBlank(each.getClientBasePath()))
.collect(Collectors.toMap(InstanceInfo::getIdentify, InstanceInfo::getClientBasePath));
List<ThreadPoolInstanceInfo> 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));

@ -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<HisRunDataMapper.ThreadPoolTaskRanking> 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<HisRunDataMapper.ThreadPoolTaskRanking> threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolMaxRanking(startTime, currentTime);
List<Object> oneList = new ArrayList<>();
List<Object> twoList = new ArrayList<>();
List<Object> 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<String, Object> dict = new LinkedHashMap<>();
dict.put("name", tenant.getTenantId());
dict.put("value", tenantThreadPoolNum);
tenantChartList.add(dict);
}
List<Map<String, Object>> 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<String, Object> 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<RankingChart.RankingChartInfo> resultList = new ArrayList<>();
List<HisRunDataMapper.ThreadPoolTaskRanking> threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolTaskSumRanking(tenTime.getTime(), currentDate.getTime());
List<HisRunDataMapper.ThreadPoolTaskRanking> threadPoolTaskRankings = hisRunDataMapper.queryThreadPoolTaskSumRanking(startTime, currentTime);
threadPoolTaskRankings.forEach(each -> {
RankingChart.RankingChartInfo rankingChartInfo = new RankingChart.RankingChartInfo();
rankingChartInfo.setMaxCompletedTaskCount(each.getMaxCompletedTaskCount());
List<Lease<InstanceInfo>> leases = baseInstanceRegistry.listInstance(each.getItemId());
Lease<InstanceInfo> first = CollUtil.getFirst(leases);
Lease<InstanceInfo> first = CollectionUtil.getFirst(leases);
if (first == null) {
rankingChartInfo.setInst(0);
} else {

@ -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;
}
}

@ -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);
}

@ -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());

@ -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);

@ -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;

@ -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) {

@ -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<InstanceInfo> {
new ScheduledThreadPoolExecutor(
SCHEDULED_THREAD_CORE_NUM,
new ThreadFactoryBuilder()
.setNamePrefix("registry-eviction")
.setDaemon(true)
.prefix("registry-eviction")
.daemon(true)
.build());
private final AtomicReference<EvictionTask> evictionTaskRef = new AtomicReference();

@ -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());
}

@ -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);
}
}
});
}

@ -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);
}
});
}

@ -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)

@ -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)

@ -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)

@ -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)

@ -39,10 +39,6 @@
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
</dependencies>
<build>

@ -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<AlarmNotifyReq
String larkAlarmTimoutTraceReplaceJson = Singleton.get(larkAlarmTimoutTraceReplaceJsonKey, () -> 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<AlarmNotifyReq
// 告警手机号
afterReceives,
// 当前时间
DateUtil.now(),
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
// 报警频率
notifyConfig.getInterval());
execute(notifyConfig.getSecretKey(), text);
@ -156,7 +157,7 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
// 告警手机号
afterReceives,
// 当前时间
DateUtil.now());
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
execute(notifyConfig.getSecretKey(), text);
}
@ -165,14 +166,15 @@ public class LarkSendMessageHandler implements SendMessageHandler<AlarmNotifyReq
return "";
}
return Arrays.stream(receives.split(","))
.map(receive -> 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);
}

@ -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);
}

@ -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());
}
}

@ -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<String, String> cache = Caffeine.newBuilder()
.expireAfterWrite(interval, TimeUnit.MINUTES)
.build();

@ -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<NotifyConfigDTO> 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<NotifyConfigDTO> notifyList = notifyConfigs.get(buildKey);
if (CollUtil.isEmpty(notifyList)) {
if (CollectionUtil.isEmpty(notifyList)) {
log.warn("Please configure alarm notification on the server. key: [{}]", threadPoolId);
return;
}

@ -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<String> rawMapping = FileUtil.readLines(new File(Thread.currentThread().getContextClassLoader().getResource("mapping.json").getPath()), StandardCharsets.UTF_8);
List<String> 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);

@ -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");

@ -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;

@ -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<String, List<NotifyConfigDTO>> 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())));
}

@ -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);
}

@ -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<Ada
|| !Objects.equals(adapterExecutorProperties.getMaximumPoolSize(), each.getMaximumPoolSize())) {
threadPoolAdapterMap.forEach((key, val) -> {
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);
}
});

@ -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))

@ -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;

@ -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

@ -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) -> {

@ -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<String> 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);
}

@ -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<String, List<NotifyConfigDTO>> buildNotify() {
List<String> 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<ThreadPoolNotifyDTO> 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;

@ -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;

@ -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<String, String> params) {
if (StrUtil.isNotBlank(securityProxy.getAccessToken())) {
if (StringUtil.isNotBlank(securityProxy.getAccessToken())) {
params.put(Constants.ACCESS_TOKEN, securityProxy.getAccessToken());
}
return params;

@ -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<String> 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;

@ -32,7 +32,6 @@
<caffeine.version>2.9.3</caffeine.version>
<guava.version>30.0-jre</guava.version>
<okhttp3.version>3.12.0</okhttp3.version>
<hutool-all.version>5.4.7</hutool-all.version>
<commons-lang3.version>3.12.0</commons-lang3.version>
<hibernate-validator.version>6.1.5.Final</hibernate-validator.version>
<transmittable-thread-local.version>2.12.1</transmittable-thread-local.version>
@ -90,11 +89,6 @@
<artifactId>okhttp</artifactId>
<version>${okhttp3.version}</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool-all.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>

Loading…
Cancel
Save