代码审查优化.

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

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

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

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

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

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

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

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

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

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

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

@ -33,7 +33,7 @@ public class LogRecordValueParser implements BeanFactoryAware {
private final LogRecordExpressionEvaluator expressionEvaluator = new LogRecordExpressionEvaluator(); 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, public Map<String, String> processTemplate(Collection<String> templates, Object ret,
Class<?> targetClass, Method method, Object[] args, String errorMsg, Class<?> targetClass, Method method, Object[] args, String errorMsg,
@ -43,7 +43,7 @@ public class LogRecordValueParser implements BeanFactoryAware {
for (String expressionTemplate : templates) { for (String expressionTemplate : templates) {
if (expressionTemplate.contains("{")) { if (expressionTemplate.contains("{")) {
Matcher matcher = pattern.matcher(expressionTemplate); Matcher matcher = PATTERN.matcher(expressionTemplate);
StringBuffer parsedStr = new StringBuffer(); StringBuffer parsedStr = new StringBuffer();
while (matcher.find()) { while (matcher.find()) {
String expression = matcher.group(2); 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) { 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); EvaluationContext evaluationContext = expressionEvaluator.createEvaluationContext(method, args, targetClass, null, null, beanFactory);
for (String expressionTemplate : templates) { for (String expressionTemplate : templates) {
if (expressionTemplate.contains("{")) { if (expressionTemplate.contains("{")) {
Matcher matcher = pattern.matcher(expressionTemplate); Matcher matcher = PATTERN.matcher(expressionTemplate);
while (matcher.find()) { while (matcher.find()) {
String expression = matcher.group(2); String expression = matcher.group(2);
if (expression.contains("#_ret") || expression.contains("#_errorMsg")) { if (expression.contains("#_ret") || expression.contains("#_errorMsg")) {

Loading…
Cancel
Save