🎨 改进结构和代码格式. add spring-javaformat plugin and format all code

This commit is contained in:
lengleng committed 2020-06-14 17:59:04 +08:00
1 parent 5414983f3d
commit bd47066299
651 files changed
+13034 -12462

No files matched your search

@@ -19,15 +19,13 @@
package com.pig4cloud.pigx.gateway;
import com.pig4cloud.pigx.common.gateway.annotation.EnablePigxDynamicRoute;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
/**
* @author lengleng
* @date 2018年06月21日
* 网关应用
* @date 2018年06月21日 网关应用
*/
@EnablePigxDynamicRoute
@SpringCloudApplication
@@ -36,4 +34,5 @@ public class PigxGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(PigxGatewayApplication.class, args);
}
}
@@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit;
@Component
@AllArgsConstructor
public class CaptchaCacheServiceProvider implements CaptchaCacheService {
private final StringRedisTemplate stringRedisTemplate;
@Override
@@ -39,4 +40,5 @@ public class CaptchaCacheServiceProvider implements CaptchaCacheService {
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
}
@@ -28,8 +28,7 @@ import java.util.List;
/**
* @author lengleng
* @date 2018/7/22
* 网关不校验终端配置
* @date 2018/7/22 网关不校验终端配置
*/
@Data
@Configuration
@@ -37,6 +36,9 @@ import java.util.List;
@ConditionalOnExpression("!'${ignore}'.isEmpty()")
@ConfigurationProperties(prefix = "ignore")
public class FilterIgnorePropertiesConfig {
private List<String> clients = new ArrayList<>();
private List<String> swaggerProviders=new ArrayList<>();
private List<String> swaggerProviders = new ArrayList<>();
}
@@ -26,13 +26,14 @@ import reactor.core.publisher.Mono;
/**
* @author lengleng
* @date 2018/7/1
* 路由限流配置
* @date 2018/7/1 路由限流配置
*/
@Configuration
public class RateLimiterConfiguration {
@Bean(value = "remoteAddrKeyResolver")
public KeyResolver remoteAddrKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
}
@@ -29,28 +29,32 @@ import org.springframework.web.reactive.function.server.RouterFunctions;
/**
* @author lengleng
* @date 2018/7/5
* 路由配置信息
* @date 2018/7/5 路由配置信息
*/
@Slf4j
@Configuration
@AllArgsConstructor
public class RouterFunctionConfiguration {
private final ImageCodeCheckHandler imageCodeCheckHandler;
private final ImageCodeCreateHandler imageCodeCreateHandler;
private final SwaggerResourceHandler swaggerResourceHandler;
private final SwaggerSecurityHandler swaggerSecurityHandler;
private final SwaggerUiHandler swaggerUiHandler;
@Bean
public RouterFunction routerFunction() {
return RouterFunctions.route(
RequestPredicates.path("/code")
.and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), imageCodeCreateHandler)
.andRoute(RequestPredicates.POST("/code/check")
.and(RequestPredicates.accept(MediaType.ALL)), imageCodeCheckHandler)
.andRoute(RequestPredicates.GET("/swagger-resources")
.and(RequestPredicates.accept(MediaType.ALL)), swaggerResourceHandler)
return RouterFunctions
.route(RequestPredicates.path("/code").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
imageCodeCreateHandler)
.andRoute(RequestPredicates.POST("/code/check").and(RequestPredicates.accept(MediaType.ALL)),
imageCodeCheckHandler)
.andRoute(RequestPredicates.GET("/swagger-resources").and(RequestPredicates.accept(MediaType.ALL)),
swaggerResourceHandler)
.andRoute(RequestPredicates.GET("/swagger-resources/configuration/ui")
.and(RequestPredicates.accept(MediaType.ALL)), swaggerUiHandler)
.andRoute(RequestPredicates.GET("/swagger-resources/configuration/security")
@@ -32,28 +32,32 @@ import java.util.List;
import java.util.stream.Collectors;
/**
* @author Sywd
* 聚合接口文档注册,和zuul实现类似
* @author Sywd 聚合接口文档注册,和zuul实现类似
*/
@Component
@Primary
@AllArgsConstructor
public class SwaggerProvider implements SwaggerResourcesProvider {
private static final String API_URI = "/v2/api-docs";
private final RouteDefinitionRepository routeDefinitionRepository;
private final FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;
@Override
public List<SwaggerResource> get() {
List<RouteDefinition> routes = new ArrayList<>();
routeDefinitionRepository.getRouteDefinitions().subscribe(routes::add);
return routes.stream().flatMap(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
.filter(predicateDefinition -> !filterIgnorePropertiesConfig.getSwaggerProviders().contains(routeDefinition.getId()))
.map(predicateDefinition ->
swaggerResource(routeDefinition.getId(), predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", API_URI))
)).sorted(Comparator.comparing(SwaggerResource::getName))
.collect(Collectors.toList());
return routes.stream()
.flatMap(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
.filter(predicateDefinition -> !filterIgnorePropertiesConfig.getSwaggerProviders()
.contains(routeDefinition.getId()))
.map(predicateDefinition -> swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**",
API_URI))))
.sorted(Comparator.comparing(SwaggerResource::getName)).collect(Collectors.toList());
}
private static SwaggerResource swaggerResource(String name, String location) {
@@ -63,4 +67,5 @@ public class SwaggerProvider implements SwaggerResourcesProvider {
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
@@ -36,12 +36,14 @@ import org.springframework.web.server.ServerWebExchange;
@Slf4j
@Component
public class HttpBasicGatewayFilter extends AbstractGatewayFilterFactory {
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
if (hasAuth(exchange)) {
return chain.filter(exchange);
} else {
}
else {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add(HttpHeaders.WWW_AUTHENTICATE, "Basic Realm=\"pigx\"");
@@ -52,7 +54,6 @@ public class HttpBasicGatewayFilter extends AbstractGatewayFilterFactory {
/**
* 简单的basic认证
*
* @param exchange 上下文
* @return 是否有权限
*/
@@ -55,22 +55,23 @@ import java.util.function.Function;
/**
* @author lengleng
* @date 2020/1/8
* 密码解密工具类
* @date 2020/1/8 密码解密工具类
* <p>
* 参考 ModifyRequestBodyGatewayFilterFactory 实现
*/
@Slf4j
@Component
public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
private final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
private static final String PASSWORD = "password";
private static final String KEY_ALGORITHM = "AES";
@Value("${security.encode.key:1234567812345678}")
private String encodeKey;
@Override
public GatewayFilter apply(Object config) {
return (exchange, chain) -> {
@@ -88,12 +89,10 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
Class inClass = String.class;
Class outClass = String.class;
ServerRequest serverRequest = ServerRequest.create(exchange,
messageReaders);
ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
// 解密生成新的报文
Mono<?> modifiedBody = serverRequest.bodyToMono(inClass)
.flatMap(decryptAES());
Mono<?> modifiedBody = serverRequest.bodyToMono(inClass).flatMap(decryptAES());
BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, outClass);
HttpHeaders headers = new HttpHeaders();
@@ -101,41 +100,35 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
headers.remove(HttpHeaders.CONTENT_LENGTH);
headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
exchange, headers);
return bodyInserter.insert(outputMessage, new BodyInserterContext())
.then(Mono.defer(() -> {
ServerHttpRequest decorator = decorate(exchange, headers,
outputMessage);
return chain
.filter(exchange.mutate().request(decorator).build());
}));
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);
return bodyInserter.insert(outputMessage, new BodyInserterContext()).then(Mono.defer(() -> {
ServerHttpRequest decorator = decorate(exchange, headers, outputMessage);
return chain.filter(exchange.mutate().request(decorator).build());
}));
};
}
/**
* 原文解密
*
* @return
*/
private Function decryptAES() {
return s -> {
// 构建前端对应解密AES 因子
AES aes = new AES(Mode.CBC, Padding.NoPadding,
new SecretKeySpec(encodeKey.getBytes(), KEY_ALGORITHM),
AES aes = new AES(Mode.CBC, Padding.NoPadding, new SecretKeySpec(encodeKey.getBytes(), KEY_ALGORITHM),
new IvParameterSpec(encodeKey.getBytes()));
// 获取请求密码并解密
Map<String, String> inParamsMap = HttpUtil.decodeParamMap((String) s, CharsetUtil.CHARSET_UTF_8);
if(inParamsMap.containsKey(PASSWORD)){
byte[] result = aes.decrypt(Base64.decode(inParamsMap.get(PASSWORD)
.getBytes(StandardCharsets.UTF_8)));
if (inParamsMap.containsKey(PASSWORD)) {
byte[] result = aes.decrypt(Base64.decode(inParamsMap.get(PASSWORD).getBytes(StandardCharsets.UTF_8)));
String password = new String(result, StandardCharsets.UTF_8);
// 返回修改后报文字符
inParamsMap.put(PASSWORD, password.trim());
} else {
log.error("非法请求数据:{}",s);
}
else {
log.error("非法请求数据:{}", s);
}
return Mono.just(HttpUtil.toParams(inParamsMap));
};
@@ -143,11 +136,10 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
/**
* 报文转换
*
* @return
*/
private ServerHttpRequestDecorator decorate(ServerWebExchange exchange, HttpHeaders headers,
CachedBodyOutputMessage outputMessage) {
CachedBodyOutputMessage outputMessage) {
return new ServerHttpRequestDecorator(exchange.getRequest()) {
@Override
public HttpHeaders getHeaders() {
@@ -156,7 +148,8 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
httpHeaders.putAll(super.getHeaders());
if (contentLength > 0) {
httpHeaders.setContentLength(contentLength);
} else {
}
else {
httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
}
return httpHeaders;
@@ -168,4 +161,5 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
}
};
}
}
@@ -39,46 +39,40 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.a
* <p>
* 全局拦截器,作用所有的微服务
* <p>
* 1. 对请求头中参数进行处理 from 参数进行清洗
* 2. 重写StripPrefix = 1,支持全局
* 1. 对请求头中参数进行处理 from 参数进行清洗 2. 重写StripPrefix = 1,支持全局
* <p>
* 支持swagger添加X-Forwarded-Prefix header (F SR2 已经支持,不需要自己维护)
* 支持swagger添加X-Forwarded-Prefix header (F SR2 已经支持,不需要自己维护)
*/
@Component
public class PigxRequestGlobalFilter implements GlobalFilter, Ordered {
/**
* Process the Web request and (optionally) delegate to the next
* {@code WebFilter} through the given {@link GatewayFilterChain}.
*
* Process the Web request and (optionally) delegate to the next {@code WebFilter}
* through the given {@link GatewayFilterChain}.
* @param exchange the current server exchange
* @param chain provides a way to delegate to the next filter
* @param chain provides a way to delegate to the next filter
* @return {@code Mono<Void>} to indicate when request processing is complete
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. 清洗请求头中from 参数
ServerHttpRequest request = exchange.getRequest().mutate()
.headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM))
.build();
.headers(httpHeaders -> httpHeaders.remove(SecurityConstants.FROM)).build();
// 2. 重写StripPrefix
addOriginalRequestUrl(exchange, request.getURI());
String rawPath = request.getURI().getRawPath();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/"))
.skip(1L).collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate()
.path(newPath)
.build();
String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/")).skip(1L)
.collect(Collectors.joining("/"));
ServerHttpRequest newRequest = request.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate()
.request(newRequest.mutate()
.build()).build());
return chain.filter(exchange.mutate().request(newRequest.mutate().build()).build());
}
@Override
public int getOrder() {
return -1000;
}
}
@@ -29,14 +29,13 @@ import org.springframework.stereotype.Component;
/**
* @author lengleng
* @date 2018/8/21
* 演示环境过滤处理
* @date 2018/8/21 演示环境过滤处理
*/
@Slf4j
@Component
public class PreviewGatewayFilter extends AbstractGatewayFilterFactory {
private static final String TOKEN = "token";
private static final String TOKEN = "token";
@Override
public GatewayFilter apply(Object config) {
@@ -44,8 +43,8 @@ public class PreviewGatewayFilter extends AbstractGatewayFilterFactory {
ServerHttpRequest request = exchange.getRequest();
// GET,直接向下执行
if (StrUtil.equalsIgnoreCase(request.getMethodValue(), HttpMethod.GET.name()) ||
StrUtil.containsIgnoreCase(request.getURI().getPath(), TOKEN)) {
if (StrUtil.equalsIgnoreCase(request.getMethodValue(), HttpMethod.GET.name())
|| StrUtil.containsIgnoreCase(request.getURI().getPath(), TOKEN)) {
return chain.filter(exchange);
}
@@ -55,4 +54,5 @@ public class PreviewGatewayFilter extends AbstractGatewayFilterFactory {
return response.setComplete();
};
}
}
@@ -48,15 +48,17 @@ import reactor.core.publisher.Mono;
/**
* @author lengleng
* @date 2020/5/19
* 登录逻辑验证码处理
* @date 2020/5/19 登录逻辑验证码处理
*/
@Slf4j
@Component
@AllArgsConstructor
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
private final ObjectMapper objectMapper;
private final RedisTemplate redisTemplate;
private final FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;
@Override
@@ -65,9 +67,8 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
ServerHttpRequest request = exchange.getRequest();
// 不是登录请求,直接向下执行
if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath()
, SecurityConstants.OAUTH_TOKEN_URL, SecurityConstants.SMS_TOKEN_URL
, SecurityConstants.SOCIAL_TOKEN_URL)) {
if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath(), SecurityConstants.OAUTH_TOKEN_URL,
SecurityConstants.SMS_TOKEN_URL, SecurityConstants.SOCIAL_TOKEN_URL)) {
return chain.filter(exchange);
}
@@ -90,22 +91,24 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
String mobile = request.getQueryParams().getFirst("mobile");
if (StrUtil.containsAny(mobile, LoginTypeEnum.SMS.getType())) {
throw new ValidateCodeException("验证码不合法");
} else {
}
else {
return chain.filter(exchange);
}
}
//校验验证码
// 校验验证码
checkCode(request);
} catch (Exception e) {
}
catch (Exception e) {
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
try {
return response.writeWith(Mono.just(response.bufferFactory()
.wrap(objectMapper.writeValueAsBytes(
R.failed(e.getMessage())))));
} catch (JsonProcessingException e1) {
return response.writeWith(Mono.just(
response.bufferFactory().wrap(objectMapper.writeValueAsBytes(R.failed(e.getMessage())))));
}
catch (JsonProcessingException e1) {
log.error("对象输出异常", e1);
}
}
@@ -116,7 +119,6 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
/**
* 检查code
*
* @param request
*/
@SneakyThrows
@@ -141,7 +143,7 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
return;
}
//https://gitee.com/log4j/pig/issues/IWA0D
// https://gitee.com/log4j/pig/issues/IWA0D
String mobile = request.getQueryParams().getFirst("mobile");
if (StrUtil.isNotBlank(mobile)) {
randomStr = mobile;
@@ -173,4 +175,5 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
redisTemplate.delete(key);
}
}
@@ -38,15 +38,14 @@ import reactor.core.publisher.Mono;
/**
* @author lengleng
* @date 2020/5/19
* 验证码生成逻辑处理类
* @date 2020/5/19 验证码生成逻辑处理类
*/
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeCheckHandler implements HandlerFunction<ServerResponse> {
private final ObjectMapper objectMapper;
private final ObjectMapper objectMapper;
@Override
@SneakyThrows
@@ -59,8 +58,8 @@ public class ImageCodeCheckHandler implements HandlerFunction<ServerResponse> {
CaptchaService captchaService = SpringContextHolder.getBean(CaptchaService.class);
ResponseModel responseModel = captchaService.check(vo);
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(objectMapper.writeValueAsString(R.ok(responseModel))));
}
}
@@ -38,15 +38,14 @@ import reactor.core.publisher.Mono;
/**
* @author lengleng
* @date 2020/5/19
* 验证码生成逻辑处理类
* @date 2020/5/19 验证码生成逻辑处理类
*/
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeCreateHandler implements HandlerFunction<ServerResponse> {
private final ObjectMapper objectMapper;
private final ObjectMapper objectMapper;
@Override
@SneakyThrows
@@ -56,8 +55,8 @@ public class ImageCodeCreateHandler implements HandlerFunction<ServerResponse> {
CaptchaService captchaService = SpringContextHolder.getBean(CaptchaService.class);
ResponseModel responseModel = captchaService.get(vo);
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(objectMapper.writeValueAsString(R.ok(responseModel))));
}
}
@@ -31,25 +31,24 @@ import springfox.documentation.swagger.web.SwaggerResourcesProvider;
/**
* @author lengleng
* @date 2018-07-19
* SwaggerResourceHandler
* @date 2018-07-19 SwaggerResourceHandler
*/
@Slf4j
@Component
@AllArgsConstructor
public class SwaggerResourceHandler implements HandlerFunction<ServerResponse> {
private final SwaggerResourcesProvider swaggerResources;
/**
* Handle the given request.
*
* @param request the request to handler
* @return the response
*/
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(swaggerResources.get()));
return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(swaggerResources.get()));
}
}
@@ -34,27 +34,25 @@ import java.util.Optional;
/**
* @author lengleng
* @date 2018-07-19
* SwaggerSecurityHandler
* @date 2018-07-19 SwaggerSecurityHandler
*/
@Slf4j
@Component
public class SwaggerSecurityHandler implements HandlerFunction<ServerResponse> {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
/**
* Handle the given request.
*
* @param request the request to handler
* @return the response
*/
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(
Optional.ofNullable(securityConfiguration)
.orElse(SecurityConfigurationBuilder.builder().build())));
return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(Optional.ofNullable(securityConfiguration)
.orElse(SecurityConfigurationBuilder.builder().build())));
}
}
@@ -34,27 +34,24 @@ import java.util.Optional;
/**
* @author lengleng
* @date 2018-07-19
* SwaggerUiHandler
* @date 2018-07-19 SwaggerUiHandler
*/
@Slf4j
@Component
public class SwaggerUiHandler implements HandlerFunction<ServerResponse> {
@Autowired(required = false)
private UiConfiguration uiConfiguration;
/**
* Handle the given request.
*
* @param request the request to handler
* @return the response
*/
@Override
public Mono<ServerResponse> handle(ServerRequest request) {
return ServerResponse.status(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(
Optional.ofNullable(uiConfiguration)
.orElse(UiConfigurationBuilder.builder().build())));
return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(BodyInserters
.fromValue(Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build())));
}
}