代码审查优化.

pull/87/head
chen.ma 2 years ago
parent 79f6765054
commit 45d2d9569e

@ -1,12 +1,12 @@
package cn.hippo4j.auth.filter;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
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.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;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -27,6 +27,7 @@ import java.util.Map;
import static cn.hippo4j.auth.constant.Constants.SPLIT_COMMA;
import static cn.hippo4j.common.constant.Constants.BASE_PATH;
import static cn.hippo4j.common.constant.Constants.MAP_INITIAL_CAPACITY;
/**
* JWT authentication filter.
@ -37,9 +38,9 @@ import static cn.hippo4j.common.constant.Constants.BASE_PATH;
@Slf4j
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
private final AuthenticationManager authenticationManager;
private ThreadLocal<Integer> rememberMe = new ThreadLocal();
private final ThreadLocal<Integer> rememberMe = new ThreadLocal();
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
@ -54,7 +55,7 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
LoginUser loginUser = new ObjectMapper().readValue(request.getInputStream(), LoginUser.class);
rememberMe.set(loginUser.getRememberMe());
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList<>())
new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword(), new ArrayList())
);
} catch (IOException e) {
logger.error("attemptAuthentication error :{}", e);
@ -67,22 +68,26 @@ public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilte
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException {
JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
boolean isRemember = rememberMe.get() == 1;
try {
JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
boolean isRemember = rememberMe.get() == 1;
String role = "";
Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
for (GrantedAuthority authority : authorities) {
role = authority.getAuthority();
}
String role = "";
Collection<? extends GrantedAuthority> authorities = jwtUser.getAuthorities();
for (GrantedAuthority authority : authorities) {
role = authority.getAuthority();
}
String token = JwtTokenUtil.createToken(jwtUser.getId(), jwtUser.getUsername(), role, isRemember);
response.setHeader("token", JwtTokenUtil.TOKEN_PREFIX + token);
response.setCharacterEncoding("UTF-8");
Map<String, Object> maps = new HashMap<>();
maps.put("data", JwtTokenUtil.TOKEN_PREFIX + token);
maps.put("roles", role.split(SPLIT_COMMA));
response.getWriter().write(JSONUtil.toJsonStr(Results.success(maps)));
String token = JwtTokenUtil.createToken(jwtUser.getId(), jwtUser.getUsername(), role, isRemember);
response.setHeader("token", JwtTokenUtil.TOKEN_PREFIX + token);
response.setCharacterEncoding("UTF-8");
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)));
} finally {
rememberMe.remove();
}
}
@Override

@ -11,6 +11,8 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import static cn.hippo4j.common.constant.Constants.MAP_INITIAL_CAPACITY;
/**
* Jwt token util.
*
@ -51,7 +53,7 @@ public class JwtTokenUtil {
*/
public static String createToken(Long id, String username, String role, boolean isRememberMe) {
long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
HashMap<String, Object> map = new HashMap<>();
HashMap<String, Object> map = new HashMap(MAP_INITIAL_CAPACITY);
map.put(ROLE_CLAIMS, role);
return Jwts.builder()
.signWith(SignatureAlgorithm.HS512, SECRET)

@ -101,14 +101,29 @@ public class InstanceInfo {
public enum InstanceStatus {
/**
* UP
*/
UP,
/**
* DOWN
*/
DOWN,
/**
* STARTING
*/
STARTING,
/**
* OUT_OF_SERVICE
*/
OUT_OF_SERVICE,
/**
* UNKNOWN
*/
UNKNOWN;
public static InstanceStatus toEnum(String s) {
@ -125,10 +140,19 @@ public class InstanceInfo {
}
public enum ActionType {
/**
* ADDED
*/
ADDED,
/**
* MODIFIED
*/
MODIFIED,
/**
* DELETED
*/
DELETED
}

@ -73,21 +73,21 @@ public class CollectionUtil {
/**
* Is empty.
*
* @param Iterator
* @param iterator
* @return
*/
public static boolean isEmpty(Iterator<?> Iterator) {
return null == Iterator || false == Iterator.hasNext();
public static boolean isEmpty(Iterator<?> iterator) {
return null == iterator || false == iterator.hasNext();
}
/**
* Is not empty.
*
* @param Iterator
* @param iterator
* @return
*/
public static boolean isNotEmpty(Iterator<?> Iterator) {
return !isEmpty(Iterator);
public static boolean isNotEmpty(Iterator<?> iterator) {
return !isEmpty(iterator);
}
/**

@ -8,6 +8,9 @@ package cn.hippo4j.common.web.exception;
*/
public enum ErrorCodeEnum {
/**
* UNKNOWN_ERROR
*/
UNKNOWN_ERROR {
@Override
public String getCode() {
@ -20,6 +23,9 @@ public enum ErrorCodeEnum {
}
},
/**
* VALIDATION_ERROR
*/
VALIDATION_ERROR {
@Override
public String getCode() {
@ -32,6 +38,9 @@ public enum ErrorCodeEnum {
}
},
/**
* SERVICE_ERROR
*/
SERVICE_ERROR {
@Override
public String getCode() {
@ -44,6 +53,9 @@ public enum ErrorCodeEnum {
}
},
/**
* NOT_FOUND
*/
NOT_FOUND {
@Override
public String getCode() {

@ -9,7 +9,20 @@ package cn.hippo4j.discovery.core;
public class Lease<T> {
enum Action {
REGISTER, CANCEL, RENEW
/**
* REGISTER
*/
REGISTER,
/**
* CANCEL
*/
CANCEL,
/**
* RENEW
*/
RENEW
}
private T holder;

@ -4,6 +4,12 @@ import cn.hippo4j.starter.enable.EnableDynamicThreadPool;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Example application.
*
* @author chen.ma
* @date 2022/01/23 21:06
*/
@SpringBootApplication
@EnableDynamicThreadPool
public class ExampleApplication {

@ -23,6 +23,9 @@ public class TaskDecoratorTest {
public static final String PLACEHOLDER = "site";
/**
* 线 {@link TaskDecorator}
*/
// @PostConstruct
public void taskDecoratorTest() {
new Thread(() -> {

@ -5,6 +5,12 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Example application.
*
* @author chen.ma
* @date 2022/01/23 21:06
*/
@EnableTransactionManagement
@SpringBootApplication(scanBasePackages = "cn.hippo4j")
@MapperScan(basePackages = {"cn.hippo4j.config.mapper", "cn.hippo4j.auth.mapper"})

@ -82,8 +82,8 @@ public class DiscoveryClient implements DisposableBean {
@Override
public void destroy() throws Exception {
log.info("{}{} - destroy service...", PREFIX, appPathIdentifier);
String ClientCloseUrlPath = Constants.BASE_PATH + "/client/close";
Result clientCLoseResult;
String clientCloseUrlPath = Constants.BASE_PATH + "/client/close";
Result clientCloseResult;
try {
String groupKeyIp = StrBuilder.create()
.append(instanceInfo.getGroupKey())
@ -96,8 +96,8 @@ public class DiscoveryClient implements DisposableBean {
.setInstanceId(instanceInfo.getInstanceId())
.setGroupKey(groupKeyIp);
clientCLoseResult = httpAgent.httpPostByDiscovery(ClientCloseUrlPath, clientCloseHookReq);
if (clientCLoseResult.isSuccess()) {
clientCloseResult = httpAgent.httpPostByDiscovery(clientCloseUrlPath, clientCloseHookReq);
if (clientCloseResult.isSuccess()) {
log.info("{}{} -client close hook success.", PREFIX, appPathIdentifier);
}
} catch (Throwable ex) {

@ -33,7 +33,7 @@ public class LogRecordValueParser implements BeanFactoryAware {
private final LogRecordExpressionEvaluator expressionEvaluator = new LogRecordExpressionEvaluator();
private static final Pattern pattern = Pattern.compile("\\{\\s*(\\w*)\\s*\\{(.*?)}}");
private static final Pattern PATTERN = Pattern.compile("\\{\\s*(\\w*)\\s*\\{(.*?)}}");
public Map<String, String> processTemplate(Collection<String> templates, Object ret,
Class<?> targetClass, Method method, Object[] args, String errorMsg,
@ -43,7 +43,7 @@ public class LogRecordValueParser implements BeanFactoryAware {
for (String expressionTemplate : templates) {
if (expressionTemplate.contains("{")) {
Matcher matcher = pattern.matcher(expressionTemplate);
Matcher matcher = PATTERN.matcher(expressionTemplate);
StringBuffer parsedStr = new StringBuffer();
while (matcher.find()) {
String expression = matcher.group(2);
@ -63,12 +63,12 @@ public class LogRecordValueParser implements BeanFactoryAware {
}
public Map<String, String> processBeforeExecuteFunctionTemplate(Collection<String> templates, Class<?> targetClass, Method method, Object[] args) {
Map<String, String> functionNameAndReturnValueMap = new HashMap<>();
Map<String, String> functionNameAndReturnValueMap = new HashMap(16);
EvaluationContext evaluationContext = expressionEvaluator.createEvaluationContext(method, args, targetClass, null, null, beanFactory);
for (String expressionTemplate : templates) {
if (expressionTemplate.contains("{")) {
Matcher matcher = pattern.matcher(expressionTemplate);
Matcher matcher = PATTERN.matcher(expressionTemplate);
while (matcher.find()) {
String expression = matcher.group(2);
if (expression.contains("#_ret") || expression.contains("#_errorMsg")) {

Loading…
Cancel
Save