Browse Source

update 优化 使用 hutool 替换 ruoyi 自带工具类 解决部分方法过期与高版本JDK不兼容问题

疯狂的狮子li 4 years ago
parent
commit
b3541e9758

+ 3 - 3
ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java

@@ -54,10 +54,10 @@ public class CommonController
 
             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
             FileUtils.setAttachmentResponseHeader(response, realFileName);
-            FileUtils.writeBytes(filePath, response.getOutputStream());
+			FileUtils.writeToStream(filePath, response.getOutputStream());
             if (delete)
             {
-                FileUtils.deleteFile(filePath);
+				FileUtils.del(filePath);
             }
         }
         catch (Exception e)
@@ -111,7 +111,7 @@ public class CommonController
             String downloadName = StrUtil.subAfter(downloadPath, "/",true);
             response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
             FileUtils.setAttachmentResponseHeader(response, downloadName);
-            FileUtils.writeBytes(downloadPath, response.getOutputStream());
+            FileUtils.writeToStream(downloadPath, response.getOutputStream());
         }
         catch (Exception e)
         {

+ 77 - 75
ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatedlyRequestWrapper.java

@@ -1,75 +1,77 @@
-package com.ruoyi.common.filter;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import javax.servlet.ReadListener;
-import javax.servlet.ServletInputStream;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-import com.ruoyi.common.utils.http.HttpHelper;
-
-/**
- * 构建可重复读取inputStream的request
- * 
- * @author ruoyi
- */
-public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper
-{
-    private final byte[] body;
-
-    public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException
-    {
-        super(request);
-        request.setCharacterEncoding("UTF-8");
-        response.setCharacterEncoding("UTF-8");
-
-        body = HttpHelper.getBodyString(request).getBytes("UTF-8");
-    }
-
-    @Override
-    public BufferedReader getReader() throws IOException
-    {
-        return new BufferedReader(new InputStreamReader(getInputStream()));
-    }
-
-    @Override
-    public ServletInputStream getInputStream() throws IOException
-    {
-        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
-        return new ServletInputStream()
-        {
-            @Override
-            public int read() throws IOException
-            {
-                return bais.read();
-            }
-
-            @Override
-            public int available() throws IOException
-            {
-                return body.length;
-            }
-
-            @Override
-            public boolean isFinished()
-            {
-                return false;
-            }
-
-            @Override
-            public boolean isReady()
-            {
-                return false;
-            }
-
-            @Override
-            public void setReadListener(ReadListener readListener)
-            {
-
-            }
-        };
-    }
-}
+package com.ruoyi.common.filter;
+
+import cn.hutool.core.io.IoUtil;
+
+import javax.servlet.ReadListener;
+import javax.servlet.ServletInputStream;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * 构建可重复读取inputStream的request
+ *
+ * @author ruoyi
+ */
+public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper
+{
+    private final byte[] body;
+
+    public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException
+    {
+        super(request);
+        request.setCharacterEncoding("UTF-8");
+        response.setCharacterEncoding("UTF-8");
+
+        body = IoUtil.readUtf8(request.getInputStream()).getBytes(StandardCharsets.UTF_8);
+    }
+
+    @Override
+    public BufferedReader getReader() throws IOException
+    {
+        return new BufferedReader(new InputStreamReader(getInputStream()));
+    }
+
+    @Override
+    public ServletInputStream getInputStream() throws IOException
+    {
+        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
+        return new ServletInputStream()
+        {
+            @Override
+            public int read() throws IOException
+            {
+                return bais.read();
+            }
+
+            @Override
+            public int available() throws IOException
+            {
+                return body.length;
+            }
+
+            @Override
+            public boolean isFinished()
+            {
+                return false;
+            }
+
+            @Override
+            public boolean isReady()
+            {
+                return false;
+            }
+
+            @Override
+            public void setReadListener(ReadListener readListener)
+            {
+
+            }
+        };
+    }
+}

+ 5 - 3
ruoyi-common/src/main/java/com/ruoyi/common/filter/XssHttpServletRequestWrapper.java

@@ -1,9 +1,9 @@
 package com.ruoyi.common.filter;
 
+import cn.hutool.core.io.IoUtil;
 import cn.hutool.core.lang.Validator;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.http.HtmlUtil;
-import org.apache.commons.io.IOUtils;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.MediaType;
 
@@ -13,6 +13,7 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletRequestWrapper;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 
 /**
  * XSS过滤处理
@@ -57,7 +58,7 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper
         }
 
         // 为空,直接返回
-        String json = IOUtils.toString(super.getInputStream(), "utf-8");
+        String json = IoUtil.read(super.getInputStream(), StandardCharsets.UTF_8);
         if (Validator.isEmpty(json))
         {
             return super.getInputStream();
@@ -65,7 +66,8 @@ public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper
 
         // xss过滤
         json = HtmlUtil.cleanHtmlTag(json).trim();
-        final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
+
+        final ByteArrayInputStream bis = IoUtil.toStream(json, StandardCharsets.UTF_8);
         return new ServletInputStream()
         {
             @Override

+ 112 - 120
ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java

@@ -2,6 +2,9 @@ package com.ruoyi.common.utils;
 
 import cn.hutool.core.convert.Convert;
 import cn.hutool.core.util.StrUtil;
+import cn.hutool.extra.servlet.ServletUtil;
+import cn.hutool.http.HttpStatus;
+import org.springframework.http.MediaType;
 import org.springframework.web.context.request.RequestAttributes;
 import org.springframework.web.context.request.RequestContextHolder;
 import org.springframework.web.context.request.ServletRequestAttributes;
@@ -10,129 +13,118 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 import java.io.IOException;
+import java.nio.charset.StandardCharsets;
 
 /**
  * 客户端工具类
- * 
+ *
  * @author ruoyi
  */
-public class ServletUtils
-{
-    /**
-     * 获取String参数
-     */
-    public static String getParameter(String name)
-    {
-        return getRequest().getParameter(name);
-    }
-
-    /**
-     * 获取String参数
-     */
-    public static String getParameter(String name, String defaultValue)
-    {
-        return Convert.toStr(getRequest().getParameter(name), defaultValue);
-    }
-
-    /**
-     * 获取Integer参数
-     */
-    public static Integer getParameterToInt(String name)
-    {
-        return Convert.toInt(getRequest().getParameter(name));
-    }
-
-    /**
-     * 获取Integer参数
-     */
-    public static Integer getParameterToInt(String name, Integer defaultValue)
-    {
-        return Convert.toInt(getRequest().getParameter(name), defaultValue);
-    }
-
-    /**
-     * 获取request
-     */
-    public static HttpServletRequest getRequest()
-    {
-        return getRequestAttributes().getRequest();
-    }
-
-    /**
-     * 获取response
-     */
-    public static HttpServletResponse getResponse()
-    {
-        return getRequestAttributes().getResponse();
-    }
-
-    /**
-     * 获取session
-     */
-    public static HttpSession getSession()
-    {
-        return getRequest().getSession();
-    }
-
-    public static ServletRequestAttributes getRequestAttributes()
-    {
-        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
-        return (ServletRequestAttributes) attributes;
-    }
-
-    /**
-     * 将字符串渲染到客户端
-     * 
-     * @param response 渲染对象
-     * @param string 待渲染的字符串
-     * @return null
-     */
-    public static String renderString(HttpServletResponse response, String string)
-    {
-        try
-        {
-            response.setStatus(200);
-            response.setContentType("application/json");
-            response.setCharacterEncoding("utf-8");
-            response.getWriter().print(string);
-        }
-        catch (IOException e)
-        {
-            e.printStackTrace();
-        }
-        return null;
-    }
-
-    /**
-     * 是否是Ajax异步请求
-     * 
-     * @param request
-     */
-    public static boolean isAjaxRequest(HttpServletRequest request)
-    {
-        String accept = request.getHeader("accept");
-        if (accept != null && accept.indexOf("application/json") != -1)
-        {
-            return true;
-        }
-
-        String xRequestedWith = request.getHeader("X-Requested-With");
-        if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1)
-        {
-            return true;
-        }
-
-        String uri = request.getRequestURI();
-        if (StrUtil.equalsAnyIgnoreCase(uri, ".json", ".xml"))
-        {
-            return true;
-        }
-
-        String ajax = request.getParameter("__ajax");
-        if (StrUtil.equalsAnyIgnoreCase(ajax, "json", "xml"))
-        {
-            return true;
-        }
-        return false;
-    }
+public class ServletUtils extends ServletUtil {
+	/**
+	 * 获取String参数
+	 */
+	public static String getParameter(String name) {
+		return getRequest().getParameter(name);
+	}
+
+	/**
+	 * 获取String参数
+	 */
+	public static String getParameter(String name, String defaultValue) {
+		return Convert.toStr(getRequest().getParameter(name), defaultValue);
+	}
+
+	/**
+	 * 获取Integer参数
+	 */
+	public static Integer getParameterToInt(String name) {
+		return Convert.toInt(getRequest().getParameter(name));
+	}
+
+	/**
+	 * 获取Integer参数
+	 */
+	public static Integer getParameterToInt(String name, Integer defaultValue) {
+		return Convert.toInt(getRequest().getParameter(name), defaultValue);
+	}
+
+	/**
+	 * 获取request
+	 */
+	public static HttpServletRequest getRequest() {
+		return getRequestAttributes().getRequest();
+	}
+
+	/**
+	 * 获取response
+	 */
+	public static HttpServletResponse getResponse() {
+		return getRequestAttributes().getResponse();
+	}
+
+	/**
+	 * 获取session
+	 */
+	public static HttpSession getSession() {
+		return getRequest().getSession();
+	}
+
+	public static ServletRequestAttributes getRequestAttributes() {
+		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
+		return (ServletRequestAttributes) attributes;
+	}
+
+	/**
+	 * 将字符串渲染到客户端
+	 *
+	 * @param response 渲染对象
+	 * @param string   待渲染的字符串
+	 * @return null
+	 */
+	public static String renderString(HttpServletResponse response, String string) {
+		try {
+			response.setStatus(HttpStatus.HTTP_OK);
+			response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+			response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
+			response.getWriter().print(string);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+		return null;
+	}
+
+	/**
+	 * 是否是Ajax异步请求
+	 *
+	 * @param request
+	 */
+	public static boolean isAjaxRequest(HttpServletRequest request) {
+
+		String accept = request.getHeader("accept");
+		if (accept != null && accept.indexOf("application/json") != -1) {
+			return true;
+		}
+
+		String xRequestedWith = request.getHeader("X-Requested-With");
+		if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
+			return true;
+		}
+
+		String uri = request.getRequestURI();
+		if (StrUtil.equalsAnyIgnoreCase(uri, ".json", ".xml")) {
+			return true;
+		}
+
+		String ajax = request.getParameter("__ajax");
+		if (StrUtil.equalsAnyIgnoreCase(ajax, "json", "xml")) {
+			return true;
+		}
+		return false;
+	}
+
+	public static String getClientIP() {
+		return getClientIP(getRequest());
+	}
+
 }

+ 8 - 82
ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java

@@ -1,5 +1,6 @@
 package com.ruoyi.common.utils.file;
 
+import cn.hutool.core.io.FileUtil;
 import cn.hutool.core.util.ArrayUtil;
 import cn.hutool.core.util.StrUtil;
 
@@ -11,91 +12,16 @@ import java.nio.charset.StandardCharsets;
 
 /**
  * 文件处理工具类
- * 
+ *
  * @author ruoyi
  */
-public class FileUtils extends org.apache.commons.io.FileUtils
+public class FileUtils extends FileUtil
 {
     public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
 
-    /**
-     * 输出指定文件的byte数组
-     * 
-     * @param filePath 文件路径
-     * @param os 输出流
-     * @return
-     */
-    public static void writeBytes(String filePath, OutputStream os) throws IOException
-    {
-        FileInputStream fis = null;
-        try
-        {
-            File file = new File(filePath);
-            if (!file.exists())
-            {
-                throw new FileNotFoundException(filePath);
-            }
-            fis = new FileInputStream(file);
-            byte[] b = new byte[1024];
-            int length;
-            while ((length = fis.read(b)) > 0)
-            {
-                os.write(b, 0, length);
-            }
-        }
-        catch (IOException e)
-        {
-            throw e;
-        }
-        finally
-        {
-            if (os != null)
-            {
-                try
-                {
-                    os.close();
-                }
-                catch (IOException e1)
-                {
-                    e1.printStackTrace();
-                }
-            }
-            if (fis != null)
-            {
-                try
-                {
-                    fis.close();
-                }
-                catch (IOException e1)
-                {
-                    e1.printStackTrace();
-                }
-            }
-        }
-    }
-
-    /**
-     * 删除文件
-     * 
-     * @param filePath 文件
-     * @return
-     */
-    public static boolean deleteFile(String filePath)
-    {
-        boolean flag = false;
-        File file = new File(filePath);
-        // 路径为文件且不为空则进行删除
-        if (file.isFile() && file.exists())
-        {
-            file.delete();
-            flag = true;
-        }
-        return flag;
-    }
-
     /**
      * 文件名称验证
-     * 
+     *
      * @param filename 文件名称
      * @return true 正常 false 非法
      */
@@ -130,7 +56,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils
 
     /**
      * 下载文件名重新编码
-     * 
+     *
      * @param request 请求对象
      * @param fileName 文件名
      * @return 编码后的文件名
@@ -142,7 +68,7 @@ public class FileUtils extends org.apache.commons.io.FileUtils
         if (agent.contains("MSIE"))
         {
             // IE浏览器
-            filename = URLEncoder.encode(filename, "utf-8");
+            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
             filename = filename.replace("+", " ");
         }
         else if (agent.contains("Firefox"))
@@ -153,12 +79,12 @@ public class FileUtils extends org.apache.commons.io.FileUtils
         else if (agent.contains("Chrome"))
         {
             // google浏览器
-            filename = URLEncoder.encode(filename, "utf-8");
+            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
         }
         else
         {
             // 其它浏览器
-            filename = URLEncoder.encode(filename, "utf-8");
+            filename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
         }
         return filename;
     }

+ 0 - 56
ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpHelper.java

@@ -1,56 +0,0 @@
-package com.ruoyi.common.utils.http;
-
-import cn.hutool.core.exceptions.ExceptionUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.servlet.ServletRequest;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.nio.charset.Charset;
-
-/**
- * 通用http工具封装
- * 
- * @author ruoyi
- */
-public class HttpHelper
-{
-    private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class);
-
-    public static String getBodyString(ServletRequest request)
-    {
-        StringBuilder sb = new StringBuilder();
-        BufferedReader reader = null;
-        try (InputStream inputStream = request.getInputStream())
-        {
-            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
-            String line = "";
-            while ((line = reader.readLine()) != null)
-            {
-                sb.append(line);
-            }
-        }
-        catch (IOException e)
-        {
-            LOGGER.warn("getBodyString出现问题!");
-        }
-        finally
-        {
-            if (reader != null)
-            {
-                try
-                {
-                    reader.close();
-                }
-                catch (IOException e)
-                {
-                    LOGGER.error(ExceptionUtil.getMessage(e));
-                }
-            }
-        }
-        return sb.toString();
-    }
-}

+ 0 - 262
ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java

@@ -1,262 +0,0 @@
-package com.ruoyi.common.utils.http;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.net.ConnectException;
-import java.net.SocketTimeoutException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.cert.X509Certificate;
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.ruoyi.common.constant.Constants;
-
-/**
- * 通用http发送方法
- * 
- * @author ruoyi
- */
-public class HttpUtils
-{
-    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
-
-    /**
-     * 向指定 URL 发送GET方法的请求
-     *
-     * @param url 发送请求的 URL
-     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
-     * @return 所代表远程资源的响应结果
-     */
-    public static String sendGet(String url, String param)
-    {
-        return sendGet(url, param, Constants.UTF8);
-    }
-
-    /**
-     * 向指定 URL 发送GET方法的请求
-     *
-     * @param url 发送请求的 URL
-     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
-     * @param contentType 编码类型
-     * @return 所代表远程资源的响应结果
-     */
-    public static String sendGet(String url, String param, String contentType)
-    {
-        StringBuilder result = new StringBuilder();
-        BufferedReader in = null;
-        try
-        {
-            String urlNameString = url + "?" + param;
-            log.info("sendGet - {}", urlNameString);
-            URL realUrl = new URL(urlNameString);
-            URLConnection connection = realUrl.openConnection();
-            connection.setRequestProperty("accept", "*/*");
-            connection.setRequestProperty("connection", "Keep-Alive");
-            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
-            connection.connect();
-            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
-            String line;
-            while ((line = in.readLine()) != null)
-            {
-                result.append(line);
-            }
-            log.info("recv - {}", result);
-        }
-        catch (ConnectException e)
-        {
-            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
-        }
-        catch (SocketTimeoutException e)
-        {
-            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
-        }
-        catch (IOException e)
-        {
-            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
-        }
-        catch (Exception e)
-        {
-            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
-        }
-        finally
-        {
-            try
-            {
-                if (in != null)
-                {
-                    in.close();
-                }
-            }
-            catch (Exception ex)
-            {
-                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
-            }
-        }
-        return result.toString();
-    }
-
-    /**
-     * 向指定 URL 发送POST方法的请求
-     *
-     * @param url 发送请求的 URL
-     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
-     * @return 所代表远程资源的响应结果
-     */
-    public static String sendPost(String url, String param)
-    {
-        PrintWriter out = null;
-        BufferedReader in = null;
-        StringBuilder result = new StringBuilder();
-        try
-        {
-            String urlNameString = url;
-            log.info("sendPost - {}", urlNameString);
-            URL realUrl = new URL(urlNameString);
-            URLConnection conn = realUrl.openConnection();
-            conn.setRequestProperty("accept", "*/*");
-            conn.setRequestProperty("connection", "Keep-Alive");
-            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
-            conn.setRequestProperty("Accept-Charset", "utf-8");
-            conn.setRequestProperty("contentType", "utf-8");
-            conn.setDoOutput(true);
-            conn.setDoInput(true);
-            out = new PrintWriter(conn.getOutputStream());
-            out.print(param);
-            out.flush();
-            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
-            String line;
-            while ((line = in.readLine()) != null)
-            {
-                result.append(line);
-            }
-            log.info("recv - {}", result);
-        }
-        catch (ConnectException e)
-        {
-            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
-        }
-        catch (SocketTimeoutException e)
-        {
-            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
-        }
-        catch (IOException e)
-        {
-            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
-        }
-        catch (Exception e)
-        {
-            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
-        }
-        finally
-        {
-            try
-            {
-                if (out != null)
-                {
-                    out.close();
-                }
-                if (in != null)
-                {
-                    in.close();
-                }
-            }
-            catch (IOException ex)
-            {
-                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
-            }
-        }
-        return result.toString();
-    }
-
-    public static String sendSSLPost(String url, String param)
-    {
-        StringBuilder result = new StringBuilder();
-        String urlNameString = url + "?" + param;
-        try
-        {
-            log.info("sendSSLPost - {}", urlNameString);
-            SSLContext sc = SSLContext.getInstance("SSL");
-            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
-            URL console = new URL(urlNameString);
-            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
-            conn.setRequestProperty("accept", "*/*");
-            conn.setRequestProperty("connection", "Keep-Alive");
-            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
-            conn.setRequestProperty("Accept-Charset", "utf-8");
-            conn.setRequestProperty("contentType", "utf-8");
-            conn.setDoOutput(true);
-            conn.setDoInput(true);
-
-            conn.setSSLSocketFactory(sc.getSocketFactory());
-            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
-            conn.connect();
-            InputStream is = conn.getInputStream();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is));
-            String ret = "";
-            while ((ret = br.readLine()) != null)
-            {
-                if (ret != null && !"".equals(ret.trim()))
-                {
-                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
-                }
-            }
-            log.info("recv - {}", result);
-            conn.disconnect();
-            br.close();
-        }
-        catch (ConnectException e)
-        {
-            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
-        }
-        catch (SocketTimeoutException e)
-        {
-            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
-        }
-        catch (IOException e)
-        {
-            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
-        }
-        catch (Exception e)
-        {
-            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
-        }
-        return result.toString();
-    }
-
-    private static class TrustAnyTrustManager implements X509TrustManager
-    {
-        @Override
-        public void checkClientTrusted(X509Certificate[] chain, String authType)
-        {
-        }
-
-        @Override
-        public void checkServerTrusted(X509Certificate[] chain, String authType)
-        {
-        }
-
-        @Override
-        public X509Certificate[] getAcceptedIssuers()
-        {
-            return new X509Certificate[] {};
-        }
-    }
-
-    private static class TrustAnyHostnameVerifier implements HostnameVerifier
-    {
-        @Override
-        public boolean verify(String hostname, SSLSession session)
-        {
-            return true;
-        }
-    }
-}

+ 36 - 41
ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java

@@ -1,56 +1,51 @@
 package com.ruoyi.common.utils.ip;
 
+import cn.hutool.core.net.NetUtil;
 import cn.hutool.core.util.StrUtil;
+import cn.hutool.http.HttpUtil;
 import com.alibaba.fastjson.JSONObject;
 import com.ruoyi.common.config.RuoYiConfig;
 import com.ruoyi.common.constant.Constants;
-import com.ruoyi.common.utils.http.HttpUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import lombok.extern.slf4j.Slf4j;
 
 /**
  * 获取地址类
- * 
+ *
  * @author ruoyi
  */
-public class AddressUtils
-{
-    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);
+@Slf4j
+public class AddressUtils {
 
-    // IP地址查询
-    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
+	// IP地址查询
+	public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
 
-    // 未知地址
-    public static final String UNKNOWN = "XX XX";
+	// 未知地址
+	public static final String UNKNOWN = "XX XX";
 
-    public static String getRealAddressByIP(String ip)
-    {
-        String address = UNKNOWN;
-        // 内网不查询
-        if (IpUtils.internalIp(ip))
-        {
-            return "内网IP";
-        }
-        if (RuoYiConfig.isAddressEnabled())
-        {
-            try
-            {
-                String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK);
-                if (StrUtil.isEmpty(rspStr))
-                {
-                    log.error("获取地理位置异常 {}", ip);
-                    return UNKNOWN;
-                }
-                JSONObject obj = JSONObject.parseObject(rspStr);
-                String region = obj.getString("pro");
-                String city = obj.getString("city");
-                return String.format("%s %s", region, city);
-            }
-            catch (Exception e)
-            {
-                log.error("获取地理位置异常 {}", ip);
-            }
-        }
-        return address;
-    }
+	public static String getRealAddressByIP(String ip) {
+		String address = UNKNOWN;
+		// 内网不查询
+		if (NetUtil.isInnerIP(ip)) {
+			return "内网IP";
+		}
+		if (RuoYiConfig.isAddressEnabled()) {
+			try {
+				String rspStr = HttpUtil.createGet(IP_URL)
+					.body("ip=" + ip + "&json=true", Constants.GBK)
+					.execute()
+					.body();
+				if (StrUtil.isEmpty(rspStr)) {
+					log.error("获取地理位置异常 {}", ip);
+					return UNKNOWN;
+				}
+				JSONObject obj = JSONObject.parseObject(rspStr);
+				String region = obj.getString("pro");
+				String city = obj.getString("city");
+				return String.format("%s %s", region, city);
+			} catch (Exception e) {
+				log.error("获取地理位置异常 {}", ip);
+			}
+		}
+		return address;
+	}
 }

+ 0 - 196
ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/IpUtils.java

@@ -1,196 +0,0 @@
-package com.ruoyi.common.utils.ip;
-
-import cn.hutool.core.lang.Validator;
-import cn.hutool.http.HtmlUtil;
-
-import javax.servlet.http.HttpServletRequest;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * 获取IP方法
- * 
- * @author ruoyi
- */
-public class IpUtils
-{
-    public static String getIpAddr(HttpServletRequest request)
-    {
-        if (request == null)
-        {
-            return "unknown";
-        }
-        String ip = request.getHeader("x-forwarded-for");
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
-        {
-            ip = request.getHeader("Proxy-Client-IP");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
-        {
-            ip = request.getHeader("X-Forwarded-For");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
-        {
-            ip = request.getHeader("WL-Proxy-Client-IP");
-        }
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
-        {
-            ip = request.getHeader("X-Real-IP");
-        }
-
-        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
-        {
-            ip = request.getRemoteAddr();
-        }
-        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
-    }
-
-    public static boolean internalIp(String ip)
-    {
-        byte[] addr = textToNumericFormatV4(ip);
-        return internalIp(addr) || "127.0.0.1".equals(ip);
-    }
-
-    private static boolean internalIp(byte[] addr)
-    {
-        if (Validator.isNull(addr) || addr.length < 2)
-        {
-            return true;
-        }
-        final byte b0 = addr[0];
-        final byte b1 = addr[1];
-        // 10.x.x.x/8
-        final byte SECTION_1 = 0x0A;
-        // 172.16.x.x/12
-        final byte SECTION_2 = (byte) 0xAC;
-        final byte SECTION_3 = (byte) 0x10;
-        final byte SECTION_4 = (byte) 0x1F;
-        // 192.168.x.x/16
-        final byte SECTION_5 = (byte) 0xC0;
-        final byte SECTION_6 = (byte) 0xA8;
-        switch (b0)
-        {
-            case SECTION_1:
-                return true;
-            case SECTION_2:
-                if (b1 >= SECTION_3 && b1 <= SECTION_4)
-                {
-                    return true;
-                }
-            case SECTION_5:
-                switch (b1)
-                {
-                    case SECTION_6:
-                        return true;
-                }
-            default:
-                return false;
-        }
-    }
-
-    /**
-     * 将IPv4地址转换成字节
-     * 
-     * @param text IPv4地址
-     * @return byte 字节
-     */
-    public static byte[] textToNumericFormatV4(String text)
-    {
-        if (text.length() == 0)
-        {
-            return null;
-        }
-
-        byte[] bytes = new byte[4];
-        String[] elements = text.split("\\.", -1);
-        try
-        {
-            long l;
-            int i;
-            switch (elements.length)
-            {
-                case 1:
-                    l = Long.parseLong(elements[0]);
-                    if ((l < 0L) || (l > 4294967295L)) {
-                        return null;
-                    }
-                    bytes[0] = (byte) (int) (l >> 24 & 0xFF);
-                    bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
-                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
-                    bytes[3] = (byte) (int) (l & 0xFF);
-                    break;
-                case 2:
-                    l = Integer.parseInt(elements[0]);
-                    if ((l < 0L) || (l > 255L)) {
-                        return null;
-                    }
-                    bytes[0] = (byte) (int) (l & 0xFF);
-                    l = Integer.parseInt(elements[1]);
-                    if ((l < 0L) || (l > 16777215L)) {
-                        return null;
-                    }
-                    bytes[1] = (byte) (int) (l >> 16 & 0xFF);
-                    bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
-                    bytes[3] = (byte) (int) (l & 0xFF);
-                    break;
-                case 3:
-                    for (i = 0; i < 2; ++i)
-                    {
-                        l = Integer.parseInt(elements[i]);
-                        if ((l < 0L) || (l > 255L)) {
-                            return null;
-                        }
-                        bytes[i] = (byte) (int) (l & 0xFF);
-                    }
-                    l = Integer.parseInt(elements[2]);
-                    if ((l < 0L) || (l > 65535L)) {
-                        return null;
-                    }
-                    bytes[2] = (byte) (int) (l >> 8 & 0xFF);
-                    bytes[3] = (byte) (int) (l & 0xFF);
-                    break;
-                case 4:
-                    for (i = 0; i < 4; ++i)
-                    {
-                        l = Integer.parseInt(elements[i]);
-                        if ((l < 0L) || (l > 255L)) {
-                            return null;
-                        }
-                        bytes[i] = (byte) (int) (l & 0xFF);
-                    }
-                    break;
-                default:
-                    return null;
-            }
-        }
-        catch (NumberFormatException e)
-        {
-            return null;
-        }
-        return bytes;
-    }
-
-    public static String getHostIp()
-    {
-        try
-        {
-            return InetAddress.getLocalHost().getHostAddress();
-        }
-        catch (UnknownHostException e)
-        {
-        }
-        return "127.0.0.1";
-    }
-
-    public static String getHostName()
-    {
-        try
-        {
-            return InetAddress.getLocalHost().getHostName();
-        }
-        catch (UnknownHostException e)
-        {
-        }
-        return "未知";
-    }
-}

+ 53 - 406
ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java

@@ -1,406 +1,53 @@
-package com.ruoyi.common.utils.reflect;
-
-import cn.hutool.core.convert.Convert;
-import com.ruoyi.common.utils.DateUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.Validate;
-import org.apache.poi.ss.usermodel.DateUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.*;
-import java.util.Date;
-
-/**
- * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
- * 
- * @author ruoyi
- */
-@SuppressWarnings("rawtypes")
-public class ReflectUtils
-{
-    private static final String SETTER_PREFIX = "set";
-
-    private static final String GETTER_PREFIX = "get";
-
-    private static final String CGLIB_CLASS_SEPARATOR = "$$";
-
-    private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
-
-    /**
-     * 调用Getter方法.
-     * 支持多级,如:对象名.对象名.方法
-     */
-    @SuppressWarnings("unchecked")
-    public static <E> E invokeGetter(Object obj, String propertyName)
-    {
-        Object object = obj;
-        for (String name : StringUtils.split(propertyName, "."))
-        {
-            String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
-            object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
-        }
-        return (E) object;
-    }
-
-    /**
-     * 调用Setter方法, 仅匹配方法名。
-     * 支持多级,如:对象名.对象名.方法
-     */
-    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)
-            {
-                String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
-                object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
-            }
-            else
-            {
-                String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
-                invokeMethodByName(object, setterMethodName, new Object[] { value });
-            }
-        }
-    }
-
-    /**
-     * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
-     */
-    @SuppressWarnings("unchecked")
-    public static <E> E getFieldValue(final Object obj, final String fieldName)
-    {
-        Field field = getAccessibleField(obj, fieldName);
-        if (field == null)
-        {
-            logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
-            return null;
-        }
-        E result = null;
-        try
-        {
-            result = (E) field.get(obj);
-        }
-        catch (IllegalAccessException e)
-        {
-            logger.error("不可能抛出的异常{}", e.getMessage());
-        }
-        return result;
-    }
-
-    /**
-     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
-     */
-    public static <E> void setFieldValue(final Object obj, final String fieldName, final E value)
-    {
-        Field field = getAccessibleField(obj, fieldName);
-        if (field == null)
-        {
-            // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
-            logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
-            return;
-        }
-        try
-        {
-            field.set(obj, value);
-        }
-        catch (IllegalAccessException e)
-        {
-            logger.error("不可能抛出的异常: {}", e.getMessage());
-        }
-    }
-
-    /**
-     * 直接调用对象方法, 无视private/protected修饰符.
-     * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
-     * 同时匹配方法名+参数类型,
-     */
-    @SuppressWarnings("unchecked")
-    public static <E> E invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
-            final Object[] args)
-    {
-        if (obj == null || methodName == null)
-        {
-            return null;
-        }
-        Method method = getAccessibleMethod(obj, methodName, parameterTypes);
-        if (method == null)
-        {
-            logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
-            return null;
-        }
-        try
-        {
-            return (E) method.invoke(obj, args);
-        }
-        catch (Exception e)
-        {
-            String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
-            throw convertReflectionExceptionToUnchecked(msg, e);
-        }
-    }
-
-    /**
-     * 直接调用对象方法, 无视private/protected修饰符,
-     * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
-     * 只匹配函数名,如果有多个同名函数调用第一个。
-     */
-    @SuppressWarnings("unchecked")
-    public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
-    {
-        Method method = getAccessibleMethodByName(obj, methodName, args.length);
-        if (method == null)
-        {
-            // 如果为空不报错,直接返回空。
-            logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
-            return null;
-        }
-        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)
-                    {
-                        args[i] = Convert.toStr(args[i]);
-                        if (StringUtils.endsWith((String) args[i], ".0"))
-                        {
-                            args[i] = StringUtils.substringBefore((String) args[i], ".0");
-                        }
-                    }
-                    else if (cs[i] == Integer.class)
-                    {
-                        args[i] = Convert.toInt(args[i]);
-                    }
-                    else if (cs[i] == Long.class)
-                    {
-                        args[i] = Convert.toLong(args[i]);
-                    }
-                    else if (cs[i] == Double.class)
-                    {
-                        args[i] = Convert.toDouble(args[i]);
-                    }
-                    else if (cs[i] == Float.class)
-                    {
-                        args[i] = Convert.toFloat(args[i]);
-                    }
-                    else if (cs[i] == Date.class)
-                    {
-                        if (args[i] instanceof String)
-                        {
-                            args[i] = DateUtils.parseDate(args[i]);
-                        }
-                        else
-                        {
-                            args[i] = DateUtil.getJavaDate((Double) args[i]);
-                        }
-                    }
-                    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)
-        {
-            String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
-            throw convertReflectionExceptionToUnchecked(msg, e);
-        }
-    }
-
-    /**
-     * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
-     * 如向上转型到Object仍无法找到, 返回null.
-     */
-    public static Field getAccessibleField(final Object obj, final String fieldName)
-    {
-        // 为空不报错。直接返回 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
-            {
-                Field field = superClass.getDeclaredField(fieldName);
-                makeAccessible(field);
-                return field;
-            }
-            catch (NoSuchFieldException e)
-            {
-                continue;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
-     * 如向上转型到Object仍无法找到, 返回null.
-     * 匹配函数名+参数类型。
-     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
-     */
-    public static Method getAccessibleMethod(final Object obj, final String methodName,
-            final Class<?>... parameterTypes)
-    {
-        // 为空不报错。直接返回 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
-            {
-                Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
-                makeAccessible(method);
-                return method;
-            }
-            catch (NoSuchMethodException e)
-            {
-                continue;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
-     * 如向上转型到Object仍无法找到, 返回null.
-     * 只匹配函数名。
-     * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
-     */
-    public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum)
-    {
-        // 为空不报错。直接返回 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())
-        {
-            Method[] methods = searchType.getDeclaredMethods();
-            for (Method method : methods)
-            {
-                if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum)
-                {
-                    makeAccessible(method);
-                    return method;
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
-     */
-    public static void makeAccessible(Method method)
-    {
-        if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
-                && !method.isAccessible())
-        {
-            method.setAccessible(true);
-        }
-    }
-
-    /**
-     * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
-     */
-    public static void makeAccessible(Field field)
-    {
-        if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
-                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible())
-        {
-            field.setAccessible(true);
-        }
-    }
-
-    /**
-     * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
-     * 如无法找到, 返回Object.class.
-     */
-    @SuppressWarnings("unchecked")
-    public static <T> Class<T> getClassGenricType(final Class clazz)
-    {
-        return getClassGenricType(clazz, 0);
-    }
-
-    /**
-     * 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
-     * 如无法找到, 返回Object.class.
-     */
-    public static Class getClassGenricType(final Class clazz, final int index)
-    {
-        Type genType = clazz.getGenericSuperclass();
-
-        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)
-        {
-            logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
-                    + params.length);
-            return Object.class;
-        }
-        if (!(params[index] instanceof Class))
-        {
-            logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
-            return Object.class;
-        }
-
-        return (Class) params[index];
-    }
-
-    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))
-        {
-            Class<?> superClass = clazz.getSuperclass();
-            if (superClass != null && !Object.class.equals(superClass))
-            {
-                return superClass;
-            }
-        }
-        return clazz;
-
-    }
-
-    /**
-     * 将反射时的checked exception转换为unchecked exception.
-     */
-    public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e)
-    {
-        if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
-                || e instanceof NoSuchMethodException)
-        {
-            return new IllegalArgumentException(msg, e);
-        }
-        else if (e instanceof InvocationTargetException)
-        {
-            return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
-        }
-        return new RuntimeException(msg, e);
-    }
-}
+package com.ruoyi.common.utils.reflect;
+
+import cn.hutool.core.util.ReflectUtil;
+import cn.hutool.core.util.StrUtil;
+
+import java.lang.reflect.Method;
+
+/**
+ * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
+ *
+ * @author Lion Li
+ */
+@SuppressWarnings("rawtypes")
+public class ReflectUtils extends ReflectUtil {
+
+	private static final String SETTER_PREFIX = "set";
+
+	private static final String GETTER_PREFIX = "get";
+
+	/**
+	 * 调用Getter方法.
+	 * 支持多级,如:对象名.对象名.方法
+	 */
+	@SuppressWarnings("unchecked")
+	public static <E> E invokeGetter(Object obj, String propertyName) {
+		Object object = obj;
+		for (String name : StrUtil.split(propertyName, ".")) {
+			String getterMethodName = GETTER_PREFIX + StrUtil.upperFirst(name);
+			object = invoke(object, getterMethodName);
+		}
+		return (E) object;
+	}
+
+	/**
+	 * 调用Setter方法, 仅匹配方法名。
+	 * 支持多级,如:对象名.对象名.方法
+	 */
+	public static <E> void invokeSetter(Object obj, String propertyName, E value) {
+		Object object = obj;
+		String[] names = StrUtil.split(propertyName, ".");
+		for (int i = 0; i < names.length; i++) {
+			if (i < names.length - 1) {
+				String getterMethodName = GETTER_PREFIX + StrUtil.upperFirst(names[i]);
+				object = invoke(object, getterMethodName);
+			} else {
+				String setterMethodName = SETTER_PREFIX + StrUtil.upperFirst(names[i]);
+				Method method = getMethodByName(object.getClass(), setterMethodName);
+				invoke(object, method, value);
+			}
+		}
+	}
+
+}

+ 133 - 126
ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java

@@ -1,126 +1,133 @@
-package com.ruoyi.framework.interceptor.impl;
-
-import cn.hutool.core.lang.Validator;
-import com.alibaba.fastjson.JSONObject;
-import com.ruoyi.common.constant.Constants;
-import com.ruoyi.common.core.redis.RedisCache;
-import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
-import com.ruoyi.common.utils.http.HttpHelper;
-import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.stereotype.Component;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-/**
- * 判断请求url和数据是否和上一次相同,
- * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。
- * 
- * @author ruoyi
- */
-@Component
-public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
-{
-    public final String REPEAT_PARAMS = "repeatParams";
-
-    public final String REPEAT_TIME = "repeatTime";
-
-    // 令牌自定义标识
-    @Value("${token.header}")
-    private String header;
-
-    @Autowired
-    private RedisCache redisCache;
-
-    /**
-     * 间隔时间,单位:秒 默认10秒
-     * 
-     * 两次相同参数的请求,如果间隔时间大于该参数,系统不会认定为重复提交的数据
-     */
-    private int intervalTime = 10;
-
-    public void setIntervalTime(int intervalTime)
-    {
-        this.intervalTime = intervalTime;
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public boolean isRepeatSubmit(HttpServletRequest request)
-    {
-        String nowParams = "";
-        if (request instanceof RepeatedlyRequestWrapper)
-        {
-            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
-            nowParams = HttpHelper.getBodyString(repeatedlyRequest);
-        }
-
-        // body参数为空,获取Parameter的数据
-        if (Validator.isEmpty(nowParams))
-        {
-            nowParams = JSONObject.toJSONString(request.getParameterMap());
-        }
-        Map<String, Object> nowDataMap = new HashMap<String, Object>();
-        nowDataMap.put(REPEAT_PARAMS, nowParams);
-        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
-
-        // 请求地址(作为存放cache的key值)
-        String url = request.getRequestURI();
-
-        // 唯一值(没有消息头则使用请求地址)
-        String submitKey = request.getHeader(header);
-        if (Validator.isEmpty(submitKey))
-        {
-            submitKey = url;
-        }
-
-        // 唯一标识(指定key + 消息头)
-        String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + submitKey;
-
-        Object sessionObj = redisCache.getCacheObject(cacheRepeatKey);
-        if (sessionObj != null)
-        {
-            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
-            if (sessionMap.containsKey(url))
-            {
-                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
-                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap))
-                {
-                    return true;
-                }
-            }
-        }
-        Map<String, Object> cacheMap = new HashMap<String, Object>();
-        cacheMap.put(url, nowDataMap);
-        redisCache.setCacheObject(cacheRepeatKey, cacheMap, intervalTime, TimeUnit.SECONDS);
-        return false;
-    }
-
-    /**
-     * 判断参数是否相同
-     */
-    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap)
-    {
-        String nowParams = (String) nowMap.get(REPEAT_PARAMS);
-        String preParams = (String) preMap.get(REPEAT_PARAMS);
-        return nowParams.equals(preParams);
-    }
-
-    /**
-     * 判断两次间隔时间
-     */
-    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap)
-    {
-        long time1 = (Long) nowMap.get(REPEAT_TIME);
-        long time2 = (Long) preMap.get(REPEAT_TIME);
-        if ((time1 - time2) < (this.intervalTime * 1000))
-        {
-            return true;
-        }
-        return false;
-    }
-}
+package com.ruoyi.framework.interceptor.impl;
+
+import cn.hutool.core.io.IoUtil;
+import cn.hutool.core.lang.Validator;
+import com.alibaba.fastjson.JSONObject;
+import com.ruoyi.common.constant.Constants;
+import com.ruoyi.common.core.redis.RedisCache;
+import com.ruoyi.common.filter.RepeatedlyRequestWrapper;
+import com.ruoyi.framework.interceptor.RepeatSubmitInterceptor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * 判断请求url和数据是否和上一次相同,
+ * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。
+ *
+ * @author ruoyi
+ */
+@Slf4j
+@Component
+public class SameUrlDataInterceptor extends RepeatSubmitInterceptor
+{
+    public final String REPEAT_PARAMS = "repeatParams";
+
+    public final String REPEAT_TIME = "repeatTime";
+
+    // 令牌自定义标识
+    @Value("${token.header}")
+    private String header;
+
+    @Autowired
+    private RedisCache redisCache;
+
+    /**
+     * 间隔时间,单位:秒 默认10秒
+     *
+     * 两次相同参数的请求,如果间隔时间大于该参数,系统不会认定为重复提交的数据
+     */
+    private int intervalTime = 10;
+
+    public void setIntervalTime(int intervalTime)
+    {
+        this.intervalTime = intervalTime;
+    }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public boolean isRepeatSubmit(HttpServletRequest request)
+    {
+        String nowParams = "";
+        if (request instanceof RepeatedlyRequestWrapper)
+        {
+            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
+			try {
+				nowParams = IoUtil.readUtf8(repeatedlyRequest.getInputStream());
+			} catch (IOException e) {
+				log.warn("读取流出现问题!");
+			}
+		}
+
+        // body参数为空,获取Parameter的数据
+        if (Validator.isEmpty(nowParams))
+        {
+            nowParams = JSONObject.toJSONString(request.getParameterMap());
+        }
+        Map<String, Object> nowDataMap = new HashMap<String, Object>();
+        nowDataMap.put(REPEAT_PARAMS, nowParams);
+        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
+
+        // 请求地址(作为存放cache的key值)
+        String url = request.getRequestURI();
+
+        // 唯一值(没有消息头则使用请求地址)
+        String submitKey = request.getHeader(header);
+        if (Validator.isEmpty(submitKey))
+        {
+            submitKey = url;
+        }
+
+        // 唯一标识(指定key + 消息头)
+        String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + submitKey;
+
+        Object sessionObj = redisCache.getCacheObject(cacheRepeatKey);
+        if (sessionObj != null)
+        {
+            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
+            if (sessionMap.containsKey(url))
+            {
+                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
+                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap))
+                {
+                    return true;
+                }
+            }
+        }
+        Map<String, Object> cacheMap = new HashMap<String, Object>();
+        cacheMap.put(url, nowDataMap);
+        redisCache.setCacheObject(cacheRepeatKey, cacheMap, intervalTime, TimeUnit.SECONDS);
+        return false;
+    }
+
+    /**
+     * 判断参数是否相同
+     */
+    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap)
+    {
+        String nowParams = (String) nowMap.get(REPEAT_PARAMS);
+        String preParams = (String) preMap.get(REPEAT_PARAMS);
+        return nowParams.equals(preParams);
+    }
+
+    /**
+     * 判断两次间隔时间
+     */
+    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap)
+    {
+        long time1 = (Long) nowMap.get(REPEAT_TIME);
+        long time2 = (Long) preMap.get(REPEAT_TIME);
+        if ((time1 - time2) < (this.intervalTime * 1000))
+        {
+            return true;
+        }
+        return false;
+    }
+}

+ 1 - 2
ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java

@@ -9,7 +9,6 @@ import com.ruoyi.common.core.domain.model.LoginUser;
 import com.ruoyi.common.core.redis.RedisCache;
 import com.ruoyi.common.utils.ServletUtils;
 import com.ruoyi.common.utils.ip.AddressUtils;
-import com.ruoyi.common.utils.ip.IpUtils;
 import com.ruoyi.framework.config.properties.TokenProperties;
 import io.jsonwebtoken.Claims;
 import io.jsonwebtoken.Jwts;
@@ -131,7 +130,7 @@ public class TokenService {
      */
     public void setUserAgent(LoginUser loginUser) {
         UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
-        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
+        String ip = ServletUtils.getClientIP();
         loginUser.setIpaddr(ip);
         loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
         loginUser.setBrowser(userAgent.getBrowser().getName());

+ 2 - 6
ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java

@@ -263,12 +263,8 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
                 StringWriter sw = new StringWriter();
                 Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                 tpl.merge(context, sw);
-                try {
-                    String path = getGenPath(table, template);
-                    FileUtils.writeStringToFile(new File(path), sw.toString(), Constants.UTF8);
-                } catch (IOException e) {
-                    throw new CustomException("渲染模板失败,表名:" + table.getTableName());
-                }
+                String path = getGenPath(table, template);
+                FileUtils.writeUtf8String(sw.toString(), path);
             }
         }
     }