Browse Source

fix: sonar问题解决

Marko552 3 years ago
parent
commit
1160970764

+ 1 - 0
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/tablestore/common/TableStoreReq.java

@@ -83,6 +83,7 @@ public class TableStoreReq<T extends TableStoreEntity> {
             field = clzParam.getDeclaredField(fieldName);
         }catch (Exception e){
             log.info("找不到字段",e);
+            throw new BusinessException(404,"字段不存在");
         }
 
         //表名

+ 11 - 6
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/infrastructure/config/CorsConfig.java

@@ -9,22 +9,27 @@ import org.springframework.web.filter.CorsFilter;
 @Configuration
 public class CorsConfig {
 
-    private long maxAge = 30 * 24 * 60 * 60;
+    private long maxAge = 30L * 24 * 60 * 60;
 
     private CorsConfiguration buildConfig() {
         CorsConfiguration corsConfiguration = new CorsConfiguration();
-        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
-        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
-        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
+        // 1 设置访问源地址
+        corsConfiguration.addAllowedOrigin("*");
+        // 2 设置访问源请求头
+        corsConfiguration.addAllowedHeader("*");
+        // 3 设置访问源请求方法
+        corsConfiguration.addAllowedMethod("*");
         corsConfiguration.setMaxAge(maxAge);
-        corsConfiguration.setAllowCredentials(true); //用于 token 跨域
+        //用于 token 跨域
+        corsConfiguration.setAllowCredentials(true);
         return corsConfiguration;
     }
 
     @Bean
     public CorsFilter corsFilter() {
         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
-        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
+        // 4 对接口配置跨域设置
+        source.registerCorsConfiguration("/**", buildConfig());
         return new CorsFilter(source);
     }
 

+ 22 - 6
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/infrastructure/qr/build/parent/RandomBuildCode.java

@@ -1,7 +1,11 @@
 package com.abi.qms.platform.infrastructure.qr.build.parent;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
 import java.util.Random;
 import java.util.UUID;
 
+import static java.security.SecureRandom.getInstanceStrong;
+
 /**
  * 随机数方式-构建码
  *
@@ -10,6 +14,19 @@ import java.util.UUID;
  */
 public abstract class RandomBuildCode extends BuildCode {
 
+    /**
+     * SecureRandom is preferred to Random
+     */
+    private Random rand;
+    {
+        try {
+            rand = getInstanceStrong();
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        }
+    }
+
+
     /**
      * 生成指定位数的随机数字
      * 该方法是通过Math.random()获取[0.0, 1.0)的随机数,再乘以需要的位数。
@@ -21,7 +38,7 @@ public abstract class RandomBuildCode extends BuildCode {
         if (length <= 0) {
             return "0";
         }
-        String randomNum = String.valueOf((long) ((Math.random() * 9 + 1) * (Math.pow(10, length - 1))));
+        String randomNum = String.valueOf((long) ((Math.random() * 9 + 1) * (Math.pow(10, (double)length - 1))));
         return randomNum;
     }
 
@@ -32,16 +49,15 @@ public abstract class RandomBuildCode extends BuildCode {
      */
     public String getRandomStr(int length) {
         StringBuffer randomStr = new StringBuffer();
-        Random random = new Random();        
         for(int i = 0; i < length; i++) {
             // 随机生成数字或字母
-            boolean isChar = random.nextInt(2) % 2 == 0;
+            boolean isChar = rand.nextInt(2) % 2 == 0;
             if(isChar) {
                 // 随机生成大写或小写字母
-                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
-                randomStr.append((char) (random.nextInt(26) + temp));
+                int temp = rand.nextInt(2) % 2 == 0 ? 65 : 97;
+                randomStr.append((char) (rand.nextInt(26) + temp));
             } else {
-                randomStr.append(random.nextInt(10));
+                randomStr.append(rand.nextInt(10));
             }
         }  
         return randomStr.toString();

+ 1 - 1
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/infrastructure/qr/build/parent/TimeBuildCode.java

@@ -40,7 +40,7 @@ public abstract class TimeBuildCode extends BuildCode {
         Stack<Character> stack = new Stack<>();
         StringBuffer result = new StringBuffer();
         while (rest != 0) {
-            stack.add(CHARSET[new Long((rest - (rest / 62) * 62)).intValue()]);
+            stack.add(CHARSET[(int) (rest - (rest / 62) * 62)]);
             rest = rest / 62;
         }
         for (; !stack.isEmpty();) {

+ 0 - 155
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/infrastructure/util/JwtTokenUtils.java

@@ -6,17 +6,10 @@ import com.abi.qms.platform.dao.entity.UserInfo;
 import com.auth0.jwt.JWT;
 import com.auth0.jwt.JWTVerifier;
 import com.auth0.jwt.algorithms.Algorithm;
-import com.auth0.jwt.exceptions.AlgorithmMismatchException;
-import com.auth0.jwt.exceptions.InvalidClaimException;
-import com.auth0.jwt.exceptions.TokenExpiredException;
-import com.auth0.jwt.interfaces.Claim;
-import com.auth0.jwt.interfaces.DecodedJWT;
 import lombok.extern.slf4j.Slf4j;
 
 import java.security.interfaces.RSAPrivateKey;
 import java.security.interfaces.RSAPublicKey;
-import java.util.*;
-
 
 import static com.abi.qms.platform.infrastructure.constant.RsaKey.RSA_PRIVATE_KEY;
 import static com.abi.qms.platform.infrastructure.constant.RsaKey.RSA_PUBLIC_KEY;
@@ -33,9 +26,6 @@ import static com.abi.qms.platform.runner.CustomApplicationRunner.globalRsaKeyMa
 @Slf4j
 public class JwtTokenUtils{
 
-    //默认两个小时过期
-    private Long expired = 7200L;
-
 
     public static Boolean checkToken(String token){
         try{
@@ -49,7 +39,6 @@ public class JwtTokenUtils{
         }
     }
 
-
     /**
      * 根据console端user用户生成token信息
      * @param user
@@ -72,148 +61,4 @@ public class JwtTokenUtils{
             throw new BusinessException(500,"生成token异常");
         }
     }
-
-
-    private static void verifyAlgorithm(DecodedJWT jwt, Algorithm expectedAlgorithm) throws AlgorithmMismatchException {
-        if (!expectedAlgorithm.getName().equals(jwt.getAlgorithm())) {
-            throw new AlgorithmMismatchException("The provided Algorithm doesn't match the one defined in the JWT's Header.");
-        }
-    }
-
-
-    private void verifyClaims(DecodedJWT jwt, Map<String, Object> claims) throws TokenExpiredException, InvalidClaimException {
-        Iterator var3 = claims.entrySet().iterator();
-
-        while(var3.hasNext()) {
-            Map.Entry<String, Object> entry = (Map.Entry)var3.next();
-            String var5 = (String)entry.getKey();
-            byte var6 = -1;
-            switch(var5.hashCode()) {
-                case 96944:
-                    if (var5.equals("aud")) {
-                        var6 = 0;
-                    }
-                    break;
-                case 100893:
-                    if (var5.equals("exp")) {
-                        var6 = 1;
-                    }
-                    break;
-                case 104028:
-                    if (var5.equals("iat")) {
-                        var6 = 2;
-                    }
-                    break;
-                case 104585:
-                    if (var5.equals("iss")) {
-                        var6 = 4;
-                    }
-                    break;
-                case 105567:
-                    if (var5.equals("jti")) {
-                        var6 = 5;
-                    }
-                    break;
-                case 108850:
-                    if (var5.equals("nbf")) {
-                        var6 = 3;
-                    }
-                    break;
-                case 114240:
-                    if (var5.equals("sub")) {
-                        var6 = 6;
-                    }
-            }
-
-            switch(var6) {
-                case 0:
-                    this.assertValidAudienceClaim(jwt.getAudience(), (List)entry.getValue());
-                    break;
-                case 1:
-                    this.assertValidDateClaim(jwt.getExpiresAt(), (Long)entry.getValue(), true);
-                    break;
-                case 2:
-                    this.assertValidDateClaim(jwt.getIssuedAt(), (Long)entry.getValue(), false);
-                    break;
-                case 3:
-                    this.assertValidDateClaim(jwt.getNotBefore(), (Long)entry.getValue(), false);
-                    break;
-                case 4:
-                    this.assertValidStringClaim((String)entry.getKey(), jwt.getIssuer(), (String)entry.getValue());
-                    break;
-                case 5:
-                    this.assertValidStringClaim((String)entry.getKey(), jwt.getId(), (String)entry.getValue());
-                    break;
-                case 6:
-                    this.assertValidStringClaim((String)entry.getKey(), jwt.getSubject(), (String)entry.getValue());
-                    break;
-                default:
-                    this.assertValidClaim(jwt.getClaim((String)entry.getKey()), (String)entry.getKey(), entry.getValue());
-            }
-        }
-
-    }
-
-    private void assertValidClaim(Claim claim, String claimName, Object value) {
-        boolean isValid = false;
-        if (value instanceof String) {
-            isValid = value.equals(claim.asString());
-        } else if (value instanceof Integer) {
-            isValid = value.equals(claim.asInt());
-        } else if (value instanceof Long) {
-            isValid = value.equals(claim.asLong());
-        } else if (value instanceof Boolean) {
-            isValid = value.equals(claim.asBoolean());
-        } else if (value instanceof Double) {
-            isValid = value.equals(claim.asDouble());
-        } else if (value instanceof Date) {
-            isValid = value.equals(claim.asDate());
-        } else if (value instanceof Object[]) {
-            List<Object> claimArr = Arrays.asList((Object[])claim.as(Object[].class));
-            List<Object> valueArr = Arrays.asList((Object[])((Object[])value));
-            isValid = claimArr.containsAll(valueArr);
-        }
-
-        if (!isValid) {
-            throw new InvalidClaimException(String.format("The Claim '%s' value doesn't match the required one.", claimName));
-        }
-    }
-
-    private void assertValidStringClaim(String claimName, String value, String expectedValue) {
-        if (!expectedValue.equals(value)) {
-            throw new InvalidClaimException(String.format("The Claim '%s' value doesn't match the required one.", claimName));
-        }
-    }
-
-    private void assertValidDateClaim(Date date, long leeway, boolean shouldBeFuture) {
-        Date today = new Date();
-        today.setTime((long)Math.floor((double)(today.getTime() / 1000L * 1000L)));
-        if (shouldBeFuture) {
-            this.assertDateIsFuture(date, leeway, today);
-        } else {
-            this.assertDateIsPast(date, leeway, today);
-        }
-
-    }
-
-    private void assertDateIsFuture(Date date, long leeway, Date today) {
-        today.setTime(today.getTime() - leeway * 1000L);
-        if (date != null && today.after(date)) {
-            throw new TokenExpiredException(String.format("The Token has expired on %s.", date));
-        }
-    }
-
-    private void assertDateIsPast(Date date, long leeway, Date today) {
-        today.setTime(today.getTime() + leeway * 1000L);
-        if (date != null && today.before(date)) {
-            throw new InvalidClaimException(String.format("The Token can't be used before %s.", date));
-        }
-    }
-
-    private void assertValidAudienceClaim(List<String> audience, List<String> value) {
-        if (audience == null || !audience.containsAll(value)) {
-            throw new InvalidClaimException("The Claim 'aud' value doesn't contain the required audience.");
-        }
-    }
-
 }

+ 10 - 6
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/infrastructure/util/OssFileDownloadUtil.java

@@ -104,14 +104,18 @@ public class OssFileDownloadUtil {
         }
         File file = new File(saveDir + File.separator + fileName);
         FileOutputStream fos = new FileOutputStream(file);
-        fos.write(getData);
-        if (fos != null) {
-            fos.close();
-        }
-        if (inputStream != null) {
-            inputStream.close();
+        try {
+            fos.write(getData);
+        }finally {
+            if (fos != null) {
+                fos.close();
+            }
+            if (inputStream != null) {
+                inputStream.close();
+            }
         }
 
+
         log.info("info:" + url + " download success");
 
     }

+ 28 - 6
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/infrastructure/util/RandomCodeUtils.java

@@ -1,12 +1,30 @@
 package com.abi.qms.platform.infrastructure.util;
 
+import com.abi.task.common.api.exception.BusinessException;
+import lombok.extern.slf4j.Slf4j;
+
+import java.security.NoSuchAlgorithmException;
 import java.util.Random;
 
+import static java.security.SecureRandom.getInstanceStrong;
+
 /**
  * 随机码工具类
  * @author AndyTan
  */
+@Slf4j
 public class RandomCodeUtils {
+    /**
+     * SecureRandom is preferred to Random
+     */
+    private static Random rand;
+    {
+        try {
+            rand = getInstanceStrong();
+        } catch (NoSuchAlgorithmException e) {
+           throw new BusinessException(404,"初始化随机数生成方法异常");
+        }
+    }
 
     /**
      * 返回长度为n的随机字符串(随机包含数字or小写字母)
@@ -14,12 +32,16 @@ public class RandomCodeUtils {
      * @return
      */
     public static String getStr(int n) {
-        String string = "0123456789abcdefghijklmnopqrstuvwxyz";//保存数字0-9 和 大小写字母
-        char[] ch = new char[n]; //声明一个字符数组对象ch 保存 验证码
+        //保存数字0-9 和 大小写字母
+        String string = "0123456789abcdefghijklmnopqrstuvwxyz";
+        //声明一个字符数组对象ch 保存 验证码
+        char[] ch = new char[n];
         for (int i = 0; i < n; i++) {
-            Random random = new Random();//创建一个新的随机数生成器
-            int index = random.nextInt(string.length());//返回[0,string.length)范围的int值    作用:保存下标
-            ch[i] = string.charAt(index);//charAt() : 返回指定索引处的 char 值   ==》保存到字符数组对象ch里面
+            //创建一个新的随机数生成器
+            //返回[0,string.length)范围的int值    作用:保存下标
+            int index = rand.nextInt(string.length());
+            //charAt() : 返回指定索引处的 char 值   ==》保存到字符数组对象ch里面
+            ch[i] = string.charAt(index);
         }
         //将char数组类型转换为String类型保存到result
         String result = String.valueOf(ch);
@@ -34,7 +56,7 @@ public class RandomCodeUtils {
         StringBuilder result = new StringBuilder();
         char[] ch = new char[n];
         for (int i = 0; i < n; i++) {
-            Integer e = new Random().nextInt(10);
+            Integer e = rand.nextInt(10);
             result.append(e.toString());
         }
 

+ 7 - 10
abi-cloud-qr-platform-server/src/main/java/com/abi/qms/platform/service/impl/ReportServiceImpl.java

@@ -10,6 +10,7 @@ import com.abi.qms.platform.infrastructure.util.AssertUtil;
 import com.abi.qms.platform.infrastructure.util.UserUtil;
 import com.abi.qms.platform.service.ReportService;
 import com.abi.task.common.utils.PojoConverterUtils;
+import com.google.common.collect.Maps;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import org.springframework.util.CollectionUtils;
@@ -255,12 +256,7 @@ public class ReportServiceImpl implements ReportService {
     @Override
     public PackageCodeTypeRes queryPackageCodeGeneral(ReportReq reportReq) {
         //0-准备时间参数
-        Map<String,String> map=new HashMap<String,String>();
-        //判断是否有参数值
-        if(null!= reportReq.getValue()){
-           //获取开始/结束时间
-           map= FillParam(reportReq,map);
-        }
+        Map<String,String> map= fillParam(reportReq);
         PackageCodeTypeRes res = new PackageCodeTypeRes();
 
         //1-查询本期
@@ -300,12 +296,13 @@ public class ReportServiceImpl implements ReportService {
     /**
      * 封装入参
      * @param reportReq
-     * @param map
      */
-    private Map FillParam(ReportReq reportReq,Map<String,String> map) {
+    private Map<String,String> fillParam(ReportReq reportReq) {
+        if (ObjectUtils.isEmpty(reportReq) || ObjectUtils.isEmpty(reportReq.getValue())){
+            return Maps.newHashMap();
+        }
         setQueryTime(reportReq);
-        map=getBeforeWeekTime(reportReq.getValue().toString());
-        return map;
+        return getBeforeWeekTime(reportReq.getValue().toString());
     }
 
     /**

+ 25 - 8
abi-cloud-qr-platform-server/src/test/java/com/abi/qms/platform/EncryptionTest.java

@@ -2,13 +2,16 @@ package com.abi.qms.platform;
 
 import cn.hutool.crypto.SecureUtil;
 import cn.hutool.crypto.symmetric.AES;
+import com.abi.task.common.api.exception.BusinessException;
 import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
+import lombok.extern.slf4j.Slf4j;
 
 import java.io.*;
 
 /**
  * 测试加解密方法
  */
+@Slf4j
 public class EncryptionTest {
     static final String key = "EC/Z+S7c3EFJa2dtvLyekg==";
 
@@ -58,10 +61,17 @@ public class EncryptionTest {
      */
     public static void getFile(String name, String path) throws IOException {
         Writer writer = new FileWriter(path, true);
-        BufferedWriter bufw = new BufferedWriter(writer);
-        bufw.write(name);
-        bufw.newLine();
-        bufw.flush();
+        BufferedWriter buff = null;
+        try {
+            buff = new BufferedWriter(writer);
+            buff.write(name);
+            buff.newLine();
+            buff.flush();
+        }finally {
+            if (null != buff){
+                buff.close();
+            }
+        }
     }
 
     /**
@@ -75,15 +85,22 @@ public class EncryptionTest {
         File file = new File(fileName);
         Long filelength = file.length();
         byte[] filecontent = new byte[filelength.intValue()];
+        FileInputStream in = null;
         try {
-            FileInputStream in = new FileInputStream(file);
+            in = new FileInputStream(file);
             in.read(filecontent);
-            in.close();
         } catch (FileNotFoundException e) {
-            e.printStackTrace();
+            throw new BusinessException(404,"文件不存在");
         } catch (IOException e) {
-            e.printStackTrace();
+            throw new BusinessException(404,"文件io不存在");
+        }finally {
+            try {
+                in.close();
+            } catch (IOException e) {
+                throw new BusinessException(404,"io流关闭异常");
+            }
         }
+
         try {
             return new String(filecontent, encoding);
         } catch (UnsupportedEncodingException e) {

+ 1 - 1
version.txt

@@ -1 +1 @@
-feature1.0.02105311533
+feature1.0.02106151708