♻️ Refactoring code. @SneakyThrows

This commit is contained in:
冷冷 committed 2019-01-19 22:35:17 +08:00
1 parent f80d6d51e4
commit 271fefcdfc
37 files changed
+206 -171

No files matched your search

@@ -26,6 +26,7 @@ import com.pig4cloud.pigx.common.security.service.PigxClientDetailsService;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
@@ -62,7 +63,8 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
private final RedisConnectionFactory redisConnectionFactory;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
@SneakyThrows
public void configure(ClientDetailsServiceConfigurer clients) {
PigxClientDetailsService clientDetailsService = new PigxClientDetailsService(dataSource);
clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.security.handler.MobileLoginSuccessHandler;
import com.pig4cloud.pigx.common.security.mobile.MobileSecurityConfigurer;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -59,7 +60,8 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices;
@Override
protected void configure(HttpSecurity http) throws Exception {
@SneakyThrows
protected void configure(HttpSecurity http) {
http
.formLogin()
.loginPage("/token/login")
@@ -87,7 +89,8 @@ public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
@SneakyThrows
public AuthenticationManager authenticationManagerBean() {
return super.authenticationManagerBean();
}
@@ -95,7 +95,7 @@ public class SpringContextHolder implements ApplicationContextAware, DisposableB
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
public void destroy() {
SpringContextHolder.clearHolder();
}
@@ -23,6 +23,7 @@ import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import com.pig4cloud.pigx.common.core.exception.CheckedException;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
@@ -204,7 +205,8 @@ public class WebUtils extends org.springframework.web.util.WebUtils {
*
* @return
*/
public String[] getClientId(ServerHttpRequest request) throws Exception {
@SneakyThrows
public String[] getClientId(ServerHttpRequest request) {
String header = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (header == null || !header.startsWith(BASIC_)) {
@@ -29,6 +29,7 @@ import com.pig4cloud.pigx.common.data.enums.DataScopeTypeEnum;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
@@ -58,7 +59,8 @@ public class DataScopeInterceptor extends AbstractSqlParserHandler implements In
private final DataSource dataSource;
@Override
public Object intercept(Invocation invocation) throws Throwable {
@SneakyThrows
public Object intercept(Invocation invocation) {
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
this.sqlParser(metaObject);
@@ -19,6 +19,7 @@ package com.pig4cloud.pigx.common.data.tenant;
import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
@@ -26,12 +27,10 @@ import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author lengleng
@@ -43,7 +42,8 @@ import java.io.IOException;
public class TenantContextHolderFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
@SneakyThrows
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
@@ -31,8 +31,8 @@ import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.pig4cloud.pigx.common.job.properties.ElasticJobProperties;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
@@ -59,7 +59,8 @@ public abstract class AbstractJobInitialization implements ApplicationContextAwa
protected ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
@SneakyThrows
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@@ -166,13 +167,13 @@ public abstract class AbstractJobInitialization implements ApplicationContextAwa
private LiteJobConfiguration getLiteJobConfiguration(JobTypeConfiguration jobTypeConfiguration, ElasticJobProperties.JobConfiguration jobConfiguration) {
//构建Lite作业
return LiteJobConfiguration.newBuilder(Objects.requireNonNull(jobTypeConfiguration))
.monitorExecution(jobConfiguration.isMonitorExecution())
.monitorPort(jobConfiguration.getMonitorPort())
.maxTimeDiffSeconds(jobConfiguration.getMaxTimeDiffSeconds())
.jobShardingStrategyClass(jobConfiguration.getJobShardingStrategyClass())
.reconcileIntervalMinutes(jobConfiguration.getReconcileIntervalMinutes())
.disabled(jobConfiguration.isDisabled())
.overwrite(jobConfiguration.isOverwrite()).build();
.monitorExecution(jobConfiguration.isMonitorExecution())
.monitorPort(jobConfiguration.getMonitorPort())
.maxTimeDiffSeconds(jobConfiguration.getMaxTimeDiffSeconds())
.jobShardingStrategyClass(jobConfiguration.getJobShardingStrategyClass())
.reconcileIntervalMinutes(jobConfiguration.getReconcileIntervalMinutes())
.disabled(jobConfiguration.isDisabled())
.overwrite(jobConfiguration.isOverwrite()).build();
}
/**
@@ -184,11 +185,11 @@ public abstract class AbstractJobInitialization implements ApplicationContextAwa
*/
protected JobCoreConfiguration getJobCoreConfiguration(String jobName, ElasticJobProperties.JobConfiguration jobConfiguration) {
JobCoreConfiguration.Builder builder = JobCoreConfiguration.newBuilder(jobName, jobConfiguration.getCron(), jobConfiguration.getShardingTotalCount())
.shardingItemParameters(jobConfiguration.getShardingItemParameters())
.jobParameter(jobConfiguration.getJobParameter())
.failover(jobConfiguration.isFailover())
.misfire(jobConfiguration.isMisfire())
.description(jobConfiguration.getDescription());
.shardingItemParameters(jobConfiguration.getShardingItemParameters())
.jobParameter(jobConfiguration.getJobParameter())
.failover(jobConfiguration.isFailover())
.misfire(jobConfiguration.isMisfire())
.description(jobConfiguration.getDescription());
if (StringUtils.isNotBlank(jobConfiguration.getJobExceptionHandler())) {
builder.jobProperties(JobPropertiesEnum.JOB_EXCEPTION_HANDLER.getKey(), jobConfiguration.getJobExceptionHandler());
}
@@ -220,7 +221,7 @@ public abstract class AbstractJobInitialization implements ApplicationContextAwa
//注册分布式监听者
AbstractDistributeOnceElasticJobListener distributedListener = registerBean(listener.getDistributedListenerClass(), listener.getDistributedListenerClass(),
AbstractDistributeOnceElasticJobListener.class, listener.getStartedTimeoutMilliseconds(), listener.getCompletedTimeoutMilliseconds());
AbstractDistributeOnceElasticJobListener.class, listener.getStartedTimeoutMilliseconds(), listener.getCompletedTimeoutMilliseconds());
if (null != distributedListener) {
elasticJobListeners.add(distributedListener);
}
@@ -23,6 +23,7 @@ import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.log.event.SysLogEvent;
import com.pig4cloud.pigx.common.log.util.SysLogUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -40,8 +41,9 @@ import org.springframework.context.ApplicationEventPublisher;
public class SysLogAspect {
private final ApplicationEventPublisher publisher;
@SneakyThrows
@Around("@annotation(sysLog)")
public Object around(ProceedingJoinPoint point, SysLog sysLog) throws Throwable {
public Object around(ProceedingJoinPoint point, SysLog sysLog) {
String strClassName = point.getTarget().getClass().getName();
String strMethodName = point.getSignature().getName();
log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);
@@ -22,6 +22,7 @@ import com.pig4cloud.common.minio.vo.MinioItem;
import com.pig4cloud.common.minio.vo.MinioObject;
import io.minio.messages.Bucket;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@@ -48,60 +49,65 @@ public class MinioEndpoint {
/**
* Bucket Endpoints
*/
@SneakyThrows
@PostMapping("/bucket/{bucketName}")
public Bucket createBucker(@PathVariable String bucketName) throws Exception {
public Bucket createBucker(@PathVariable String bucketName) {
template.createBucket(bucketName);
return template.getBucket(bucketName).get();
}
@SneakyThrows
@GetMapping("/bucket")
public List<Bucket> getBuckets() throws Exception {
public List<Bucket> getBuckets() {
return template.getAllBuckets();
}
@SneakyThrows
@GetMapping("/bucket/{bucketName}")
public Bucket getBucket(@PathVariable String bucketName) throws Exception {
public Bucket getBucket(@PathVariable String bucketName) {
return template.getBucket(bucketName).orElseThrow(() -> new IllegalArgumentException("Bucket Name not found!"));
}
@SneakyThrows
@DeleteMapping("/bucket/{bucketName}")
@ResponseStatus(HttpStatus.ACCEPTED)
public void deleteBucket(@PathVariable String bucketName) throws Exception {
public void deleteBucket(@PathVariable String bucketName) {
template.removeBucket(bucketName);
}
/**
* Object Endpoints
*/
@SneakyThrows
@PostMapping("/object/{bucketName}")
public MinioObject createObject(@RequestBody MultipartFile object, @PathVariable String bucketName) throws Exception {
public MinioObject createObject(@RequestBody MultipartFile object, @PathVariable String bucketName) {
String name = object.getOriginalFilename();
template.putObject(bucketName, name, object.getInputStream(), object.getSize(), object.getContentType());
return new MinioObject(template.getObjectInfo(bucketName, name));
}
@SneakyThrows
@PostMapping("/object/{bucketName}/{objectName}")
public MinioObject createObject(@RequestBody MultipartFile object, @PathVariable String bucketName, @PathVariable String objectName) throws Exception {
public MinioObject createObject(@RequestBody MultipartFile object, @PathVariable String bucketName, @PathVariable String objectName) {
template.putObject(bucketName, objectName, object.getInputStream(), object.getSize(), object.getContentType());
return new MinioObject(template.getObjectInfo(bucketName, objectName));
}
@SneakyThrows
@GetMapping("/object/{bucketName}/{objectName}")
public List<MinioItem> filterObject(@PathVariable String bucketName, @PathVariable String objectName) throws Exception {
public List<MinioItem> filterObject(@PathVariable String bucketName, @PathVariable String objectName) {
return template.getAllObjectsByPrefix(bucketName, objectName, true);
}
@SneakyThrows
@GetMapping("/object/{bucketName}/{objectName}/{expires}")
public Map<String, Object> getObject(@PathVariable String bucketName, @PathVariable String objectName, @PathVariable Integer expires) throws Exception {
public Map<String, Object> getObject(@PathVariable String bucketName, @PathVariable String objectName, @PathVariable Integer expires) {
Map<String, Object> responseBody = new HashMap<>(8);
// Put Object info
responseBody.put("bucket", bucketName);
@@ -111,9 +117,10 @@ public class MinioEndpoint {
return responseBody;
}
@DeleteMapping("/object/{bucketName}/{objectName}/")
@SneakyThrows
@ResponseStatus(HttpStatus.ACCEPTED)
public void deleteObject(@PathVariable String bucketName, @PathVariable String objectName) throws Exception {
@DeleteMapping("/object/{bucketName}/{objectName}/")
public void deleteObject(@PathVariable String bucketName, @PathVariable String objectName) {
template.removeObject(bucketName, objectName);
}
@@ -24,6 +24,7 @@ import io.minio.Result;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
@@ -48,9 +49,9 @@ public class MinioTemplate implements InitializingBean {
* 创建bucket
*
* @param bucketName bucket名称
* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#makeBucket
*/
public void createBucket(String bucketName) throws Exception {
@SneakyThrows
public void createBucket(String bucketName) {
if (!client.bucketExists(bucketName)) {
client.makeBucket(bucketName);
}
@@ -61,23 +62,24 @@ public class MinioTemplate implements InitializingBean {
* <p>
* https://docs.minio.io/cn/java-client-api-reference.html#listBuckets
*/
public List<Bucket> getAllBuckets() throws Exception {
@SneakyThrows
public List<Bucket> getAllBuckets() {
return client.listBuckets();
}
/**
* @param bucketName bucket名称
* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#listBuckets
*/
public Optional<Bucket> getBucket(String bucketName) throws Exception {
@SneakyThrows
public Optional<Bucket> getBucket(String bucketName) {
return client.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
}
/**
* @param bucketName bucket名称
* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#removeBucket
*/
public void removeBucket(String bucketName) throws Exception {
@SneakyThrows
public void removeBucket(String bucketName) {
client.removeBucket(bucketName);
}
@@ -88,9 +90,9 @@ public class MinioTemplate implements InitializingBean {
* @param prefix 前缀
* @param recursive 是否递归查询
* @return MinioItem 列表
* @throws Exception
*/
public List<MinioItem> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) throws Exception {
@SneakyThrows
public List<MinioItem> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
List<MinioItem> objectList = new ArrayList<>();
Iterable<Result<Item>> objectsIterator = client
.listObjects(bucketName, prefix, recursive);
@@ -108,9 +110,9 @@ public class MinioTemplate implements InitializingBean {
* @param objectName 文件名称
* @param expires 过期时间 <=7
* @return url
* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#getObject
*/
public String getObjectURL(String bucketName, String objectName, Integer expires) throws Exception {
@SneakyThrows
public String getObjectURL(String bucketName, String objectName, Integer expires) {
return client.presignedGetObject(bucketName, objectName, expires);
}
@@ -120,9 +122,9 @@ public class MinioTemplate implements InitializingBean {
* @param bucketName bucket名称
* @param objectName 文件名称
* @return 二进制流
* @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#getObject
*/
public InputStream getObject(String bucketName, String objectName) throws Exception {
@SneakyThrows
public InputStream getObject(String bucketName, String objectName) {
return client.getObject(bucketName, objectName);
}
@@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.security.exception.PigxAuth2Exception;
import lombok.SneakyThrows;
import java.io.IOException;
@@ -37,7 +38,8 @@ public class PigxAuth2ExceptionSerializer extends StdSerializer<PigxAuth2Excepti
}
@Override
public void serialize(PigxAuth2Exception value, JsonGenerator gen, SerializerProvider provider) throws IOException {
@SneakyThrows
public void serialize(PigxAuth2Exception value, JsonGenerator gen, SerializerProvider provider) {
gen.writeStartObject();
gen.writeObjectField("code", CommonConstants.FAIL);
gen.writeStringField("msg", value.getMessage());
@@ -18,6 +18,7 @@
package com.pig4cloud.pigx.common.security.component;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -56,10 +57,10 @@ public class PigxResourceServerConfigurerAdapter extends ResourceServerConfigure
* 默认的配置,对外暴露
*
* @param httpSecurity
* @throws Exception
*/
@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
@SneakyThrows
public void configure(HttpSecurity httpSecurity) {
//允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
httpSecurity.headers().frameOptions().disable();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>
@@ -21,6 +21,7 @@ import cn.hutool.core.util.StrUtil;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -43,8 +44,9 @@ import javax.servlet.http.HttpServletRequest;
public class PigxSecurityInnerAspect {
private final HttpServletRequest request;
@SneakyThrows
@Around("@annotation(inner)")
public Object around(ProceedingJoinPoint point, Inner inner) throws Throwable {
public Object around(ProceedingJoinPoint point, Inner inner) {
String header = request.getHeader(SecurityConstants.FROM);
if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
log.warn("访问接口 {} 没有权限", point.getSignature().getName());
@@ -45,7 +45,7 @@ public class PigxWebResponseExceptionTranslator implements WebResponseExceptionT
private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
@Override
public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
public ResponseEntity<OAuth2Exception> translate(Exception e) {
// Try to extract a SpringSecurityException from the stacktrace
Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
@@ -22,6 +22,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
@@ -46,8 +47,9 @@ public class ResourceAuthExceptionEntryPoint implements AuthenticationEntryPoint
private final ObjectMapper objectMapper;
@Override
@SneakyThrows
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
AuthenticationException authException) {
response.setCharacterEncoding(CommonConstants.UTF8);
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
R<String> result = new R<>();
@@ -20,12 +20,12 @@ package com.pig4cloud.pigx.common.security.mobile;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationEventPublisher;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -62,11 +62,12 @@ public class MobileAuthenticationFilter extends AbstractAuthenticationProcessing
}
@Override
@SneakyThrows
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
HttpServletResponse response) {
if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
@@ -93,11 +94,11 @@ public class MobileAuthenticationFilter extends AbstractAuthenticationProcessing
logger.debug("Authentication request failed: " + failed);
eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
try {
authenticationEntryPoint.commence(request, response,
new UsernameNotFoundException(failed.getMessage(), failed));
new UsernameNotFoundException(failed.getMessage(), failed));
} catch (Exception e) {
logger.error("authenticationEntryPoint handle error:{}", failed);
}
@@ -21,12 +21,12 @@ import com.pig4cloud.pigx.common.security.component.PigxPreAuthenticationChecks;
import com.pig4cloud.pigx.common.security.service.PigxUserDetailsService;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
@@ -47,7 +47,8 @@ public class MobileAuthenticationProvider implements AuthenticationProvider {
private PigxUserDetailsService userDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
@SneakyThrows
public Authentication authenticate(Authentication authentication) {
MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
String principal = mobileAuthenticationToken.getPrincipal().toString();
@@ -17,6 +17,7 @@
package com.pig4cloud.pigx.common.security.mobile;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
@@ -30,46 +31,47 @@ import java.util.Collection;
*/
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
private final Object principal;
public MobileAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public MobileAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public MobileAuthenticationToken(Object principal,
public MobileAuthenticationToken(Object principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
@Override
@SneakyThrows
public void setAuthenticated(boolean isAuthenticated) {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
}
super.setAuthenticated(false);
}
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
}
@@ -18,6 +18,7 @@
package com.pig4cloud.pigx.common.security.service;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.SneakyThrows;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
@@ -45,8 +46,9 @@ public class PigxClientDetailsService extends JdbcClientDetailsService {
* @throws InvalidClientException
*/
@Override
@SneakyThrows
@Cacheable(value = SecurityConstants.CLIENT_DETAILS_KEY, key = "#clientId", unless = "#result == null")
public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
public ClientDetails loadClientByClientId(String clientId) {
return super.loadClientByClientId(clientId);
}
}
@@ -26,6 +26,7 @@ import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
@@ -60,7 +61,8 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService {
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
@SneakyThrows
public UserDetails loadUserByUsername(String username) {
Cache cache = cacheManager.getCache("user_details");
if (cache != null && cache.get(username) != null) {
return (PigxUser) cache.get(username).get();
@@ -81,7 +83,8 @@ public class PigxUserDetailsServiceImpl implements PigxUserDetailsService {
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserBySocial(String inStr) throws UsernameNotFoundException {
@SneakyThrows
public UserDetails loadUserBySocial(String inStr) {
return getUserDetails(remoteUserService.social(inStr, SecurityConstants.FROM_IN));
}
@@ -19,6 +19,7 @@ package com.pig4cloud.pigx.common.security.util;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
@@ -43,8 +44,8 @@ public class AuthUtils {
* @throws RuntimeException if the Basic header is not present or is not valid
* Base64
*/
public String[] extractAndDecodeHeader(String header)
throws IOException {
@SneakyThrows
public String[] extractAndDecodeHeader(String header) {
byte[] base64Token = header.substring(6).getBytes("UTF-8");
byte[] decoded;
@@ -70,10 +71,9 @@ public class AuthUtils {
*
* @param request
* @return
* @throws IOException
*/
public String[] extractAndDecodeHeader(HttpServletRequest request)
throws IOException {
@SneakyThrows
public String[] extractAndDecodeHeader(HttpServletRequest request) {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header == null || !header.startsWith(BASIC_)) {
@@ -18,6 +18,7 @@
package com.pig4cloud.pigx.common.transaction.tx.springcloud.http;
import com.codingapi.tx.aop.bean.TxTransactionLocal;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
@@ -34,8 +35,10 @@ import java.io.IOException;
*/
@Slf4j
public class TransactionHttpRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
@SneakyThrows
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) {
TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();
String groupId = txTransactionLocal == null ? null : txTransactionLocal.getGroupId();
@@ -17,6 +17,7 @@
package com.pig4cloud.pigx.common.transaction.tx.springcloud.interceptor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -41,17 +42,18 @@ public class TransactionAspect implements Ordered {
@Autowired
private TxManagerInterceptor txManagerInterceptor;
@SneakyThrows
@Around("@annotation(com.codingapi.tx.annotation.TxTransaction)")
public Object transactionRunning(ProceedingJoinPoint point) throws Throwable {
public Object transactionRunning(ProceedingJoinPoint point) {
log.debug("annotation-TransactionRunning-start---->");
Object obj = txManagerInterceptor.around(point);
log.debug("annotation-TransactionRunning-end---->");
return obj;
}
@SneakyThrows
@Around("this(com.codingapi.tx.annotation.ITxTransaction) && execution( * *(..))")
public Object around(ProceedingJoinPoint point) throws Throwable {
public Object around(ProceedingJoinPoint point) {
log.debug("interface-ITransactionRunning-start---->");
Object obj = txManagerInterceptor.around(point);
log.debug("interface-ITransactionRunning-end---->");
@@ -18,6 +18,7 @@
package com.pig4cloud.pigx.common.transaction.tx.springcloud.interceptor;
import com.codingapi.tx.aop.service.AspectBeforeService;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -39,7 +40,8 @@ public class TxManagerInterceptor {
@Autowired
private AspectBeforeService aspectBeforeService;
public Object around(ProceedingJoinPoint point) throws Throwable {
@SneakyThrows
public Object around(ProceedingJoinPoint point) {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String groupId = request.getHeader("tx-group");
@@ -22,6 +22,7 @@ package com.pig4cloud.pigx.eureka.security;
* @date 2018/7/12
*/
import lombok.SneakyThrows;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@@ -29,11 +30,12 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
@SneakyThrows
protected void configure(HttpSecurity http) {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/actuator/**").permitAll()
.anyRequest()
.authenticated().and().httpBasic();
.authorizeRequests()
.antMatchers("/actuator/**").permitAll()
.anyRequest()
.authenticated().and().httpBasic();
}
}
@@ -22,6 +22,7 @@ import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
@@ -51,7 +52,8 @@ public class PasswordDecoderFilter extends AbstractGatewayFilterFactory {
@Value("${security.encode.key:1234567812345678}")
private String encodeKey;
private static String decryptAES(String data, String pass) throws Exception {
@SneakyThrows
private static String decryptAES(String data, String pass) {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
SecretKeySpec keyspec = new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM);
IvParameterSpec ivspec = new IvParameterSpec(pass.getBytes());
@@ -27,6 +27,7 @@ import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.core.util.WebUtils;
import com.pig4cloud.pigx.gateway.config.FilterIgnorePropertiesConfig;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
@@ -97,9 +98,9 @@ public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory {
* 检查code
*
* @param request
* @throws ValidateCodeException 校验异常
*/
private void checkCode(ServerHttpRequest request) throws ValidateCodeException {
@SneakyThrows
private void checkCode(ServerHttpRequest request) {
String code = request.getQueryParams().getFirst("code");
if (StrUtil.isBlank(code)) {
@@ -23,6 +23,7 @@ import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.SysGeneratorService;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
@@ -55,13 +56,14 @@ public class SysGeneratorController {
/**
* 生成代码
*/
@SneakyThrows
@PostMapping("/code")
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) throws IOException {
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
byte[] data = sysGeneratorService.generatorCode(genConfig);
response.reset();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
response.setContentType("application/octet-stream; charset=UTF-8");
IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
@@ -25,6 +25,7 @@ import com.pig4cloud.pigx.manager.model.ModelInfo;
import com.pig4cloud.pigx.manager.model.ModelName;
import com.pig4cloud.pigx.manager.model.TxState;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@@ -89,18 +90,21 @@ public class AdminController {
return apiAdminService.modelInfos(path);
}
@SneakyThrows
@RequestMapping(value = "/compensate", method = RequestMethod.GET)
public boolean compensate(@RequestParam("path") String path) throws ServiceException {
public boolean compensate(@RequestParam("path") String path) {
return apiAdminService.compensate(path);
}
@SneakyThrows
@RequestMapping(value = "/delCompensate", method = RequestMethod.GET)
public boolean delCompensate(@RequestParam("path") String path) throws ServiceException {
public boolean delCompensate(@RequestParam("path") String path) {
return apiAdminService.delCompensate(path);
}
@SneakyThrows
@RequestMapping(value = "/hasCompensate", method = RequestMethod.GET)
public boolean hasCompensate() throws ServiceException {
public boolean hasCompensate() {
return apiAdminService.hasCompensate();
}
}
@@ -21,6 +21,7 @@ import com.lorne.core.framework.exception.ServiceException;
import com.pig4cloud.pigx.manager.compensate.model.TxModel;
import com.pig4cloud.pigx.manager.model.ModelName;
import com.pig4cloud.pigx.manager.model.TxState;
import lombok.SneakyThrows;
import java.util.List;
import java.util.Map;
@@ -28,6 +28,7 @@ import com.pig4cloud.pigx.manager.model.ModelName;
import com.pig4cloud.pigx.manager.model.TxState;
import com.pig4cloud.pigx.manager.redis.RedisServerService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@@ -108,7 +109,8 @@ public class ApiAdminServiceImpl implements ApiAdminService {
}
@Override
public boolean compensate(String path) throws ServiceException {
@SneakyThrows
public boolean compensate(String path) {
return compensateService.executeCompensate(path);
}
@@ -36,6 +36,7 @@ import com.pig4cloud.pigx.manager.model.ModelInfo;
import com.pig4cloud.pigx.manager.model.ModelName;
import com.pig4cloud.pigx.manager.netty.model.TxGroup;
import com.pig4cloud.pigx.manager.netty.model.TxInfo;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -309,7 +310,8 @@ public class CompensateServiceImpl implements CompensateService {
@Override
public boolean executeCompensate(String path) throws ServiceException {
@SneakyThrows
public boolean executeCompensate(String path) {
String json = compensateDao.getCompensate(path);
if (json == null) {
@@ -326,8 +328,8 @@ public class CompensateServiceImpl implements CompensateService {
return false;
}
private boolean executeCompensateMethod(String json) throws ServiceException {
@SneakyThrows
private boolean executeCompensateMethod(String json) {
JSONObject jsonObject = JSON.parseObject(json);
String model = jsonObject.getString("model");
@@ -301,19 +301,11 @@ public class TxManagerSenderServiceImpl implements TxManagerSenderService {
private ScheduledFuture schedule(final String key, int delayTime) {
ScheduledFuture future = executorService.schedule(new Runnable() {
@Override
public void run() {
Task task = ConditionUtils.getInstance().getTask(key);
if (task != null && !task.isNotify()) {
task.setBack(new IBack() {
@Override
public Object doing(Object... objs) throws Throwable {
return "-2";
}
});
task.signalTask();
}
ScheduledFuture future = executorService.schedule(() -> {
Task task = ConditionUtils.getInstance().getTask(key);
if (task != null && !task.isNotify()) {
task.setBack(objs -> "-2");
task.signalTask();
}
}, delayTime, TimeUnit.SECONDS);
@@ -64,22 +64,12 @@ public class ChannelSender {
final String res = HttpUtils.post(url, "msg=" + msg + "&model=" + modelName);
if (StringUtils.isNotEmpty(res)) {
if (task != null) {
task.setBack(new IBack() {
@Override
public Object doing(Object... objs) throws Throwable {
return res;
}
});
task.setBack(objs -> res);
task.signalTask();
}
} else {
if (task != null) {
task.setBack(new IBack() {
@Override
public Object doing(Object... objs) throws Throwable {
return "-2";
}
});
task.setBack(objs -> "-2");
task.signalTask();
}
}
@@ -32,6 +32,7 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -62,15 +63,10 @@ public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1)
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
final String json = SocketUtils.getJson(msg);
logger.debug("request->" + json);
threadPool.execute(new Runnable() {
@Override
public void run() {
service(json, ctx);
}
});
threadPool.execute(() -> service(json, ctx));
}
private void service(String json, ChannelHandlerContext ctx) {
@@ -95,7 +91,8 @@ public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1)
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
@SneakyThrows
public void channelRegistered(ChannelHandlerContext ctx) {
//是否到达最大上线连接数
if (SocketManager.getInstance().isAllowConnection()) {
@@ -107,7 +104,8 @@ public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1)
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
@SneakyThrows
public void channelUnregistered(ChannelHandlerContext ctx) {
SocketManager.getInstance().removeClient(ctx.channel());
String modelName = ctx.channel().remoteAddress().toString();
@@ -118,18 +116,18 @@ public class TxCoreServerHandler extends ChannelInboundHandlerAdapter { // (1)
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
//ctx.close();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
//心跳配置
if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
IdleStateEvent event = (IdleStateEvent) evt;
@@ -32,12 +32,7 @@ public class BaseSignalTaskService {
final String data = params.getString("d");
Task task = ConditionUtils.getInstance().getTask(key);
if (task != null) {
task.setBack(new IBack() {
@Override
public Object doing(Object... objs) throws Throwable {
return data;
}
});
task.setBack(objs -> data);
task.signalTask();
}
return res;
@@ -81,7 +81,7 @@ public class NettyServerServiceImpl implements NettyServerService, DisposableBea
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
public void initChannel(SocketChannel ch) {
ch.pipeline().addLast("timeout", new IdleStateHandler(heartTime, heartTime, heartTime, TimeUnit.SECONDS));
ch.pipeline().addLast(new LengthFieldPrepender(4, false));
@@ -113,7 +113,7 @@ public class NettyServerServiceImpl implements NettyServerService, DisposableBea
}
@Override
public void destroy() throws Exception {
public void destroy() {
close();
threadPool.shutdown();
}