Ver código fonte

修复代码漏洞

gaoxiong 1 ano atrás
pai
commit
591f1914c3
18 arquivos alterados com 288 adições e 750 exclusões
  1. 0 37
      soc-auth/src/main/java/com/xunmei/auth/service/SysLoginService.java
  2. 14 13
      soc-common/soc-common-core/src/main/java/com/xunmei/common/core/util/BeanHelper.java
  3. 0 8
      soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/IDHelper.java
  4. 0 32
      soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/ip/IpUtils.java
  5. 77 156
      soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/reflect/ReflectUtils.java
  6. 1 37
      soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/uuid/UUID.java
  7. 44 74
      soc-common/soc-common-log/src/main/java/com/xunmei/common/log/aspect/LogAspect.java
  8. 7 7
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/aop/RepeatSubmitCheckAspect.java
  9. 7 5
      soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/delay/RedisDelayedQueueInit.java
  10. 0 243
      soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/AsymmetricEncryptionUtil.java
  11. 74 74
      soc-modules/soc-modules-core/src/main/java/com/xunmei/core/safetyCheck/job/SafetyCheckJobBusiness.java
  12. 3 0
      soc-modules/soc-modules-core/src/main/java/com/xunmei/core/safetyCheck/service/impl/SafetyCheckRegisterSericeImpl.java
  13. 7 0
      soc-modules/soc-modules-file/pom.xml
  14. 28 23
      soc-modules/soc-modules-file/src/main/java/com/xunmei/file/service/LocalSysFileServiceImpl.java
  15. 5 6
      soc-modules/soc-modules-file/src/main/java/com/xunmei/file/utils/FileUploadUtils.java
  16. 8 30
      soc-modules/soc-modules-file/src/main/java/com/xunmei/file/utils/PdfUtil.java
  17. 3 0
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysDeptServiceImpl.java
  18. 10 5
      soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysUserServiceImpl.java

+ 0 - 37
soc-auth/src/main/java/com/xunmei/auth/service/SysLoginService.java

@@ -1,7 +1,5 @@
 package com.xunmei.auth.service;
 
-import cn.hutool.core.util.NumberUtil;
-import cn.hutool.core.util.ObjectUtil;
 import com.xunmei.common.core.constant.CacheConstants;
 import com.xunmei.common.core.constant.Constants;
 import com.xunmei.common.core.constant.SecurityConstants;
@@ -13,8 +11,6 @@ import com.xunmei.common.core.text.Convert;
 import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.utils.ip.IpUtils;
 import com.xunmei.common.redis.utils.RedisUtils;
-import com.xunmei.common.security.utils.AsymmetricEncryptionUtil;
-import com.xunmei.common.security.utils.SecurityUtils;
 import com.xunmei.system.api.RemoteUserService;
 import com.xunmei.system.api.domain.SysUser;
 import com.xunmei.system.api.model.LoginUser;
@@ -96,39 +92,6 @@ public class SysLoginService{
         recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功", platformType);
     }
 
-    public void checkLogin(String authCode) {
-        if (SecurityUtils.isApp()) {
-            return;
-        }
-        String decrypt = AsymmetricEncryptionUtil.decrypt(authCode);
-        if (ObjectUtil.isEmpty(decrypt) || null == decrypt) {
-            throw new RuntimeException("登录信息失效");
-        }
-        //如果redis中存在此key,说明已经登录过了
-       /* BoundSetOperations<String, Object> operations = redisService.getBoundSetOperations("loginAuth");
-        if (Boolean.TRUE.equals(operations.isMember(decrypt))) {
-            throw new RuntimeException("登录信息失效");
-        }*/
-        //如果不满足此规则,说明是伪造的
-        String[] split = decrypt.split(":");
-        if (split.length != 2) {
-            throw new RuntimeException("登录信息失效");
-        }
-        //如果不满足以下规则,说明是伪造的
-        String timeStamp = split[1];
-        if (!NumberUtil.isNumber(timeStamp)) {
-            throw new RuntimeException("登录信息失效");
-        }
-        //三分钟内有效
-        if (System.currentTimeMillis() - Long.parseLong(timeStamp) > 300000) {
-            throw new RuntimeException("登录信息失效");
-        }
-        /*operations.add(decrypt);
-        operations.expireAt(DateUtil.endOfDay(new Date()));
-*/
-
-    }
-
     /**
      * 用户名登录
      * @param username

+ 14 - 13
soc-common/soc-common-core/src/main/java/com/xunmei/common/core/util/BeanHelper.java

@@ -66,12 +66,12 @@ public class BeanHelper {
         // Field[] fields = obj.getClass().getDeclaredFields();
         Field[] fields = getAllFields(obj.getClass());
         //遍历所有属性
-        for (int j = 0; j < fields.length; j++) {
-            Field field = fields[j];
-            String type = field.getGenericType().toString();
-            ReflectionUtils.makeAccessible(field);
-            Object value = null;
-            try {
+        try {
+            for (int j = 0; j < fields.length; j++) {
+                Field field = fields[j];
+                String type = field.getGenericType().toString();
+                ReflectionUtils.makeAccessible(field);
+                Object value = null;
                 value = field.get(obj);
                 if (value != null && StringUtils.isNotBlank(value.toString())) {
                     continue;
@@ -114,11 +114,13 @@ public class BeanHelper {
                     default:
                         break;
                 }
-            } catch (IllegalAccessException e) {
-                e.printStackTrace();
             }
+        } catch (IllegalAccessException e) {
+            e.printStackTrace();
         }
+
     }
+
     /**
      * 获取本类及其父类的属性的方法
      *
@@ -140,15 +142,14 @@ public class BeanHelper {
             return Collections.emptyList();
         }
         List<T> targetList = new ArrayList<>();
-
-        for (U sourceObject : sourceList) {
-            try {
+        try {
+            for (U sourceObject : sourceList) {
                 T targetObject = targetClass.getDeclaredConstructor().newInstance();
                 BeanUtils.copyProperties(sourceObject, targetObject);
                 targetList.add(targetObject);
-            } catch (Exception e) {
-                e.printStackTrace();
             }
+        } catch (Exception e) {
+            e.printStackTrace();
         }
 
         return targetList;

+ 0 - 8
soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/IDHelper.java

@@ -106,12 +106,4 @@ public class IDHelper {
                 .collect(Collectors.joining()));
     }
 
-    public static String md5(final Serializable... os) {
-        final StringBuilder stringBuilder = new StringBuilder(os.length * 10);
-        for (final Serializable o : os) {
-            stringBuilder.append(o.toString());
-        }
-        stringBuilder.trimToSize();
-        return DigestUtils.md5Hex(stringBuilder.toString());
-    }
 }

+ 0 - 32
soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/ip/IpUtils.java

@@ -212,39 +212,7 @@ public class IpUtils
         return bytes;
     }
 
-    /**
-     * 获取IP地址
-     * 
-     * @return 本地IP地址
-     */
-    public static String getHostIp()
-    {
-        try
-        {
-            return InetAddress.getLocalHost().getHostAddress();
-        }
-        catch (UnknownHostException e)
-        {
-        }
-        return "127.0.0.1";
-    }
 
-    /**
-     * 获取主机名
-     * 
-     * @return 本地主机名
-     */
-    public static String getHostName()
-    {
-        try
-        {
-            return InetAddress.getLocalHost().getHostName();
-        }
-        catch (UnknownHostException e)
-        {
-        }
-        return "未知";
-    }
 
     /**
      * 从多级反向代理中获得第一个非unknown IP地址

+ 77 - 156
soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/reflect/ReflectUtils.java

@@ -13,12 +13,11 @@ import java.util.Date;
 
 /**
  * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
- * 
+ *
  * @author xunmei
  */
 @SuppressWarnings("rawtypes")
-public class ReflectUtils
-{
+public class ReflectUtils {
     private static final String SETTER_PREFIX = "set";
 
     private static final String GETTER_PREFIX = "get";
@@ -32,13 +31,11 @@ public class ReflectUtils
      * 支持多级,如:对象名.对象名.方法
      */
     @SuppressWarnings("unchecked")
-    public static <E> E invokeGetter(Object obj, String propertyName)
-    {
+    public static <E> E invokeGetter(Object obj, String propertyName) {
         Object object = obj;
-        for (String name : StringUtils.split(propertyName, "."))
-        {
+        for (String name : StringUtils.split(propertyName, ".")) {
             String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
-            object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
+            object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
         }
         return (E) object;
     }
@@ -47,21 +44,16 @@ public class ReflectUtils
      * 调用Setter方法, 仅匹配方法名。
      * 支持多级,如:对象名.对象名.方法
      */
-    public static <E> void invokeSetter(Object obj, String propertyName, E value)
-    {
+    public static <E> void invokeSetter(Object obj, String propertyName, E value) {
         Object object = obj;
         String[] names = StringUtils.split(propertyName, ".");
-        for (int i = 0; i < names.length; i++)
-        {
-            if (i < names.length - 1)
-            {
+        for (int i = 0; i < names.length; i++) {
+            if (i < names.length - 1) {
                 String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
-                object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
-            }
-            else
-            {
+                object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
+            } else {
                 String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
-                invokeMethodByName(object, setterMethodName, new Object[] { value });
+                invokeMethodByName(object, setterMethodName, new Object[]{value});
             }
         }
     }
@@ -70,21 +62,16 @@ public class ReflectUtils
      * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
      */
     @SuppressWarnings("unchecked")
-    public static <E> E getFieldValue(final Object obj, final String fieldName)
-    {
+    public static <E> E getFieldValue(final Object obj, final String fieldName) {
         Field field = getAccessibleField(obj, fieldName);
-        if (field == null)
-        {
+        if (field == null) {
             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
             return null;
         }
         E result = null;
-        try
-        {
+        try {
             result = (E) field.get(obj);
-        }
-        catch (IllegalAccessException e)
-        {
+        } catch (IllegalAccessException e) {
             logger.error("不可能抛出的异常{}", e.getMessage());
         }
         return result;
@@ -93,21 +80,16 @@ public class ReflectUtils
     /**
      * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
      */
-    public static <E> void setFieldValue(final Object obj, final String fieldName, final E value)
-    {
+    public static <E> void setFieldValue(final Object obj, final String fieldName, final E value) {
         Field field = getAccessibleField(obj, fieldName);
-        if (field == null)
-        {
+        if (field == null) {
             // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
             return;
         }
-        try
-        {
+        try {
             field.set(obj, value);
-        }
-        catch (IllegalAccessException e)
-        {
+        } catch (IllegalAccessException e) {
             logger.error("不可能抛出的异常: {}", e.getMessage());
         }
     }
@@ -119,24 +101,18 @@ public class ReflectUtils
      */
     @SuppressWarnings("unchecked")
     public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
-            final Object[] args)
-    {
-        if (obj == null || methodName == null)
-        {
+                                     final Object[] args) {
+        if (obj == null || methodName == null) {
             return null;
         }
         Method method = getAccessibleMethod(obj, methodName, parameterTypes);
-        if (method == null)
-        {
+        if (method == null) {
             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
             return null;
         }
-        try
-        {
+        try {
             return (E) method.invoke(obj, args);
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
             throw convertReflectionExceptionToUnchecked(msg, e);
         }
@@ -148,68 +124,44 @@ public class ReflectUtils
      * 只匹配函数名,如果有多个同名函数调用第一个。
      */
     @SuppressWarnings("unchecked")
-    public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
-    {
+    public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
         Method method = getAccessibleMethodByName(obj, methodName, args.length);
-        if (method == null)
-        {
+        if (method == null) {
             // 如果为空不报错,直接返回空。
             logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
             return null;
         }
-        try
-        {
+        try {
             // 类型转换(将参数数据类型转换为目标方法参数类型)
             Class<?>[] cs = method.getParameterTypes();
-            for (int i = 0; i < cs.length; i++)
-            {
-                if (args[i] != null && !args[i].getClass().equals(cs[i]))
-                {
-                    if (cs[i] == String.class)
-                    {
+            for (int i = 0; i < cs.length; i++) {
+                if (args[i] != null && !args[i].getClass().equals(cs[i])) {
+                    if (cs[i] == String.class) {
                         args[i] = Convert.toStr(args[i]);
-                        if (StringUtils.endsWith((String) args[i], ".0"))
-                        {
+                        if (StringUtils.endsWith((String) args[i], ".0")) {
                             args[i] = StringUtils.substringBefore((String) args[i], ".0");
                         }
-                    }
-                    else if (cs[i] == Integer.class)
-                    {
+                    } else if (cs[i] == Integer.class) {
                         args[i] = Convert.toInt(args[i]);
-                    }
-                    else if (cs[i] == Long.class)
-                    {
+                    } else if (cs[i] == Long.class) {
                         args[i] = Convert.toLong(args[i]);
-                    }
-                    else if (cs[i] == Double.class)
-                    {
+                    } else if (cs[i] == Double.class) {
                         args[i] = Convert.toDouble(args[i]);
-                    }
-                    else if (cs[i] == Float.class)
-                    {
+                    } else if (cs[i] == Float.class) {
                         args[i] = Convert.toFloat(args[i]);
-                    }
-                    else if (cs[i] == Date.class)
-                    {
-                        if (args[i] instanceof String)
-                        {
+                    } else if (cs[i] == Date.class) {
+                        if (args[i] instanceof String) {
                             args[i] = DateUtils.parseDate(args[i]);
-                        }
-                        else
-                        {
+                        } else {
                             //args[i] = DateUtil.getJavaDate((Double) args[i]);
                         }
-                    }
-                    else if (cs[i] == boolean.class || cs[i] == Boolean.class)
-                    {
+                    } else if (cs[i] == boolean.class || cs[i] == Boolean.class) {
                         args[i] = Convert.toBool(args[i]);
                     }
                 }
             }
             return (E) method.invoke(obj, args);
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
             throw convertReflectionExceptionToUnchecked(msg, e);
         }
@@ -219,26 +171,21 @@ public class ReflectUtils
      * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
      * 如向上转型到Object仍无法找到, 返回null.
      */
-    public static Field getAccessibleField(final Object obj, final String fieldName)
-    {
+    public static Field getAccessibleField(final Object obj, final String fieldName) {
         // 为空不报错。直接返回 null
-        if (obj == null)
-        {
+        if (obj == null) {
             return null;
         }
         Validate.notBlank(fieldName, "fieldName can't be blank");
-        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass())
-        {
-            try
-            {
+        try {
+            for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
+
                 Field field = superClass.getDeclaredField(fieldName);
                 makeAccessible(field);
                 return field;
             }
-            catch (NoSuchFieldException e)
-            {
-                continue;
-            }
+        } catch (NoSuchFieldException e) {
+            e.printStackTrace();
         }
         return null;
     }
@@ -250,26 +197,22 @@ public class ReflectUtils
      * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
      */
     public static Method getAccessibleMethod(final Object obj, final String methodName,
-            final Class<?>... parameterTypes)
-    {
+                                             final Class<?>... parameterTypes) {
         // 为空不报错。直接返回 null
-        if (obj == null)
-        {
+        if (obj == null) {
             return null;
         }
         Validate.notBlank(methodName, "methodName can't be blank");
-        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
-        {
-            try
-            {
+        try {
+            for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
                 Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
-                makeAccessible(method);
+                if(method != null){
+                    makeAccessible(method);
+                }
                 return method;
             }
-            catch (NoSuchMethodException e)
-            {
-                continue;
-            }
+        } catch (NoSuchMethodException e) {
+            e.printStackTrace();
         }
         return null;
     }
@@ -280,21 +223,16 @@ public class ReflectUtils
      * 只匹配函数名。
      * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
      */
-    public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum)
-    {
+    public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) {
         // 为空不报错。直接返回 null
-        if (obj == null)
-        {
+        if (obj == null) {
             return null;
         }
         Validate.notBlank(methodName, "methodName can't be blank");
-        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass())
-        {
+        for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
             Method[] methods = searchType.getDeclaredMethods();
-            for (Method method : methods)
-            {
-                if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
-                {
+            for (Method method : methods) {
+                if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) {
                     makeAccessible(method);
                     return method;
                 }
@@ -306,11 +244,9 @@ public class ReflectUtils
     /**
      * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
      */
-    public static void makeAccessible(Method method)
-    {
+    public static void makeAccessible(Method method) {
         if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
-                && !method.isAccessible())
-        {
+                && !method.isAccessible()) {
             ReflectionUtils.makeAccessible(method);
         }
     }
@@ -318,11 +254,9 @@ public class ReflectUtils
     /**
      * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
      */
-    public static void makeAccessible(Field field)
-    {
+    public static void makeAccessible(Field field) {
         if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
-                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible())
-        {
+                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
             ReflectionUtils.makeAccessible(field);
         }
     }
@@ -332,8 +266,7 @@ public class ReflectUtils
      * 如无法找到, 返回Object.class.
      */
     @SuppressWarnings("unchecked")
-    public static <T> Class<T> getClassGenricType(final Class clazz)
-    {
+    public static <T> Class<T> getClassGenricType(final Class clazz) {
         return getClassGenricType(clazz, 0);
     }
 
@@ -341,26 +274,22 @@ public class ReflectUtils
      * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
      * 如无法找到, 返回Object.class.
      */
-    public static Class getClassGenricType(final Class clazz, final int index)
-    {
+    public static Class getClassGenricType(final Class clazz, final int index) {
         Type genType = clazz.getGenericSuperclass();
 
-        if (!(genType instanceof ParameterizedType))
-        {
+        if (!(genType instanceof ParameterizedType)) {
             logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
             return Object.class;
         }
 
         Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
 
-        if (index >= params.length || index < 0)
-        {
+        if (index >= params.length || index < 0) {
             logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                     + params.length);
             return Object.class;
         }
-        if (!(params[index] instanceof Class))
-        {
+        if (!(params[index] instanceof Class)) {
             logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
             return Object.class;
         }
@@ -368,18 +297,14 @@ public class ReflectUtils
         return (Class) params[index];
     }
 
-    public static Class<?> getUserClass(Object instance)
-    {
-        if (instance == null)
-        {
+    public static Class<?> getUserClass(Object instance) {
+        if (instance == null) {
             throw new RuntimeException("Instance must not be null");
         }
         Class clazz = instance.getClass();
-        if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR))
-        {
+        if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
             Class<?> superClass = clazz.getSuperclass();
-            if (superClass != null && !Object.class.equals(superClass))
-            {
+            if (superClass != null && !Object.class.equals(superClass)) {
                 return superClass;
             }
         }
@@ -390,15 +315,11 @@ public class ReflectUtils
     /**
      * 将反射时的checked exception转换为unchecked exception.
      */
-    public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e)
-    {
+    public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) {
         if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
-                || e instanceof NoSuchMethodException)
-        {
+                || e instanceof NoSuchMethodException) {
             return new IllegalArgumentException(msg, e);
-        }
-        else if (e instanceof InvocationTargetException)
-        {
+        } else if (e instanceof InvocationTargetException) {
             return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
         }
         return new RuntimeException(msg, e);

+ 1 - 37
soc-common/soc-common-core/src/main/java/com/xunmei/common/core/utils/uuid/UUID.java

@@ -94,7 +94,7 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
      */
     public static UUID randomUUID(boolean isSecure)
     {
-        final Random ng = isSecure ? Holder.numberGenerator : getRandom();
+        final Random ng = Holder.numberGenerator;
 
         byte[] randomBytes = new byte[16];
         ng.nextBytes(randomBytes);
@@ -105,31 +105,6 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
         return new UUID(randomBytes);
     }
 
-    /**
-     * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。
-     *
-     * @param name 用于构造 UUID 的字节数组。
-     *
-     * @return 根据指定数组生成的 {@code UUID}
-     */
-    public static UUID nameUUIDFromBytes(byte[] name)
-    {
-        MessageDigest md;
-        try
-        {
-            md = MessageDigest.getInstance("MD5");
-        }
-        catch (NoSuchAlgorithmException nsae)
-        {
-            throw new InternalError("MD5 not supported");
-        }
-        byte[] md5Bytes = md.digest(name);
-        md5Bytes[6] &= 0x0f; /* clear version */
-        md5Bytes[6] |= 0x30; /* set to version 3 */
-        md5Bytes[8] &= 0x3f; /* clear variant */
-        md5Bytes[8] |= 0x80; /* set to IETF variant */
-        return new UUID(md5Bytes);
-    }
 
     /**
      * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。
@@ -471,15 +446,4 @@ public final class UUID implements java.io.Serializable, Comparable<UUID>
             throw new UtilException(e);
         }
     }
-
-    /**
-     * 获取随机数生成器对象<br>
-     * ThreadLocalRandom是JDK 7之后提供并发产生随机数,能够解决多个线程发生的竞争争夺。
-     * 
-     * @return {@link ThreadLocalRandom}
-     */
-    public static ThreadLocalRandom getRandom()
-    {
-        return ThreadLocalRandom.current();
-    }
 }

+ 44 - 74
soc-common/soc-common-log/src/main/java/com/xunmei/common/log/aspect/LogAspect.java

@@ -32,18 +32,20 @@ import java.util.Map;
 
 /**
  * 操作日志记录处理
- *
  */
 @Aspect
 @Component
-public class LogAspect
-{
+public class LogAspect {
     private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
 
-    /** 排除敏感属性字段 */
-    public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };
+    /**
+     * 排除敏感属性字段
+     */
+    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};
 
-    /** 计算操作消耗时间 */
+    /**
+     * 计算操作消耗时间
+     */
     private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("Cost Time");
 
     @Autowired
@@ -53,8 +55,7 @@ public class LogAspect
      * 处理请求前执行
      */
     @Before(value = "@annotation(controllerLog)")
-    public void boBefore(JoinPoint joinPoint, Log controllerLog)
-    {
+    public void boBefore(JoinPoint joinPoint, Log controllerLog) {
         TIME_THREADLOCAL.set(System.currentTimeMillis());
     }
 
@@ -64,27 +65,23 @@ public class LogAspect
      * @param joinPoint 切点
      */
     @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
-    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult)
-    {
+    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
         handleLog(joinPoint, controllerLog, null, jsonResult);
     }
 
     /**
      * 拦截异常操作
-     * 
+     *
      * @param joinPoint 切点
-     * @param e 异常
+     * @param e         异常
      */
     @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
-    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e)
-    {
+    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
         handleLog(joinPoint, controllerLog, e, null);
     }
 
-    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult)
-    {
-        try
-        {
+    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
+        try {
             // *========数据库日志=========*//
             SysOperLog operLog = new SysOperLog();
             operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
@@ -93,13 +90,11 @@ public class LogAspect
             operLog.setOperIp(ip);
             operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
             String username = SecurityUtils.getUsername();
-            if (StringUtils.isNotBlank(username))
-            {
+            if (StringUtils.isNotBlank(username)) {
                 operLog.setOperName(username);
             }
 
-            if (e != null)
-            {
+            if (e != null) {
                 operLog.setStatus(BusinessStatus.FAIL.ordinal());
                 operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
             }
@@ -115,28 +110,23 @@ public class LogAspect
             operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());
             // 保存数据库
             asyncLogService.saveSysLog(operLog);
-        }
-        catch (Exception exp)
-        {
+        } catch (Exception exp) {
             // 记录本地异常日志
             log.error("异常信息:{}", exp.getMessage());
             exp.printStackTrace();
-        }
-        finally
-        {
+        } finally {
             TIME_THREADLOCAL.remove();
         }
     }
 
     /**
      * 获取注解中对方法的描述信息 用于Controller层注解
-     * 
-     * @param log 日志
+     *
+     * @param log     日志
      * @param operLog 操作日志
      * @throws Exception
      */
-    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception
-    {
+    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception {
         // 设置action动作
         operLog.setBusinessType(log.businessType().ordinal());
         // 设置标题
@@ -144,36 +134,30 @@ public class LogAspect
         // 设置操作人类别
         operLog.setOperatorType(log.operatorType().ordinal());
         // 是否需要保存request,参数和值
-        if (log.isSaveRequestData())
-        {
+        if (log.isSaveRequestData()) {
             // 获取参数的信息,传入到数据库中。
             setRequestValue(joinPoint, operLog, log.excludeParamNames());
         }
         // 是否需要保存response,参数和值
-        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult))
-        {
+        if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) {
             operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
         }
     }
 
     /**
      * 获取请求的参数,放到log中
-     * 
+     *
      * @param operLog 操作日志
      * @throws Exception 异常
      */
-    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception
-    {
+    private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception {
         String requestMethod = operLog.getRequestMethod();
         Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());
         if (StringUtils.isEmpty(paramsMap)
-                && (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)))
-        {
+                && (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))) {
             String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames);
             operLog.setOperParam(StringUtils.substring(params, 0, 2000));
-        }
-        else
-        {
+        } else {
             operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter(excludeParamNames)), 0, 2000));
         }
     }
@@ -181,24 +165,19 @@ public class LogAspect
     /**
      * 参数拼装
      */
-    private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames)
-    {
+    private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames) {
         String params = "";
-        if (paramsArray != null && paramsArray.length > 0)
-        {
-            for (Object o : paramsArray)
-            {
-                if (StringUtils.isNotNull(o) && !isFilterObject(o))
-                {
-                    try
-                    {
+        if (paramsArray != null && paramsArray.length > 0) {
+            try {
+                for (Object o : paramsArray) {
+                    if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
+
                         String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(excludeParamNames));
                         params += jsonObj.toString() + " ";
                     }
-                    catch (Exception e)
-                    {
-                    }
                 }
+            } catch (Exception e) {
+                e.printStackTrace();
             }
         }
         return params.trim();
@@ -207,38 +186,29 @@ public class LogAspect
     /**
      * 忽略敏感属性
      */
-    public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames)
-    {
+    public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames) {
         return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames));
     }
 
     /**
      * 判断是否需要过滤的对象。
-     * 
+     *
      * @param o 对象信息。
      * @return 如果是需要过滤的对象,则返回true;否则返回false。
      */
     @SuppressWarnings("rawtypes")
-    public boolean isFilterObject(final Object o)
-    {
+    public boolean isFilterObject(final Object o) {
         Class<?> clazz = o.getClass();
-        if (clazz.isArray())
-        {
+        if (clazz.isArray()) {
             return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
-        }
-        else if (Collection.class.isAssignableFrom(clazz))
-        {
+        } else if (Collection.class.isAssignableFrom(clazz)) {
             Collection collection = (Collection) o;
-            for (Object value : collection)
-            {
+            for (Object value : collection) {
                 return value instanceof MultipartFile;
             }
-        }
-        else if (Map.class.isAssignableFrom(clazz))
-        {
+        } else if (Map.class.isAssignableFrom(clazz)) {
             Map map = (Map) o;
-            for (Object value : map.entrySet())
-            {
+            for (Object value : map.entrySet()) {
                 Map.Entry entry = (Map.Entry) value;
                 return entry.getValue() instanceof MultipartFile;
             }

+ 7 - 7
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/aop/RepeatSubmitCheckAspect.java

@@ -1,6 +1,8 @@
 package com.xunmei.common.redis.aop;
 
 import cn.hutool.core.convert.Convert;
+import cn.hutool.crypto.SmUtil;
+import cn.hutool.crypto.symmetric.SM4;
 import com.alibaba.fastjson2.JSON;
 import com.xunmei.common.core.web.domain.AjaxResult;
 import com.xunmei.common.redis.utils.RedisUtils;
@@ -21,11 +23,9 @@ import org.springframework.web.context.request.ServletRequestAttributes;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.xml.bind.DatatypeConverter;
 import java.io.IOException;
 import java.lang.reflect.Method;
 import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 
 /**
@@ -102,7 +102,7 @@ public class RepeatSubmitCheckAspect {
         }
 
         // redis查询不为null,并且本次的请求参数md5与val相同则为重复请求
-        final String md5Value = jdkMD5(sb.toString());
+        final String md5Value = SM4(sb.toString());
         if (StringUtils.isNotBlank(bucket.get())) {
             return bucket.get().equals(md5Value);
         }
@@ -120,9 +120,9 @@ public class RepeatSubmitCheckAspect {
     /**
      * MD5摘要并转换为字符串
      */
-    private static String jdkMD5(String str) throws NoSuchAlgorithmException {
-        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
-        byte[] mdBytes = messageDigest.digest(str.getBytes());
-        return DatatypeConverter.printHexBinary(mdBytes);
+    private static String SM4(String str){
+        SM4 sm4 = SmUtil.sm4();
+        String encrypt = sm4.encryptHex(str.getBytes());
+        return encrypt;
     }
 }

+ 7 - 5
soc-common/soc-common-redis/src/main/java/com/xunmei/common/redis/delay/RedisDelayedQueueInit.java

@@ -21,6 +21,7 @@ import java.util.Map;
 public class RedisDelayedQueueInit implements ApplicationContextAware {
     @Autowired
     private RedissonClient redissonClient;
+
     @Override
     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         Map<String, RedisDelayedQueueListener> map = applicationContext.getBeansOfType(RedisDelayedQueueListener.class);
@@ -33,7 +34,8 @@ public class RedisDelayedQueueInit implements ApplicationContextAware {
 
     /**
      * 启动线程获取队列
-     * @param queueName 队列名称
+     *
+     * @param queueName                 队列名称
      * @param redisDelayedQueueListener 任务回调监听
      */
     private <T> void startThread(String queueName, RedisDelayedQueueListener redisDelayedQueueListener) {
@@ -41,14 +43,14 @@ public class RedisDelayedQueueInit implements ApplicationContextAware {
         //由于此线程需要常驻,可以新建线程,不用交给线程池管理
         Thread thread = new Thread(() -> {
             log.info("启动监听队列线程" + queueName);
-            while (true) {
-                try {
+            try {
+                while (true) {
                     T t = blockingFairQueue.take();
                     log.info("监听队列线程{},获取到值:{}", queueName, JSON.toJSONString(t));
                     redisDelayedQueueListener.invoke(t);
-                } catch (Exception e) {
-                    log.info("监听队列线程错误,", e);
                 }
+            } catch (Exception e) {
+                log.info("监听队列线程错误,", e);
             }
         });
         thread.setName(queueName);

+ 0 - 243
soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/AsymmetricEncryptionUtil.java

@@ -1,243 +0,0 @@
-package com.xunmei.common.security.utils;
-
-
-import cn.hutool.core.io.resource.ClassPathResource;
-import cn.hutool.core.io.resource.NoResourceException;
-import cn.hutool.core.util.ObjectUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.codec.binary.Base64;
-
-import javax.crypto.Cipher;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.nio.charset.StandardCharsets;
-import java.security.*;
-import java.security.interfaces.RSAPrivateKey;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-import java.util.Arrays;
-import java.util.concurrent.ConcurrentHashMap;
-
-
-
-@Slf4j
-public class AsymmetricEncryptionUtil {
-
-    //private static final String RSA = "RSA";
-    private static final String RSA = "AES/ECB/PKCS7Padding";
-    private static final ConcurrentHashMap<String,Key> cache = new ConcurrentHashMap<>();
-
-/*    public static void main(String[] args) {
-        //test("123456");
-        String content = "GhZ/K5X9m/c2ArlDvH1H2IU0TOfAV0mR7vZJxXtanaS0GyNRPu/AzQld9Oe6LmaJRRSEleJQ6041u6IqeGKXnqsjrK1IQjwtJDgTAz3GvbxyOsedl0pol2FqdvQFw/y3rsFEFQsCYPPF7IYS/6YScSS+F7Qm/k+6fYryJG1xHoU=";
-        String decrypt = decrypt(content);
-        System.out.println("解密后明文为:"+decrypt);
-    }*/
-
-/*    public static void test(String content) {
-        try {
-            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
-            keyPairGenerator.initialize(1024);
-            KeyPair keyPair = keyPairGenerator.generateKeyPair();
-            //生成公钥
-            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
-            //生成密钥
-            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
-            //加密
-            String encrypt = encryptByAsymmetric(content, rsaPublicKey);
-            System.out.println("加密密文:" + encrypt);
-            //解密
-            String decrypt = decryptByAsymmetric(encrypt, rsaPrivateKey);
-            System.out.println("原文内容:" + content);
-            System.out.println("解密明文:" + decrypt);
-        } catch (NoSuchAlgorithmException e) {
-            log.error("加解密失败", e);
-        }
-    }*/
-
-
-    /**
-     * 从文件中加载密钥
-     */
-    private static Key loadKeyFromFile(InputStream inputStream, Boolean isPublic) {
-
-        try {
-            //将InputStream读入Reader中
-            Reader reader = new InputStreamReader(inputStream);
-            //实例化一个StringBuilder以保存结果
-            StringBuilder result = new StringBuilder();
-            //读取每个字节并转换为char,添加到StringBuilder
-            for (int data = reader.read(); data != -1; data = reader.read()) {
-                result.append((char) data);
-            }
-            // 将文件内容转为字符串
-            String keyString = result.toString();
-            //String keyString = FileUtils.readFileToString(file, String.valueOf(StandardCharsets.UTF_8));
-            // 进行Base64解码
-            byte[] decode = cn.hutool.core.codec.Base64.decode(keyString);
-            // 获取密钥工厂
-            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
-            if (!isPublic) {
-                // 构建密钥规范
-                PKCS8EncodedKeySpec key = new PKCS8EncodedKeySpec(decode);
-                return keyFactory.generatePrivate(key);
-            }
-            // 构建密钥规范
-            X509EncodedKeySpec key = new X509EncodedKeySpec(decode);
-            // 获取公钥
-            return keyFactory.generatePublic(key);
-        } catch (Exception e) {
-            e.printStackTrace();
-            throw new RuntimeException("获取密钥文件失败!");
-        }
-    }
-
-    public static String encrypt(String content) {
-        if (ObjectUtil.isEmpty(content)) {
-            return null;
-        }
-        if (cache.containsKey("publicKey")){
-            return encryptByAsymmetric(content, (RSAPublicKey) cache.get("publicKey"));
-        }
-        String result = null;
-        try {
-            final ClassPathResource resource = new ClassPathResource("key/publicKey.pub");
-            RSAPublicKey publicKey1 = (RSAPublicKey) loadKeyFromFile(resource.getStream(), true);
-            cache.put("publicKey",publicKey1);
-            result = encryptByAsymmetric(content, publicKey1);
-        } catch (Exception e) {
-            log.error("加密失败", e);
-        }
-        return result;
-    }
-
-    public static String decrypt(String encrypt) {
-        if (ObjectUtil.isEmpty(encrypt)) {
-            return null;
-        }
-        if (cache.containsKey("privateKey")){
-            return decryptByAsymmetric(encrypt, (RSAPrivateKey) cache.get("privateKey"));
-        }
-        String result = null;
-        try {
-            ClassPathResource resource = new ClassPathResource("key/private.pri");
-            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) loadKeyFromFile(resource.getStream(), false);
-            cache.put("privateKey",rsaPrivateKey);
-            result = decryptByAsymmetric(encrypt, rsaPrivateKey);
-        } catch (NoResourceException e) {
-            log.error("解密失败", e);
-        }
-        return result;
-    }
-
-    /**
-     * 解密
-     *
-     * @param encrypted : 密文
-     * @param key       : 密钥
-     * @return : 原文
-     * @throws Exception
-     */
-    private static String decryptByAsymmetric(String encrypted, Key key) {
-        try {
-            // 获取Cipher对象
-            Cipher cipher = Cipher.getInstance(RSA,"CCM");
-            // 初始化模式(解密)和密钥
-            cipher.init(Cipher.DECRYPT_MODE, key);
-            return new String(getMaxResultDecrypt(encrypted, cipher));
-        } catch (
-                Exception e) {
-            e.printStackTrace();
-            throw new RuntimeException("解密失败!");
-        }
-    }
-
-
-    /**
-     * 加密
-     *
-     * @param content : 加密内容
-     * @param key     : 密钥(公钥/密钥)
-     * @return : 密文
-     * @throws Exception
-     */
-    private static String encryptByAsymmetric(String content, Key key) {
-        try {
-            // 获取Cipher对象
-            Cipher cipher = Cipher.getInstance(RSA,"CCM");
-            // 初始化模式(加密)和密钥
-            cipher.init(Cipher.ENCRYPT_MODE, key);
-            byte[] resultBytes = getMaxResultEncrypt(content, cipher);
-            return Base64.encodeBase64String(resultBytes);
-        } catch (Exception e) {
-            e.printStackTrace();
-            throw new RuntimeException("加密失败!");
-        }
-    }
-
-    /**
-     * 分段处理加密数据
-     *
-     * @param content : 加密文本
-     * @param cipher  : Cipher对象
-     * @return
-     */
-    private static byte[] getMaxResultEncrypt(String content, Cipher cipher) throws Exception {
-        byte[] inputArray = content.getBytes();
-        int inputLength = inputArray.length;
-        // 最大加密字节数,超出最大字节数需要分组加密
-        int MAX_ENCRYPT_BLOCK = 117;
-        // 标识
-        int offSet = 0;
-        byte[] resultBytes = {};
-        byte[] cache = {};
-        while (inputLength - offSet > 0) {
-            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
-                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
-                offSet += MAX_ENCRYPT_BLOCK;
-            } else {
-                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
-                offSet = inputLength;
-            }
-            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
-            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
-        }
-        return resultBytes;
-    }
-
-    /**
-     * 分段处理解密数据
-     *
-     * @param decryptText : 加密文本
-     * @param cipher      : Cipher对象
-     * @throws Exception
-     */
-    private static byte[] getMaxResultDecrypt(String decryptText, Cipher cipher) throws Exception {
-        byte[] inputArray = Base64.decodeBase64(decryptText.getBytes(StandardCharsets.UTF_8));
-        int inputLength = inputArray.length;
-
-        // 最大解密字节数,超出最大字节数需要分组加密
-        int MAX_ENCRYPT_BLOCK = 128;
-        // 标识
-        int offSet = 0;
-        byte[] resultBytes = {};
-        byte[] cache = {};
-        while (inputLength - offSet > 0) {
-            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
-                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
-                offSet += MAX_ENCRYPT_BLOCK;
-            } else {
-                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
-                offSet = inputLength;
-            }
-            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
-            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
-        }
-        return resultBytes;
-    }
-
-
-}
-

+ 74 - 74
soc-modules/soc-modules-core/src/main/java/com/xunmei/core/safetyCheck/job/SafetyCheckJobBusiness.java

@@ -747,99 +747,99 @@ public class SafetyCheckJobBusiness extends TaskCreatingServiceImplBase<CoreSafe
 
         }
         List<SysOrg> orgs = remoteOrgService.selectByOrgIdList(orgIds, SecurityConstants.INNER);
-        for (SysOrg worg : orgs) {
-            if (ObjectUtil.isNull(worg.getType())) {
-                continue;
-            }
+        try {
+            for (SysOrg worg : orgs) {
+                if (ObjectUtil.isNull(worg.getType())) {
+                    continue;
+                }
 
-            Long orgId = worg.getId();
-            checkTaskService.deleteByOrgIdAndRange(orgId, startDate, endDate, planCycle);
-            if (!workingMap.containsKey(orgId) || !workingMap.get(orgId)) {
-                //当前作息周期已经歇业,删除未进行的任务
+                Long orgId = worg.getId();
                 checkTaskService.deleteByOrgIdAndRange(orgId, startDate, endDate, planCycle);
-                continue;
-            } else {
-                //开始营业,重新生成任务
-                //获取当前机构的所属行社
-                List<Long> wids = new ArrayList();
-                wids.add(worg.getId());
-                List<SysOrg> orgs1 = remoteOrgService.selectParentHs(wids, SecurityConstants.INNER);
-                //拿到唯一行社
-                SysOrg ofhs = null;
-                Integer ofType = 0;
-                if (CollectionUtil.isNotEmpty(orgs1)) {
-                    ofhs = orgs1.get(0);
-                    ofType = ofhs.getType();
-                    //拿到当前周期所有检查计划
-                    List<CoreSafecheckPlan> plans = planMapper.selectByPlanStatus(1, planCycle);
+                if (!workingMap.containsKey(orgId) || !workingMap.get(orgId)) {
+                    //当前作息周期已经歇业,删除未进行的任务
+                    checkTaskService.deleteByOrgIdAndRange(orgId, startDate, endDate, planCycle);
+                    continue;
+                } else {
+                    //开始营业,重新生成任务
+                    //获取当前机构的所属行社
+                    List<Long> wids = new ArrayList();
+                    wids.add(worg.getId());
+                    List<SysOrg> orgs1 = remoteOrgService.selectParentHs(wids, SecurityConstants.INNER);
+                    //拿到唯一行社
+                    SysOrg ofhs = null;
+                    Integer ofType = 0;
+                    if (CollectionUtil.isNotEmpty(orgs1)) {
+                        ofhs = orgs1.get(0);
+                        ofType = ofhs.getType();
+                        //拿到当前周期所有检查计划
+                        List<CoreSafecheckPlan> plans = planMapper.selectByPlanStatus(1, planCycle);
 //                    Long fcheckOrgType = Long.valueOf(worg.getType());
-                    //过滤受检机构类型为作息变更机构类型的计划
+                        //过滤受检机构类型为作息变更机构类型的计划
 
-                    Iterator<CoreSafecheckPlan> iterator = plans.iterator();
+                        Iterator<CoreSafecheckPlan> iterator = plans.iterator();
 
-                    while (iterator.hasNext()) {
-                        CoreSafecheckPlan p = iterator.next();
-                        List<Integer> checkOrgTypes = coreSafecheckPlanToCheckOrgTypeMapper.selectList(new LambdaQueryWrapper<CoreSafecheckPlanToCheckOrgType>().eq(CoreSafecheckPlanToCheckOrgType::getPlanId, p.getId())).stream().map(CoreSafecheckPlanToCheckOrgType::getTypeId).collect(Collectors.toList());
-                        if (!checkOrgTypes.contains(worg.getType())) {
-                            iterator.remove();
+                        while (iterator.hasNext()) {
+                            CoreSafecheckPlan p = iterator.next();
+                            List<Integer> checkOrgTypes = coreSafecheckPlanToCheckOrgTypeMapper.selectList(new LambdaQueryWrapper<CoreSafecheckPlanToCheckOrgType>().eq(CoreSafecheckPlanToCheckOrgType::getPlanId, p.getId())).stream().map(CoreSafecheckPlanToCheckOrgType::getTypeId).collect(Collectors.toList());
+                            if (!checkOrgTypes.contains(worg.getType())) {
+                                iterator.remove();
+                            }
                         }
-                    }
 
 //                    plans = plans.stream().filter(p -> {
 //                        p.getCheckOrgType().equals(fcheckOrgType)
 //                    }).collect(Collectors.toList());
-                    Integer fofOrgType = ofType;
-                    //过滤所属机构类型为作息变更机构所属行社的机构类型的计划
-                    plans = plans.stream().filter(p -> p.getPlanOfOrgType().equals(fofOrgType)).collect(Collectors.toList());
-                    //过滤所属机构为作息变更机构所属行社的机构的计划
-                    SysOrg fofOrgHs = ofhs;
-                    plans = plans.stream().filter(p -> p.getPlanOfOrgId().equals(fofOrgHs.getId())).collect(Collectors.toList());
-                    Iterator<CoreSafecheckPlan> safecheckPlanIterator = plans.iterator();
-                    //遍历计划
-                    while (safecheckPlanIterator.hasNext()) {
-                        //如果存在相等的受检机构,开始重新生成任务
-                        CoreSafecheckPlan plan = safecheckPlanIterator.next();
-                        List<PlanTaskBuildVo> list = new ArrayList<>();
-                        List<CoreSafecheckPlanToExecOrg> execOrg = new ArrayList<>();
-                        List<CoreSafecheckPlanToCheckOrg> checkOrg = new ArrayList<>();
-
-                        //获取执行角色
-                        QueryWrapper<CoreSafecheckPlanToRole> ros = new QueryWrapper<>();
-                        ros.lambda().eq(CoreSafecheckPlanToRole::getPlanId, plan.getId());
-                        List<CoreSafecheckPlanToRole> roles = planToRoleMapper.selectList(ros);
-                        List<SysOrg> execOrgs = null;
-                        //选择了具体执行检查的机构
-                        execOrgs = plan.getExecOrgList();
-                        //如果不存在具体的执行检查的机构就是指定类型,直接拿所属行社
-                        if (CollectionUtil.isEmpty(execOrgs)) {
-                            execOrgs.add(ofhs);
-                        }
-                        //此处循环所有执行检查的机构
-                        for (SysOrg org : execOrgs) {
-                            List<SysOrg> checkOrgs = null;
-                            //选择了具体的受检机构
-                            checkOrgs = plan.getCheckOrgList();
-                            //如果不存在具体的受检机构就是指定类型,直接拿作息变更的机构
-                            if (CollectionUtil.isEmpty(checkOrgs)) {
-                                checkOrgs.add(worg);
+                        Integer fofOrgType = ofType;
+                        //过滤所属机构类型为作息变更机构所属行社的机构类型的计划
+                        plans = plans.stream().filter(p -> p.getPlanOfOrgType().equals(fofOrgType)).collect(Collectors.toList());
+                        //过滤所属机构为作息变更机构所属行社的机构的计划
+                        SysOrg fofOrgHs = ofhs;
+                        plans = plans.stream().filter(p -> p.getPlanOfOrgId().equals(fofOrgHs.getId())).collect(Collectors.toList());
+                        Iterator<CoreSafecheckPlan> safecheckPlanIterator = plans.iterator();
+                        //遍历计划
+                        while (safecheckPlanIterator.hasNext()) {
+                            //如果存在相等的受检机构,开始重新生成任务
+                            CoreSafecheckPlan plan = safecheckPlanIterator.next();
+                            List<PlanTaskBuildVo> list = new ArrayList<>();
+                            List<CoreSafecheckPlanToExecOrg> execOrg = new ArrayList<>();
+                            List<CoreSafecheckPlanToCheckOrg> checkOrg = new ArrayList<>();
+
+                            //获取执行角色
+                            QueryWrapper<CoreSafecheckPlanToRole> ros = new QueryWrapper<>();
+                            ros.lambda().eq(CoreSafecheckPlanToRole::getPlanId, plan.getId());
+                            List<CoreSafecheckPlanToRole> roles = planToRoleMapper.selectList(ros);
+                            List<SysOrg> execOrgs = null;
+                            //选择了具体执行检查的机构
+                            execOrgs = plan.getExecOrgList();
+                            //如果不存在具体的执行检查的机构就是指定类型,直接拿所属行社
+                            if (CollectionUtil.isEmpty(execOrgs)) {
+                                execOrgs.add(ofhs);
                             }
-                            //构建数据
-                            List<PlanTaskBuildVo> bs = getBuild(plan, org, checkOrgs, roles);
-                            list.addAll(bs);
-                        }
-                        //生成具体任务
-                        try {
+                            //此处循环所有执行检查的机构
+                            for (SysOrg org : execOrgs) {
+                                List<SysOrg> checkOrgs = null;
+                                //选择了具体的受检机构
+                                checkOrgs = plan.getCheckOrgList();
+                                //如果不存在具体的受检机构就是指定类型,直接拿作息变更的机构
+                                if (CollectionUtil.isEmpty(checkOrgs)) {
+                                    checkOrgs.add(worg);
+                                }
+                                //构建数据
+                                List<PlanTaskBuildVo> bs = getBuild(plan, org, checkOrgs, roles);
+                                list.addAll(bs);
+                            }
+                            //生成具体任务
                             DateTime datetime = new DateTime();
                             datetime.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
                             buildTask(datetime, list, startDate, endDate, false, 0);
-                        } catch (Exception e) {
-                            e.printStackTrace();
                         }
                     }
+
                 }
 
             }
-
+        } catch (Exception e) {
+            e.printStackTrace();
         }
     }
 

+ 3 - 0
soc-modules/soc-modules-core/src/main/java/com/xunmei/core/safetyCheck/service/impl/SafetyCheckRegisterSericeImpl.java

@@ -227,7 +227,10 @@ public class SafetyCheckRegisterSericeImpl extends ServiceImpl<CoreSafetyTaskMap
         CoreSafecheckPlan plan = null;
         if (ObjectUtil.isNotNull(task.getPlanId())) {
             plan = coreSafecheckPlanMapper.selectById(task.getPlanId());
+        } else {
+          throw  new RuntimeException("计划id不存在");
         }
+
         SysOrg beCheckedOrg = remoteOrgService.selectOrgById(task.getOrgId(), SecurityConstants.INNER);
         if (ObjectUtil.isNull(beCheckedOrg)) {
             throw new ServiceException("受检机构不存在");

+ 7 - 0
soc-modules/soc-modules-file/pom.xml

@@ -70,6 +70,13 @@
             <groupId>cn.hutool</groupId>
             <artifactId>hutool-all</artifactId>
         </dependency>
+
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-text</artifactId>
+            <version>1.8</version>
+        </dependency>
+
         <dependency>
             <groupId>ant</groupId>
             <artifactId>ant</artifactId>

+ 28 - 23
soc-modules/soc-modules-file/src/main/java/com/xunmei/file/service/LocalSysFileServiceImpl.java

@@ -101,20 +101,21 @@ public class LocalSysFileServiceImpl implements ISysFileService {
 
     /**
      * 修复路径操纵bug
+     *
      * @param param
      * @return
      */
-    private static String filterPath(String param){
+    private static String filterPath(String param) {
         Pattern pattern = Pattern.compile("[/\\:*?<>|]");
         Matcher matcher = pattern.matcher(param);
-        param =matcher.replaceAll("");
+        param = matcher.replaceAll("");
         return param;
     }
 
-    private static String filterHeader(String param){
+    private static String filterHeader(String param) {
         Pattern pattern = Pattern.compile("[/\\:*?<>|=\\r\\n]");
         Matcher matcher = pattern.matcher(param);
-        param =matcher.replaceAll("");
+        param = matcher.replaceAll("");
         return param;
     }
 
@@ -170,7 +171,9 @@ public class LocalSysFileServiceImpl implements ISysFileService {
             e.printStackTrace();
         } finally {
             try {
-                out.close();
+                if (out != null) {
+                    out.close();
+                }
             } catch (IOException e) {
                 e.printStackTrace();
             }
@@ -638,8 +641,8 @@ public class LocalSysFileServiceImpl implements ISysFileService {
             response.setContentType("application/octet-stream");
             response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
             List<PdfToZipTempVo> pdfToZipTempVoList = registerBookPdfList.parallelStream().map(pdf -> {
-                        return resolve(pdf, count);
-                    }).filter(Objects::nonNull)
+                return resolve(pdf, count);
+            }).filter(Objects::nonNull)
                     .collect(Collectors.toList());
             count.await();
             pdfToZipTempVoList.removeIf(pdfToZipTempVo -> !FileUtil.exist(pdfToZipTempVo.getFile()));
@@ -682,7 +685,7 @@ public class LocalSysFileServiceImpl implements ISysFileService {
             final String pdfFileName = pdf.getFileName();
             //pdfFileName==null的时候在下面会报错此处加个判断,要处理问题还需要在问题源头除处理
             // registerBookPdfBatchExportTempDir (Is a directory)
-            if(StringUtils.isEmpty(pdfFileName)){
+            if (StringUtils.isEmpty(pdfFileName)) {
                 return null;
             }
             final PdfToZipTempVo tempVo = new PdfToZipTempVo();
@@ -762,17 +765,18 @@ public class LocalSysFileServiceImpl implements ISysFileService {
         //判断需要分几片导出
         List<List<CoreRegisterBookPdfPageVo>> lists = checkSubList(pdfDto);
         int num = 1;
-        for (List<CoreRegisterBookPdfPageVo> list : lists) {
-            CountDownLatch count = new CountDownLatch(list.size());
-            String zipName = null;
-            try {
+        try {
+            for (List<CoreRegisterBookPdfPageVo> list : lists) {
+                CountDownLatch count = new CountDownLatch(list.size());
+                String zipName = null;
+
                 String str = lists.size() == 1 ? "" : "_part_" + num;
                 String fileNameStr = fileName + DateHelper.getDateString(new Date()) + str;
                 zipName = URLEncoder.encode(fileNameStr + ".zip", "UTF-8");
 
                 List<PdfToZipTempVo> pdfToZipTempVoList = list.parallelStream().map(pdf -> {
-                            return resolve(pdf, count);
-                        }).filter(Objects::nonNull)
+                    return resolve(pdf, count);
+                }).filter(Objects::nonNull)
                         .collect(Collectors.toList());
                 pdfToZipTempVoList.removeIf(pdfToZipTempVo -> !FileUtil.exist(pdfToZipTempVo.getFile()));
                 log.info("登记簿全部下载完成,开始压缩文件,数量:{}", pdfToZipTempVoList.size());
@@ -792,13 +796,14 @@ public class LocalSysFileServiceImpl implements ISysFileService {
                 fos.close();
                 num++;
                 saveFileDataToRedis(org, date, zipName, filePath, fileSize, pdfDto);
-            } catch (Throwable e) {
-                throw new RuntimeException(e);
-            } finally {
-                File file = new File(TEMP_DIR_NAME);
-                if (file.exists()) {
-                    FileUtil.del(file);
-                }
+
+            }
+        } catch (Throwable e) {
+            throw new RuntimeException(e);
+        } finally {
+            File file = new File(TEMP_DIR_NAME);
+            if (file.exists()) {
+                FileUtil.del(file);
             }
         }
 
@@ -818,10 +823,10 @@ public class LocalSysFileServiceImpl implements ISysFileService {
         pdfLocalFileTempVo.setCreateTime(new Date());
         //此处localFileName 为文件的绝对路径,存在redis延迟队列中,一个小时后删除文件
         delayedQueue.addQueueHours(pdfLocalFileTempVo.getLocalFileName(), 1, RegisterBookFileExpirationListener.class);
-        localFileName = localFileName.replace(this.localFilePath+File.separator, "");
+        localFileName = localFileName.replace(this.localFilePath + File.separator, "");
         //此处localFileName 为文件名称,存入redis中,用于页面展示文件名称,下载
         //RedisUtils.setCacheObject(URLDecoder.decode(localFileName, "UTF-8"), JSON.toJSONString(pdfLocalFileTempVo),true);
-        RedisUtils.setCacheObject(URLDecoder.decode(localFileName, "UTF-8"), JSON.toJSONString(pdfLocalFileTempVo), Duration.ofMillis(3500*1000L));
+        RedisUtils.setCacheObject(URLDecoder.decode(localFileName, "UTF-8"), JSON.toJSONString(pdfLocalFileTempVo), Duration.ofMillis(3500 * 1000L));
     }
 
     private List<List<CoreRegisterBookPdfPageVo>> checkSubList(CoreRegisterBookPdfExportDto pdfDto) {

+ 5 - 6
soc-modules/soc-modules-file/src/main/java/com/xunmei/file/utils/FileUploadUtils.java

@@ -2,8 +2,6 @@ package com.xunmei.file.utils;
 
 import cn.hutool.core.codec.Base64;
 import cn.hutool.core.io.FileUtil;
-import cn.hutool.core.io.file.FileNameUtil;
-import cn.hutool.core.lang.UUID;
 import com.xunmei.common.core.exception.file.FileException;
 import com.xunmei.common.core.exception.file.FileNameLengthLimitExceededException;
 import com.xunmei.common.core.exception.file.FileSizeLimitExceededException;
@@ -13,9 +11,8 @@ import com.xunmei.common.core.utils.StringUtils;
 import com.xunmei.common.core.utils.file.FileTypeUtils;
 import com.xunmei.common.core.utils.file.MimeTypeUtils;
 import com.xunmei.common.core.utils.uuid.Seq;
-import com.xunmei.file.controller.SysFileController;
 import com.xunmei.file.vo.FileBase64Vo;
-import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.text.StringEscapeUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.web.multipart.MultipartFile;
@@ -155,12 +152,14 @@ public class FileUploadUtils
     public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
     {
         File desc = new File(uploadDir + File.separator + fileName);
-        log.info("当前上传文件地址:{}",desc.getAbsolutePath());
+        String path = StringEscapeUtils.escapeEcmaScript(desc.getAbsolutePath());
+        String file = StringEscapeUtils.escapeEcmaScript(desc.getParentFile().getName());
+        log.info("当前上传文件地址:{}",path);
         if (!desc.exists())
         {
             if (!desc.getParentFile().exists())
             {
-                log.info("创建文件夹:{}",desc.getParentFile());
+                log.info("创建文件夹:{}",file);
                 desc.getParentFile().mkdirs();
             }
         }

+ 8 - 30
soc-modules/soc-modules-file/src/main/java/com/xunmei/file/utils/PdfUtil.java

@@ -215,7 +215,7 @@ public class PdfUtil {
         names.add("营业终了");
 
 
-        for(String s:names){
+        for (String s : names) {
             List<LinkedHashMap<String, Object>> lists = (List<LinkedHashMap<String, Object>>) data.get(s);
             if (ObjectUtil.isEmpty(lists)) {
                 continue;
@@ -248,7 +248,6 @@ public class PdfUtil {
         document.add(foot);
 
 
-
     }
 
     public static String getLineStr(String str) {
@@ -342,27 +341,6 @@ public class PdfUtil {
     }
 
 
-    public static Image getImage(String image) throws Exception {
-        Image imageData = null;
-        if (image.contains("black.png")) {
-            final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
-            final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
-            imageData = Image.getInstance(resources[0].getURL());
-        } else {
-            try {
-                imageData = convertFileToByteArray(new File(image));
-            } catch (IOException e) {
-                //此处如果未能读取到图片则放弃,选择使用空白图片来填充,继续生成pdf
-                log.error("读取图片失败,图片路径:{}", image);
-                final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
-                final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
-                imageData = Image.getInstance(resources[0].getURL());
-            }
-        }
-        imageData.scaleAbsolute(100, 100);
-        return imageData;
-    }
-
     private static PdfPTable getImage(List<String> images, int totalImages) throws Exception {
         if (images == null) {
             images = new ArrayList<>();
@@ -381,17 +359,14 @@ public class PdfUtil {
             rows.add(row);
         }
 
+
         for (List<String> row : rows) {
             for (String image : row) {
                 Image imageData = null;
-                try {
-                    imageData = getImage(image);
-                } catch (Exception e) {
-                    final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
-                    final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
-                    imageData = Image.getInstance(resources[0].getURL());
+                imageData = convertFileToByteArray(new File(image));
+                if(imageData != null ){
+                    imageData.scaleAbsolute(100, 100);
                 }
-                imageData.scaleAbsolute(100, 100);
                 PdfPCell cell = new PdfPCell(imageData);
                 cell.setBorder(Rectangle.NO_BORDER);
                 cell.setHorizontalAlignment(Element.ALIGN_CENTER);
@@ -433,6 +408,9 @@ public class PdfUtil {
         try {
             final ApplicationContext applicationContext = SpringUtil.getApplicationContext();
             final Resource[] resources = applicationContext.getResources("classpath:file/black.png");
+            if(resources == null || resources.length == 0){
+                return null;
+            }
             return Image.getInstance(resources[0].getURL());
         } catch (IOException | BadElementException e) {
             throw new RuntimeException(e);

+ 3 - 0
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysDeptServiceImpl.java

@@ -221,6 +221,9 @@ public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> impl
                 excludeOrg = first.get();
             }
         }
+        if(excludeOrg == null){
+            return null;
+        }
 
         for (SysOrgVO org : cacheList) {
             String path = org.getPath();

+ 10 - 5
soc-modules/soc-modules-system/src/main/java/com/xunmei/system/service/impl/SysUserServiceImpl.java

@@ -595,9 +595,11 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
         StringBuilder successMsg = new StringBuilder();
         StringBuilder failureMsg = new StringBuilder();
         String password = configService.selectConfigByKey("sys.user.initPassword");
-        for (SysUser user : userList) {
-            try {
-                // 验证是否存在这个用户
+        SysUser us = null;
+        try {
+            // 验证是否存在这个用户
+            for (SysUser user : userList) {
+                us = user;
                 SysUser u = userMapper.selectUserByUserName(user.getUsername());
                 if (StringUtils.isNull(u)) {
                     BeanValidators.validateWithException(validator, user);
@@ -619,12 +621,15 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
                     failureNum++;
                     failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUsername() + " 已存在");
                 }
-            } catch (Exception e) {
+            }
+        } catch (Exception e) {
+            if (us != null) {
                 failureNum++;
-                String msg = "<br/>" + failureNum + "、账号 " + user.getUsername() + " 导入失败:";
+                String msg = "<br/>" + failureNum + "、账号 " + us.getUsername() + " 导入失败:";
                 failureMsg.append(msg + e.getMessage());
                 log.error(msg, e);
             }
+
         }
         if (failureNum > 0) {
             failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:");