From b3541e975898e17a6cbc1a9ea776f3ec7e91d39a Mon Sep 17 00:00:00 2001 From: 疯狂的狮子li <15040126243@163.com> Date: 星期六, 12 六月 2021 20:13:35 +0800 Subject: [PATCH] update 优化 使用 hutool 替换 ruoyi 自带工具类 解决部分方法过期与高版本JDK不兼容问题 --- ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java | 208 ++++---- ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java | 8 /dev/null | 196 ------- ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java | 259 +++++----- ruoyi-common/src/main/java/com/ruoyi/common/filter/XssHttpServletRequestWrapper.java | 8 ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java | 6 ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java | 77 +- ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java | 90 --- ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatedlyRequestWrapper.java | 152 +++--- ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java | 3 ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java | 459 ++---------------- 11 files changed, 418 insertions(+), 1,048 deletions(-) diff --git a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java index 7418a2c..38913f5 100644 --- a/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java +++ b/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java @@ -54,10 +54,10 @@ 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 @@ 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) { diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatedlyRequestWrapper.java b/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatedlyRequestWrapper.java index caacba6..74659bf 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatedlyRequestWrapper.java +++ b/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; - -/** - * 鏋勫缓鍙噸澶嶈鍙杋nputStream鐨剅equest - * - * @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; + +/** + * 鏋勫缓鍙噸澶嶈鍙杋nputStream鐨剅equest + * + * @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) + { + + } + }; + } +} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/filter/XssHttpServletRequestWrapper.java b/ruoyi-common/src/main/java/com/ruoyi/common/filter/XssHttpServletRequestWrapper.java index 0170e1d..4d36a92 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/filter/XssHttpServletRequestWrapper.java +++ b/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.HttpServletRequestWrapper; import java.io.ByteArrayInputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; /** * XSS杩囨护澶勭悊 @@ -57,7 +58,7 @@ } // 涓虹┖锛岀洿鎺ヨ繑鍥� - 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 @@ // 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 diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java index 0535cf2..1594291 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java @@ -2,6 +2,9 @@ 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.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); - } +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); - } + /** + * 鑾峰彇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) { + return Convert.toInt(getRequest().getParameter(name)); + } - /** - * 鑾峰彇Integer鍙傛暟 - */ - public static Integer getParameterToInt(String name, Integer defaultValue) - { - return Convert.toInt(getRequest().getParameter(name), defaultValue); - } + /** + * 鑾峰彇Integer鍙傛暟 + */ + public static Integer getParameterToInt(String name, Integer defaultValue) { + return Convert.toInt(getRequest().getParameter(name), defaultValue); + } - /** - * 鑾峰彇request - */ - public static HttpServletRequest getRequest() - { - return getRequestAttributes().getRequest(); - } + /** + * 鑾峰彇request + */ + public static HttpServletRequest getRequest() { + return getRequestAttributes().getRequest(); + } - /** - * 鑾峰彇response - */ - public static HttpServletResponse getResponse() - { - return getRequestAttributes().getResponse(); - } + /** + * 鑾峰彇response + */ + public static HttpServletResponse getResponse() { + return getRequestAttributes().getResponse(); + } - /** - * 鑾峰彇session - */ - public static HttpSession getSession() - { - return getRequest().getSession(); - } + /** + * 鑾峰彇session + */ + public static HttpSession getSession() { + return getRequest().getSession(); + } - public static ServletRequestAttributes getRequestAttributes() - { - RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); - return (ServletRequestAttributes) attributes; - } + 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; - } + /** + * 灏嗗瓧绗︿覆娓叉煋鍒板鎴风 + * + * @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; + } - /** - * 鏄惁鏄疉jax寮傛璇锋眰 - * - * @param request - */ - public static boolean isAjaxRequest(HttpServletRequest request) - { - String accept = request.getHeader("accept"); - if (accept != null && accept.indexOf("application/json") != -1) - { - return true; - } + /** + * 鏄惁鏄疉jax寮傛璇锋眰 + * + * @param request + */ + public static boolean isAjaxRequest(HttpServletRequest request) { - String xRequestedWith = request.getHeader("X-Requested-With"); - if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) - { - return true; - } + String accept = request.getHeader("accept"); + if (accept != null && accept.indexOf("application/json") != -1) { + return true; + } - String uri = request.getRequestURI(); - if (StrUtil.equalsAnyIgnoreCase(uri, ".json", ".xml")) - { - return true; - } + String xRequestedWith = request.getHeader("X-Requested-With"); + if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) { + return true; + } - String ajax = request.getParameter("__ajax"); - if (StrUtil.equalsAnyIgnoreCase(ajax, "json", "xml")) - { - return true; - } - return false; - } + 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()); + } + } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java index 587b2bf..bc953de 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUtils.java +++ b/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 @@ /** * 鏂囦欢澶勭悊宸ュ叿绫� - * + * * @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]+"; /** - * 杈撳嚭鎸囧畾鏂囦欢鐨刡yte鏁扮粍 - * - * @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 姝e父 false 闈炴硶 */ @@ -130,7 +56,7 @@ /** * 涓嬭浇鏂囦欢鍚嶉噸鏂扮紪鐮� - * + * * @param request 璇锋眰瀵硅薄 * @param fileName 鏂囦欢鍚� * @return 缂栫爜鍚庣殑鏂囦欢鍚� @@ -142,7 +68,7 @@ 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 @@ 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; } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpHelper.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpHelper.java deleted file mode 100644 index 430daf8..0000000 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpHelper.java +++ /dev/null @@ -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(); - } -} diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java deleted file mode 100644 index 9aee92e..0000000 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java +++ /dev/null @@ -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 鍙戦�丟ET鏂规硶鐨勮姹� - * - * @param url 鍙戦�佽姹傜殑 URL - * @param param 璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋�� - * @return 鎵�浠h〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋� - */ - public static String sendGet(String url, String param) - { - return sendGet(url, param, Constants.UTF8); - } - - /** - * 鍚戞寚瀹� URL 鍙戦�丟ET鏂规硶鐨勮姹� - * - * @param url 鍙戦�佽姹傜殑 URL - * @param param 璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋�� - * @param contentType 缂栫爜绫诲瀷 - * @return 鎵�浠h〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋� - */ - 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 鍙戦�丳OST鏂规硶鐨勮姹� - * - * @param url 鍙戦�佽姹傜殑 URL - * @param param 璇锋眰鍙傛暟锛岃姹傚弬鏁板簲璇ユ槸 name1=value1&name2=value2 鐨勫舰寮忋�� - * @return 鎵�浠h〃杩滅▼璧勬簮鐨勫搷搴旂粨鏋� - */ - 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; - } - } -} \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java index 4805d25..2093e19 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java +++ b/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; + } } diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/IpUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/IpUtils.java deleted file mode 100644 index c46c69b..0000000 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/IpUtils.java +++ /dev/null @@ -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; - } - } - - /** - * 灏咺Pv4鍦板潃杞崲鎴愬瓧鑺� - * - * @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 "鏈煡"; - } -} \ No newline at end of file diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java index a3b3a76..7ffa94c 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/reflect/ReflectUtils.java +++ b/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, 琚獳OP杩囩殑鐪熷疄绫荤瓑宸ュ叿鍑芥暟. - * - * @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淇グ绗�, 涓嶇粡杩噂etter鍑芥暟. - */ - @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淇グ绗�, 涓嶇粡杩噑etter鍑芥暟. - */ - 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); - } - } - - /** - * 寰幆鍚戜笂杞瀷, 鑾峰彇瀵硅薄鐨凞eclaredField, 骞跺己鍒惰缃负鍙闂�. - * 濡傚悜涓婅浆鍨嬪埌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; - } - - /** - * 寰幆鍚戜笂杞瀷, 鑾峰彇瀵硅薄鐨凞eclaredMethod,骞跺己鍒惰缃负鍙闂�. - * 濡傚悜涓婅浆鍨嬪埌Object浠嶆棤娉曟壘鍒�, 杩斿洖null. - * 鍖归厤鍑芥暟鍚�+鍙傛暟绫诲瀷銆� - * 鐢ㄤ簬鏂规硶闇�瑕佽澶氭璋冪敤鐨勬儏鍐�. 鍏堜娇鐢ㄦ湰鍑芥暟鍏堝彇寰桵ethod,鐒跺悗璋冪敤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; - } - - /** - * 寰幆鍚戜笂杞瀷, 鑾峰彇瀵硅薄鐨凞eclaredMethod,骞跺己鍒惰缃负鍙闂�. - * 濡傚悜涓婅浆鍨嬪埌Object浠嶆棤娉曟壘鍒�, 杩斿洖null. - * 鍙尮閰嶅嚱鏁板悕銆� - * 鐢ㄤ簬鏂规硶闇�瑕佽澶氭璋冪敤鐨勬儏鍐�. 鍏堜娇鐢ㄦ湰鍑芥暟鍏堝彇寰桵ethod,鐒跺悗璋冪敤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鐨凷ecurityManager鎶辨�ㄣ�� - */ - 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鐨凷ecurityManager鎶辨�ㄣ�� - */ - 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瀹氫箟涓0鏄庣殑娉涘瀷鍙傛暟鐨勭被鍨�, 娉ㄦ剰娉涘瀷蹇呴』瀹氫箟鍦ㄧ埗绫诲 - * 濡傛棤娉曟壘鍒�, 杩斿洖Object.class. - */ - @SuppressWarnings("unchecked") - public static <T> Class<T> getClassGenricType(final Class clazz) - { - return getClassGenricType(clazz, 0); - } - - /** - * 閫氳繃鍙嶅皠, 鑾峰緱Class瀹氫箟涓0鏄庣殑鐖剁被鐨勬硾鍨嬪弬鏁扮殑绫诲瀷. - * 濡傛棤娉曟壘鍒�, 杩斿洖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; - - } - - /** - * 灏嗗弽灏勬椂鐨刢hecked exception杞崲涓簎nchecked 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, 琚獳OP杩囩殑鐪熷疄绫荤瓑宸ュ叿鍑芥暟. + * + * @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); + } + } + } + +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java index 60bbf7c..b6cdfac 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java +++ b/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鍙傛暟涓虹┖锛岃幏鍙朠arameter鐨勬暟鎹� - 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()); - - // 璇锋眰鍦板潃锛堜綔涓哄瓨鏀綾ache鐨刱ey鍊硷級 - String url = request.getRequestURI(); - - // 鍞竴鍊硷紙娌℃湁娑堟伅澶村垯浣跨敤璇锋眰鍦板潃锛� - String submitKey = request.getHeader(header); - if (Validator.isEmpty(submitKey)) - { - submitKey = url; - } - - // 鍞竴鏍囪瘑锛堟寚瀹歬ey + 娑堟伅澶达級 - 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鍙傛暟涓虹┖锛岃幏鍙朠arameter鐨勬暟鎹� + 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()); + + // 璇锋眰鍦板潃锛堜綔涓哄瓨鏀綾ache鐨刱ey鍊硷級 + String url = request.getRequestURI(); + + // 鍞竴鍊硷紙娌℃湁娑堟伅澶村垯浣跨敤璇锋眰鍦板潃锛� + String submitKey = request.getHeader(header); + if (Validator.isEmpty(submitKey)) + { + submitKey = url; + } + + // 鍞竴鏍囪瘑锛堟寚瀹歬ey + 娑堟伅澶达級 + 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; + } +} diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java index 0db777b..f834570 100644 --- a/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java +++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/TokenService.java @@ -9,7 +9,6 @@ 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 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()); diff --git a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java index f156e4f..1568824 100644 --- a/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java +++ b/ruoyi-generator/src/main/java/com/ruoyi/generator/service/GenTableServiceImpl.java @@ -263,12 +263,8 @@ 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); } } } -- Gitblit v1.9.3