增加sonar测试并修复sonar测试的问题

This commit is contained in:
zlt
2019-02-04 14:18:47 +08:00
parent e16d8f5d02
commit 110bdc5a84
58 changed files with 181 additions and 233 deletions
@@ -30,9 +30,7 @@ public class DefaultSecurityHandlerConfig {
*/
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
return (request, response, authException) -> {
ResponseUtil.responseWriter(objectMapper, response, authException.getMessage(), HttpStatus.UNAUTHORIZED.value());
};
return (request, response, authException) -> ResponseUtil.responseWriter(objectMapper, response, authException.getMessage(), HttpStatus.UNAUTHORIZED.value());
}
@Bean
@@ -140,7 +140,7 @@ public class RedisTemplateTokenStore implements TokenStore {
ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
Date expiration = expiringRefreshToken.getExpiration();
if (expiration != null) {
int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue();
int seconds = (int)((expiration.getTime() - System.currentTimeMillis()) / 1000L);
redisTemplate.expire(REFRESH_TO_ACCESS + token.getRefreshToken().getValue(), seconds, TimeUnit.SECONDS);
redisTemplate.expire(ACCESS_TO_REFRESH + token.getValue(), seconds, TimeUnit.SECONDS);
@@ -221,24 +221,20 @@ public class RedisTemplateTokenStore implements TokenStore {
@Override
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
List<Object> result = redisTemplate.opsForList().range(UNAME_TO_ACCESS + getApprovalKey(clientId, userName), 0, -1);
if (result == null || result.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
return getTokenColl(result);
}
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
List<Object> result = redisTemplate.opsForList().range((CLIENT_ID_TO_ACCESS + clientId), 0, -1);
if (result == null || result.size() == 0) {
return getTokenColl(result);
}
private Collection<OAuth2AccessToken> getTokenColl(List<Object> result) {
if (result == null || result.isEmpty()) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>(result.size());
List<OAuth2AccessToken> accessTokens = new ArrayList<>(result.size());
for (Iterator<Object> it = result.iterator(); it.hasNext(); ) {
OAuth2AccessToken accessToken = (OAuth2AccessToken) it.next();
accessTokens.add(accessToken);
@@ -50,8 +50,8 @@ public class ResJwtTokenStore {
* @return 公钥 Key
*/
private String getPubKey() {
Resource resource = new ClassPathResource(ResJwtTokenStore.PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
Resource res = new ClassPathResource(ResJwtTokenStore.PUBLIC_KEY);
try (BufferedReader br = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
return br.lines().collect(Collectors.joining("\n"));
} catch (IOException ioe) {
return getKeyFromAuthorizationServer();
@@ -7,6 +7,7 @@ import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAut
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Enumeration;
@@ -18,6 +19,10 @@ import java.util.Enumeration;
*/
@Slf4j
public class AuthUtils {
private AuthUtils() {
throw new IllegalStateException("Utility class");
}
private static final String BASIC_ = "Basic ";
/**
@@ -60,7 +65,7 @@ public class AuthUtils {
/**
* *从header 请求中的clientId:clientSecret
*/
public static String[] extractClient(HttpServletRequest request) throws IOException, UnapprovedClientAuthenticationException {
public static String[] extractClient(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith(BASIC_)) {
throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
@@ -73,10 +78,10 @@ public class AuthUtils {
*
* @param header header中的参数
*/
public static String[] extractHeaderClient(String header) throws IOException {
byte[] base64Client = header.substring(BASIC_.length()).getBytes(CommonConstant.UTF8);
public static String[] extractHeaderClient(String header) {
byte[] base64Client = header.substring(BASIC_.length()).getBytes(StandardCharsets.UTF_8);
byte[] decoded = Base64.getDecoder().decode(base64Client);
String clientStr = new String(decoded, CommonConstant.UTF8);
String clientStr = new String(decoded, StandardCharsets.UTF_8);
String[] clientArr = clientStr.split(":");
if (clientArr.length != 2) {
throw new RuntimeException("Invalid basic authentication token");
@@ -72,11 +72,6 @@ public interface CommonConstant {
*/
String DEL_FLAG = "is_del";
/**
* 编码
*/
String UTF8 = "UTF-8";
/**
* 超级管理员用户名
*/
@@ -15,8 +15,4 @@ public enum CodeEnum {
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
@@ -33,9 +33,7 @@ public class LoginAppUser extends SysUser implements SocialUserDetails {
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> collection = new HashSet<>();
if (!CollectionUtils.isEmpty(super.getRoles())) {
super.getRoles().parallelStream().forEach(role -> {
collection.add(new SimpleGrantedAuthority(role.getCode()));
});
super.getRoles().parallelStream().forEach(role -> collection.add(new SimpleGrantedAuthority(role.getCode())));
}
return collection;
}
@@ -27,7 +27,7 @@ public class Result<T> implements Serializable {
}
public static <T> Result<T> succeedWith(T datas, Integer code, String msg) {
return new Result<T>(datas, code, msg);
return new Result<>(datas, code, msg);
}
public static <T> Result<T> failed(String msg) {
@@ -39,7 +39,7 @@ public class Result<T> implements Serializable {
}
public static <T> Result<T> failedWith(T datas, Integer code, String msg) {
return new Result<T>(datas, code, msg);
return new Result<>(datas, code, msg);
}
}
@@ -9,6 +9,10 @@ import java.util.Date;
* @author zlt
*/
public class DateUtils {
private DateUtils() {
throw new IllegalStateException("Utility class");
}
/** 时间格式(yyyy-MM-dd) */
public final static String DATE_PATTERN = "yyyy-MM-dd";
/** 时间格式(yyyy-MM-dd HH:mm:ss) */
@@ -13,6 +13,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -23,6 +24,10 @@ import java.util.Map;
* @date 2019/1/6
*/
public class ExcelUtil {
private ExcelUtil() {
throw new IllegalStateException("Utility class");
}
/**
* 导出
*
@@ -95,23 +100,21 @@ public class ExcelUtil {
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
if (StringUtils.isBlank(filePath)) {
return null;
return Collections.emptyList();
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
return list;
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
if (file == null) {
return null;
return Collections.emptyList();
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
return list;
return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}
}
@@ -8,6 +8,10 @@ import java.util.regex.Pattern;
* 正则表达式手机号码校验类
*/
public class PhoneUtil {
private PhoneUtil() {
throw new IllegalStateException("Utility class");
}
private static String REGEX = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
private static Pattern P = Pattern.compile(REGEX);
@@ -14,6 +14,9 @@ import java.util.Map;
* @date 2018/12/20
*/
public class ResponseUtil {
private ResponseUtil() {
throw new IllegalStateException("Utility class");
}
/**
* 通过流写到前端
*
@@ -1,6 +1,5 @@
package com.central.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
@@ -28,7 +27,7 @@ public class SpringUtil implements ApplicationContextAware {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext) {
SpringUtil.applicationContext = applicationContext;
}
}
@@ -1,25 +1,21 @@
package com.central.common.utils;
import cn.hutool.core.bean.BeanUtil;
import com.central.common.model.SysRole;
import com.central.common.model.SysUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import com.central.common.model.LoginAppUser;
import java.util.*;
/**
* 获取用户信息
*
* @author zlt
*/
public class SysUserUtil {
private SysUserUtil() {
throw new IllegalStateException("Utility class");
}
public static LoginAppUser getLoginAppUser(SysUser user) {
LoginAppUser login = new LoginAppUser();
BeanUtil.copyProperties(user, login);
@@ -14,6 +14,10 @@ import java.util.UUID;
* @date 2017-3-28 下午1:11:31
*/
public class UUIDUtil {
private UUIDUtil() {
throw new IllegalStateException("Utility class");
}
private static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
@@ -27,7 +31,7 @@ public class UUIDUtil {
* @author wangfan
*/
public static String randomUUID8() {
StringBuffer shortBuffer = new StringBuffer();
StringBuilder shortBuffer = new StringBuilder();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 8; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
@@ -43,8 +47,7 @@ public class UUIDUtil {
* @author wangfan
*/
public static String randomUUID32(){
String uuid = UUID.randomUUID().toString().replace("-", "");
return uuid;
return UUID.randomUUID().toString().replace("-", "");
}
}
@@ -12,21 +12,23 @@ import java.util.Date;
* @date 2018/12/11
*/
public class DateMetaObjectHandler implements MetaObjectHandler {
private final static String UPDATE_TIME = "updateTime";
private final static String CREATE_TIME = "createTime";
/**
* 插入填充,字段为空自动填充
*/
@Override
public void insertFill(MetaObject metaObject) {
Object createTime = getFieldValByName("createTime", metaObject);
Object updateTime = getFieldValByName("updateTime", metaObject);
Object createTime = getFieldValByName(CREATE_TIME, metaObject);
Object updateTime = getFieldValByName(UPDATE_TIME, metaObject);
if (createTime == null || updateTime == null) {
Date date = new Date();
if (createTime == null) {
setFieldValByName("createTime", date, metaObject);
setFieldValByName(CREATE_TIME, date, metaObject);
}
if (updateTime == null) {
setFieldValByName("updateTime", date, metaObject);
setFieldValByName(UPDATE_TIME, date, metaObject);
}
}
}
@@ -39,6 +41,6 @@ public class DateMetaObjectHandler implements MetaObjectHandler {
@Override
public void updateFill(MetaObject metaObject) {
//mybatis-plus版本2.0.9+
setFieldValByName("updateTime", new Date(), metaObject);
setFieldValByName(UPDATE_TIME, new Date(), metaObject);
}
}
@@ -28,7 +28,6 @@ public class DefaultMybatisPlusConfig {
@Bean
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
return performanceInterceptor;
return new PerformanceInterceptor();
}
}
@@ -9,6 +9,10 @@ import lombok.extern.slf4j.Slf4j;
*/
@Slf4j
public class PointUtil {
private PointUtil() {
throw new IllegalStateException("Utility class");
}
public static final String SPLIT = "|";
/**
@@ -101,11 +101,10 @@ public class RedisAutoConfigure {
}
private RedisCacheConfiguration getDefConf() {
RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
return RedisCacheConfiguration.defaultCacheConfig()
.disableCachingNullValues()
.computePrefixWith(cacheName -> "cache".concat(":").concat(cacheName).concat(":"))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new RedisObjectSerializer()));
return cacheConfiguration;
}
}
@@ -7,7 +7,9 @@ package com.central.common.redis.constant;
* @date 2018/5/21 11:59
*/
public class RedisToolsConstant {
private RedisToolsConstant() {
throw new IllegalStateException("Utility class");
}
/**
* single Redis
*/
@@ -56,7 +56,8 @@ public class RedisDistributedLock extends AbstractDistributedLock {
log.debug("get redisDistributeLock failed, retrying..." + retryTimes);
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
return false;
log.warn("Interrupted!", e);
Thread.currentThread().interrupt();
}
result = setRedis(key, expire);
}
@@ -14,6 +14,7 @@ import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
@@ -27,7 +28,7 @@ public class RedisRepository {
/**
* 默认编码
*/
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* key序列化
@@ -12,22 +12,26 @@ import org.springframework.data.redis.serializer.SerializationException;
* @author zlt
*/
public class RedisObjectSerializer implements RedisSerializer<Object> {
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // 做一个空数组,不是null
// 做一个空数组,不是null
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
// 为了方便进行对象与字节数组的转换,所以应该首先准备出两个转换器
private Converter<Object, byte[]> serializingConverter = new SerializingConverter();
private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();
@Override
public byte[] serialize(Object obj) throws SerializationException {
if (obj == null) { // 这个时候没有要序列化的对象出现,所以返回的字节数组应该就是一个空数组
public byte[] serialize(Object obj) {
// 这个时候没有要序列化的对象出现,所以返回的字节数组应该就是一个空数组
if (obj == null) {
return EMPTY_BYTE_ARRAY;
}
return this.serializingConverter.convert(obj); // 将对象变为字节数组
// 将对象变为字节数组
return this.serializingConverter.convert(obj);
}
@Override
public Object deserialize(byte[] data) throws SerializationException {
if (data == null || data.length == 0) { // 此时没有对象的内容信息
public Object deserialize(byte[] data) {
// 此时没有对象的内容信息
if (data == null || data.length == 0) {
return null;
}
return this.deserializingConverter.convert(data);
@@ -41,6 +41,7 @@ import java.util.stream.Collectors;
Swagger2Configuration.class
})
public class SwaggerAutoConfiguration implements BeanFactoryAware {
private static final String AUTH_KEY = "Authorization";
private BeanFactory beanFactory;
@@ -179,7 +180,7 @@ public class SwaggerAutoConfiguration implements BeanFactoryAware {
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@@ -198,13 +199,13 @@ public class SwaggerAutoConfiguration implements BeanFactoryAware {
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> references = new ArrayList<>(1);
references.add(new SecurityReference("Authorization", authorizationScopes));
references.add(new SecurityReference(AUTH_KEY, authorizationScopes));
return references;
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>(1);
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
ApiKey apiKey = new ApiKey(AUTH_KEY, AUTH_KEY, "header");
apiKeys.add(apiKey);
return apiKeys;
}
@@ -1,6 +1,8 @@
package com.central.common.swagger2;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
@@ -51,7 +53,8 @@ public class SwaggerProperties {
/**全局参数配置**/
private List<GlobalOperationParameter> globalOperationParameters;
@Setter
@Getter
public static class GlobalOperationParameter{
/**参数名**/
private String name;
@@ -67,46 +70,6 @@ public class SwaggerProperties {
/**参数是否必须传**/
private String required;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getModelRef() {
return modelRef;
}
public void setModelRef(String modelRef) {
this.modelRef = modelRef;
}
public String getParameterType() {
return parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public String getRequired() {
return required;
}
public void setRequired(String required) {
this.required = required;
}
}
@Data
@@ -139,7 +102,6 @@ public class SwaggerProperties {
@Data
public static class Contact {
/**联系人**/
private String name = "";
/**联系人url**/