diff --git a/.etc/checkstyle/checkstyle.xml b/.etc/checkstyle/checkstyle.xml index caaff17e8..5349e5070 100644 --- a/.etc/checkstyle/checkstyle.xml +++ b/.etc/checkstyle/checkstyle.xml @@ -45,28 +45,28 @@ - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/constant/enums/BooleanEnum.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/constant/enums/BooleanEnum.java index 4d78181d2..60dff8cbb 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/constant/enums/BooleanEnum.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/constant/enums/BooleanEnum.java @@ -40,11 +40,11 @@ public enum BooleanEnum { private final Integer intValue; public Boolean booleanValue() { - return booleanValue; + return this.booleanValue; } public Integer intValue() { - return intValue; + return this.intValue; } } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/https/CompatibleSSLFactory.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/https/CompatibleSSLFactory.java index 30b6fe81b..f8df5e379 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/https/CompatibleSSLFactory.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/https/CompatibleSSLFactory.java @@ -59,52 +59,52 @@ public CompatibleSSLFactory(String protocol, KeyManager[] keyManagers, TrustMana @Override public String[] getDefaultCipherSuites() { - return factory.getDefaultCipherSuites(); + return this.factory.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { - return factory.getSupportedCipherSuites(); + return this.factory.getSupportedCipherSuites(); } @Override public Socket createSocket() throws IOException { - return enabledProtocols(factory.createSocket()); + return enabledProtocols(this.factory.createSocket()); } @Override public Socket createSocket(Socket socket, InputStream inputStream, boolean b) throws IOException { - return enabledProtocols(factory.createSocket(socket, inputStream, b)); + return enabledProtocols(this.factory.createSocket(socket, inputStream, b)); } @Override public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOException { - return enabledProtocols(factory.createSocket(socket, s, i, b)); + return enabledProtocols(this.factory.createSocket(socket, s, i, b)); } @Override public Socket createSocket(String s, int i) throws IOException { - return enabledProtocols(factory.createSocket(s, i)); + return enabledProtocols(this.factory.createSocket(s, i)); } @Override public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException { - return enabledProtocols(factory.createSocket(s, i, inetAddress, i1)); + return enabledProtocols(this.factory.createSocket(s, i, inetAddress, i1)); } @Override public Socket createSocket(InetAddress inetAddress, int i) throws IOException { - return enabledProtocols(factory.createSocket(inetAddress, i)); + return enabledProtocols(this.factory.createSocket(inetAddress, i)); } @Override public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException { - return enabledProtocols(factory.createSocket(inetAddress, i, inetAddress1, i1)); + return enabledProtocols(this.factory.createSocket(inetAddress, i, inetAddress1, i1)); } private Socket enabledProtocols(Socket socket) { - if (!ArrayUtils.isEmpty(protocols) && socket instanceof SSLSocket) { - ((SSLSocket) socket).setEnabledProtocols(protocols); + if (!ArrayUtils.isEmpty(this.protocols) && socket instanceof SSLSocket) { + ((SSLSocket) socket).setEnabledProtocols(this.protocols); } return socket; } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/ModifyParameterRequestWrapper.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/ModifyParameterRequestWrapper.java index e6a573de7..43639575b 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/ModifyParameterRequestWrapper.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/ModifyParameterRequestWrapper.java @@ -53,7 +53,7 @@ public String getParameter(String name) { @Override public Enumeration getParameterNames() { - return Collections.enumeration(parameterMap.keySet()); + return Collections.enumeration(this.parameterMap.keySet()); } @Override diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/RepeatBodyRequestWrapper.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/RepeatBodyRequestWrapper.java index 57ea3af18..0cef93665 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/RepeatBodyRequestWrapper.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/request/wrapper/RepeatBodyRequestWrapper.java @@ -51,12 +51,13 @@ public RepeatBodyRequestWrapper(HttpServletRequest request) { @Override public BufferedReader getReader() { - return ObjectUtils.isEmpty(bodyByteArray) ? null : new BufferedReader(new InputStreamReader(getInputStream())); + return ObjectUtils.isEmpty(this.bodyByteArray) ? null + : new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() { - final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bodyByteArray); + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.bodyByteArray); return new ServletInputStream() { @Override public boolean isFinished() { @@ -81,7 +82,7 @@ public int read() { } public byte[] getBodyByteArray() { - return bodyByteArray; + return this.bodyByteArray; } private static byte[] getByteBody(HttpServletRequest request) { @@ -102,7 +103,7 @@ private static byte[] getByteBody(HttpServletRequest request) { */ @Override public Map getParameterMap() { - return parameterMap; + return this.parameterMap; } } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractBlockingQueueThread.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractBlockingQueueThread.java index abc624197..ff908b8f2 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractBlockingQueueThread.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractBlockingQueueThread.java @@ -33,20 +33,20 @@ public abstract class AbstractBlockingQueueThread extends AbstractQueueThread public void put(T t) { if (t != null) { try { - queue.put(t); + this.queue.put(t); } catch (InterruptedException e) { currentThread().interrupt(); } catch (Exception e) { - log.error("{} put Object error, param: {}", this.getClass().toString(), t, e); + this.log.error("{} put Object error, param: {}", this.getClass().toString(), t, e); } } } @Override protected T poll(long time) throws InterruptedException { - return queue.poll(time, TimeUnit.MILLISECONDS); + return this.queue.poll(time, TimeUnit.MILLISECONDS); } } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractDynamicTimer.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractDynamicTimer.java index 1ba64481a..67e71d193 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractDynamicTimer.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractDynamicTimer.java @@ -54,16 +54,16 @@ public void put(T t) { } try { - lock.runByInterruptibly(() -> { - queue.add(t); - lock.signalAll(); + this.lock.runByInterruptibly(() -> { + this.queue.add(t); + this.lock.signalAll(); }); } catch (InterruptedException e) { interrupt(); } catch (Exception e) { - log.error("{} put error, param: {}", this.getClass().toString(), t, e); + this.log.error("{} put error, param: {}", this.getClass().toString(), t, e); } } @@ -80,9 +80,9 @@ public void run() { while (isRun()) { try { T t = pool(); - lock.runByInterruptibly(() -> { + this.lock.runByInterruptibly(() -> { if (t == null) { - lock.await(24, TimeUnit.HOURS); + this.lock.await(24, TimeUnit.HOURS); return; } @@ -90,7 +90,7 @@ public void run() { // 需要休眠 if (sleepTime > 0) { // 如果是被唤醒 - if (lock.await(sleepTime, TimeUnit.MILLISECONDS)) { + if (this.lock.await(sleepTime, TimeUnit.MILLISECONDS)) { replay(t); return; } @@ -111,17 +111,17 @@ public void run() { } protected T pool() { - return queue.poll(); + return this.queue.poll(); } protected abstract void process(T t); protected void error(Exception e) { - log.error("类: {}; 线程: {}; 运行异常! ", getSimpleName(), getId(), e); + this.log.error("类: {}; 线程: {}; 运行异常! ", getSimpleName(), getId(), e); } protected void shutdown() { - log.warn("类: {}; 线程: {}; 被中断! 剩余数据: {}", getSimpleName(), getId(), queue.size()); + this.log.warn("类: {}; 线程: {}; 被中断! 剩余数据: {}", getSimpleName(), getId(), this.queue.size()); } } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractQueueThread.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractQueueThread.java index 5f61a9e9d..958600678 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractQueueThread.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractQueueThread.java @@ -132,7 +132,7 @@ public void run() { } // Throwable 异常直接结束. 这里捕获用来保留信息. 方便排查问题 catch (Throwable t) { - log.error("线程队列运行异常!", t); + this.log.error("线程队列运行异常!", t); throw t; } } @@ -170,7 +170,7 @@ public E poll() { e = poll(getPollTimeout()); } catch (InterruptedException ex) { - log.error("{} 类的poll线程被中断!id: {}", getClass().getSimpleName(), getId()); + this.log.error("{} 类的poll线程被中断!id: {}", getClass().getSimpleName(), getId()); interrupt(); } return e; @@ -188,7 +188,7 @@ public E poll() { * @param list 当前数据 */ protected void shutdown(List list) { - log.warn("{} 线程: {} 被关闭. 数据:{}", this.getClass().getSimpleName(), getId(), list); + this.log.warn("{} 线程: {} 被关闭. 数据:{}", this.getClass().getSimpleName(), getId(), list); } } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractThreadContextComponent.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractThreadContextComponent.java index 0bb7cefc7..8b7aeaeb7 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractThreadContextComponent.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractThreadContextComponent.java @@ -44,7 +44,7 @@ public void onApplicationStart() { @Override public void onApplicationStop() { - log.warn("{} 线程: {}; 开始关闭!", getClass().getSimpleName(), getId()); + this.log.warn("{} 线程: {}; 开始关闭!", getClass().getSimpleName(), getId()); interrupt(); } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractTimer.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractTimer.java index afabb899d..f244c5050 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractTimer.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/thread/AbstractTimer.java @@ -39,11 +39,11 @@ public long getTimeout() { * 线程被中断触发. */ protected void shutdown() { - log.warn("{} 类 线程: {} 被中断!", getClass().getSimpleName(), getId()); + this.log.warn("{} 类 线程: {} 被中断!", getClass().getSimpleName(), getId()); } protected void error(Exception e) { - log.error("{} 类 线程: {} 出现异常!", getClass().getSimpleName(), getId(), e); + this.log.error("{} 类 线程: {} 出现异常!", getClass().getSimpleName(), getId(), e); } @Override diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfClass.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfClass.java index 68c4c3c3d..1fce9bff0 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfClass.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfClass.java @@ -34,16 +34,16 @@ public class EnumValueValidatorOfClass implements ConstraintValidator clazz : classList) { + for (Class clazz : this.classList) { if (clazz.isAssignableFrom(value)) { return true; } diff --git a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfInt.java b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfInt.java index 6284a30d8..ad460b14e 100644 --- a/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfInt.java +++ b/common/ballcat-common-core/src/main/java/org/ballcat/common/core/validation/validator/EnumValueValidatorOfInt.java @@ -34,16 +34,16 @@ public class EnumValueValidatorOfInt implements ConstraintValidator eClass : targetEnum) { + for (Class eClass : this.targetEnum) { // 包装类和原始类型的处理 Class clazz = ClassUtils.isPrimitiveWrapper(value.getClass()) ? ClassUtils.wrapperToPrimitive(value.getClass()) : value.getClass(); try { - Object enumInstance = MethodUtils.invokeStaticMethod(eClass, checkMethod, new Object[] { value }, + Object enumInstance = MethodUtils.invokeStaticMethod(eClass, this.checkMethod, new Object[] { value }, new Class[] { clazz }); return enumInstance != null; } diff --git a/common/ballcat-common-core/src/test/java/org/ballcat/common/core/thread/AbstractDynamicTimerTest.java b/common/ballcat-common-core/src/test/java/org/ballcat/common/core/thread/AbstractDynamicTimerTest.java index 926c9d4a5..0cf586873 100644 --- a/common/ballcat-common-core/src/test/java/org/ballcat/common/core/thread/AbstractDynamicTimerTest.java +++ b/common/ballcat-common-core/src/test/java/org/ballcat/common/core/thread/AbstractDynamicTimerTest.java @@ -42,13 +42,13 @@ class AbstractDynamicTimerTest { @BeforeEach void before() { - timer = new DynamicTimer(); - timer.onApplicationStart(); + this.timer = new DynamicTimer(); + this.timer.onApplicationStart(); } @AfterEach void after() { - timer.onApplicationStop(); + this.timer.onApplicationStop(); } @Test @@ -58,19 +58,19 @@ void test() throws InterruptedException { Action a2 = new Action("2", now.plusSeconds(2)); Action a4 = new Action("4", now.plusSeconds(4)); - timer.put(a1); - timer.put(a2); - timer.put(a4); + this.timer.put(a1); + this.timer.put(a2); + this.timer.put(a4); TimeUnit.MILLISECONDS.sleep(1050); - Assertions.assertEquals(1, timer.getProcessedCount()); + Assertions.assertEquals(1, this.timer.getProcessedCount()); TimeUnit.SECONDS.sleep(1); - Assertions.assertEquals(2, timer.getProcessedCount()); + Assertions.assertEquals(2, this.timer.getProcessedCount()); - timer.put(a2); + this.timer.put(a2); TimeUnit.MILLISECONDS.sleep(2050); - Assertions.assertEquals(4, timer.getProcessedCount()); + Assertions.assertEquals(4, this.timer.getProcessedCount()); } @Data diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/lock/JavaReentrantLock.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/lock/JavaReentrantLock.java index b7bb7e058..763a49d04 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/lock/JavaReentrantLock.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/lock/JavaReentrantLock.java @@ -36,7 +36,7 @@ public class JavaReentrantLock { /** * 激活与休眠线程 */ - protected final Condition defaultCondition = lock.newCondition(); + protected final Condition defaultCondition = this.lock.newCondition(); public Condition newCondition() { return getLock().newCondition(); diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/markdown/MarkdownBuilder.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/markdown/MarkdownBuilder.java index 525fec25a..a0286c338 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/markdown/MarkdownBuilder.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/markdown/MarkdownBuilder.java @@ -67,7 +67,7 @@ public MarkdownBuilder() { * @param content 自定义内容 */ public MarkdownBuilder append(Object content) { - lineTextBuilder.append(toString(content)); + this.lineTextBuilder.append(toString(content)); return this; } @@ -100,7 +100,7 @@ public MarkdownBuilder orderList(Object content) { */ public MarkdownBuilder orderList(int index, Object content) { lineBreak(); - lineTextBuilder.append(index).append(ORDER_LIST_PREFIX).append(toString(content)); + this.lineTextBuilder.append(index).append(ORDER_LIST_PREFIX).append(toString(content)); return this; } @@ -110,7 +110,7 @@ public MarkdownBuilder orderList(int index, Object content) { public MarkdownBuilder unorderedList(Object content) { // 换行 lineBreak(); - lineTextBuilder.append(UNORDERED_LIST_PREFIX).append(toString(content)); + this.lineTextBuilder.append(UNORDERED_LIST_PREFIX).append(toString(content)); return this; } @@ -128,7 +128,7 @@ public MarkdownBuilder pic(String url) { * @param url 图片路径 */ public MarkdownBuilder pic(Object title, String url) { - lineTextBuilder.append("![").append(title).append("](").append(url).append(")"); + this.lineTextBuilder.append("![").append(title).append("](").append(url).append(")"); return this; } @@ -138,7 +138,7 @@ public MarkdownBuilder pic(Object title, String url) { * @param url http 路径 */ public MarkdownBuilder link(Object title, String url) { - lineTextBuilder.append("[").append(title).append("](").append(url).append(")"); + this.lineTextBuilder.append("[").append(title).append("](").append(url).append(")"); return this; } @@ -146,7 +146,7 @@ public MarkdownBuilder link(Object title, String url) { * 斜体 */ public MarkdownBuilder italic(Object content) { - lineTextBuilder.append(ITALIC_PREFIX).append(toString(content)).append(ITALIC_PREFIX); + this.lineTextBuilder.append(ITALIC_PREFIX).append(toString(content)).append(ITALIC_PREFIX); return this; } @@ -154,7 +154,7 @@ public MarkdownBuilder italic(Object content) { * 加粗 */ public MarkdownBuilder bold(Object content) { - lineTextBuilder.append(BOLD_PREFIX).append(toString(content)).append(BOLD_PREFIX); + this.lineTextBuilder.append(BOLD_PREFIX).append(toString(content)).append(BOLD_PREFIX); return this; } @@ -164,9 +164,9 @@ public MarkdownBuilder bold(Object content) { */ public MarkdownBuilder quote(Object... content) { lineBreak(); - lineTextBuilder.append(QUOTE_PREFIX); + this.lineTextBuilder.append(QUOTE_PREFIX); for (Object o : content) { - lineTextBuilder.append(toString(o)); + this.lineTextBuilder.append(toString(o)); } return this; } @@ -186,13 +186,13 @@ public MarkdownBuilder quoteBreak(Object... content) { */ public MarkdownBuilder code(String type, Object... code) { lineBreak(); - lineTextBuilder.append(CODE_PREFIX).append(type); + this.lineTextBuilder.append(CODE_PREFIX).append(type); lineBreak(); for (Object o : code) { - lineTextBuilder.append(toString(o)); + this.lineTextBuilder.append(toString(o)); } lineBreak(); - lineTextBuilder.append(CODE_SUFFIX); + this.lineTextBuilder.append(CODE_SUFFIX); return lineBreak(); } @@ -220,8 +220,8 @@ private String multiJson(Object obj) { * 强制换行 */ public MarkdownBuilder forceLineBreak() { - content.add(lineTextBuilder.toString()); - lineTextBuilder = new StringBuilder(); + this.content.add(this.lineTextBuilder.toString()); + this.lineTextBuilder = new StringBuilder(); return this; } @@ -229,7 +229,7 @@ public MarkdownBuilder forceLineBreak() { * 换行 当已编辑文本长度不为0时换行 */ public MarkdownBuilder lineBreak() { - if (lineTextBuilder.length() != 0) { + if (this.lineTextBuilder.length() != 0) { return forceLineBreak(); } return this; @@ -244,10 +244,10 @@ private MarkdownBuilder title(int i, Object content) { // 如果当前操作行已有字符,需要换行 lineBreak(); for (int j = 0; j < i; j++) { - lineTextBuilder.append(TITLE_PREFIX); + this.lineTextBuilder.append(TITLE_PREFIX); } - this.content.add(lineTextBuilder.append(" ").append(toString(content)).toString()); - lineTextBuilder = new StringBuilder(); + this.content.add(this.lineTextBuilder.append(" ").append(toString(content)).toString()); + this.lineTextBuilder = new StringBuilder(); return this; } @@ -290,7 +290,7 @@ public String toString() { public String build() { lineBreak(); StringBuilder res = new StringBuilder(); - content.forEach(line -> res.append(line).append(" \n")); + this.content.forEach(line -> res.append(line).append(" \n")); return res.toString(); } diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/CircularQueue.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/CircularQueue.java index 161cb818e..7ed1db29f 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/CircularQueue.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/CircularQueue.java @@ -38,25 +38,25 @@ public class CircularQueue { private Iterator iterator; public CircularQueue add(T t) throws InterruptedException { - lock.runByInterruptibly(() -> source.add(t)); + this.lock.runByInterruptibly(() -> this.source.add(t)); return this; } public CircularQueue addAll(Collection collection) throws InterruptedException { - lock.runByInterruptibly(() -> source.addAll(collection)); + this.lock.runByInterruptibly(() -> this.source.addAll(collection)); return this; } public T pool() throws InterruptedException { - return lock.getByInterruptibly(() -> { - if (CollectionUtils.isEmpty(source)) { + return this.lock.getByInterruptibly(() -> { + if (CollectionUtils.isEmpty(this.source)) { return null; } - if (iterator == null || !iterator.hasNext()) { - iterator = source.iterator(); + if (this.iterator == null || !this.iterator.hasNext()) { + this.iterator = this.source.iterator(); } - return iterator.next(); + return this.iterator.next(); }); } diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/WaitQueue.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/WaitQueue.java index ded55b6d2..53dbeeed0 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/WaitQueue.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/queue/WaitQueue.java @@ -38,7 +38,7 @@ public WaitQueue(LinkedBlockingQueue queue) { } public V get() { - return queue.poll(); + return this.queue.poll(); } public V poll() throws InterruptedException { @@ -48,18 +48,18 @@ public V poll() throws InterruptedException { public V poll(long timeout, TimeUnit unit) throws InterruptedException { V v; do { - v = queue.poll(timeout, unit); + v = this.queue.poll(timeout, unit); } while (v == null); return v; } public void clear() { - queue.clear(); + this.queue.clear(); } public void add(V seat) { - queue.add(seat); + this.queue.add(seat); } public void addAll(Collection accounts) { diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/system/Command.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/system/Command.java index 2dc7ea052..64d04dac9 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/system/Command.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/system/Command.java @@ -71,9 +71,9 @@ private Command(String init, String nextLine, String exit, Charset charset) thro this.stdErr = FileUtils.createTemp(); // 重定向标准输出和标准错误到文件, 避免写入到缓冲区然后占满导致 waitFor 死锁 - ProcessBuilder builder = new ProcessBuilder(cmdArray).redirectError(stdErr).redirectOutput(stdOut); + ProcessBuilder builder = new ProcessBuilder(cmdArray).redirectError(this.stdErr).redirectOutput(this.stdOut); this.process = builder.start(); - this.stdIn = process.getOutputStream(); + this.stdIn = this.process.getOutputStream(); this.nextLine = nextLine; this.exit = exit; this.charset = charset; @@ -101,8 +101,8 @@ public static Command of(String init, String nextLine, String exit, Charset char } public Command write(String str) throws IOException { - stdIn.write(str.getBytes(charset)); - stdIn.flush(); + this.stdIn.write(str.getBytes(this.charset)); + this.stdIn.flush(); return this; } @@ -110,14 +110,14 @@ public Command write(String str) throws IOException { * 换到下一行 */ public Command line() throws IOException { - return write(nextLine); + return write(this.nextLine); } /** * 写入通道退出指令 */ public Command exit() throws IOException { - write(exit); + write(this.exit); return line(); } @@ -144,8 +144,8 @@ public Command exec(String str) throws IOException { *

*/ public CommandResult result() throws InterruptedException { - process.waitFor(); - return CommandResult.of(stdOut, stdErr, startTime, LocalDateTime.now(), charset); + this.process.waitFor(); + return CommandResult.of(this.stdOut, this.stdErr, this.startTime, LocalDateTime.now(), this.charset); } /** @@ -162,16 +162,16 @@ public CommandResult result() throws InterruptedException { * @return live.lingting.tools.system.CommandResult */ public CommandResult result(long millis) throws InterruptedException, CommandTimeoutException { - if (process.waitFor(millis, TimeUnit.MILLISECONDS)) { + if (this.process.waitFor(millis, TimeUnit.MILLISECONDS)) { return result(); } // 超时. 强行杀死子线程 - process.destroyForcibly(); + this.process.destroyForcibly(); throw new CommandTimeoutException(); } public void close() { - process.destroy(); + this.process.destroy(); } } diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/system/CommandResult.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/system/CommandResult.java index bbafd2583..81597467b 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/system/CommandResult.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/system/CommandResult.java @@ -61,48 +61,48 @@ public static CommandResult of(File stdOut, File stdErr, LocalDateTime startTime } public File stdOut() { - return stdOut; + return this.stdOut; } public File stdErr() { - return stdErr; + return this.stdErr; } public String stdOutStr() throws IOException { - if (!StringUtils.hasText(strOutput)) { - try (FileInputStream output = new FileInputStream(stdOut)) { - strOutput = StreamUtils.toString(output, StreamUtils.DEFAULT_SIZE, charset); + if (!StringUtils.hasText(this.strOutput)) { + try (FileInputStream output = new FileInputStream(this.stdOut)) { + this.strOutput = StreamUtils.toString(output, StreamUtils.DEFAULT_SIZE, this.charset); } } - return strOutput; + return this.strOutput; } public String stdErrStr() throws IOException { - if (!StringUtils.hasText(strError)) { - try (FileInputStream error = new FileInputStream(stdErr)) { - strError = StreamUtils.toString(error, StreamUtils.DEFAULT_SIZE, charset); + if (!StringUtils.hasText(this.strError)) { + try (FileInputStream error = new FileInputStream(this.stdErr)) { + this.strError = StreamUtils.toString(error, StreamUtils.DEFAULT_SIZE, this.charset); } } - return strError; + return this.strError; } public InputStream stdOutStream() throws IOException { - return Files.newInputStream(stdOut.toPath()); + return Files.newInputStream(this.stdOut.toPath()); } public InputStream stdErrStream() throws IOException { - return Files.newInputStream(stdErr.toPath()); + return Files.newInputStream(this.stdErr.toPath()); } public void clean() { try { - Files.delete(stdOut.toPath()); + Files.delete(this.stdOut.toPath()); } catch (Exception e) { // } try { - Files.delete(stdErr.toPath()); + Files.delete(this.stdErr.toPath()); } catch (Exception e) { // diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/system/StopWatch.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/system/StopWatch.java index 56e4e4a08..4c30f0829 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/system/StopWatch.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/system/StopWatch.java @@ -39,25 +39,25 @@ public class StopWatch { * 开始计时, 如果已开始, 则从延续之前的计时 */ public void start() { - if (startTimeNanos != null) { + if (this.startTimeNanos != null) { return; } - durationNanos = null; - startTimeNanos = System.nanoTime(); + this.durationNanos = null; + this.startTimeNanos = System.nanoTime(); } /** * 是否正在运行 */ public boolean isRunning() { - return startTimeNanos != null; + return this.startTimeNanos != null; } public void stop() { - if (startTimeNanos != null) { - durationNanos = System.nanoTime() - startTimeNanos; + if (this.startTimeNanos != null) { + this.durationNanos = System.nanoTime() - this.startTimeNanos; } - startTimeNanos = null; + this.startTimeNanos = null; } public void restart() { @@ -75,10 +75,10 @@ public void restart() { *

*/ public long timeNanos() { - if (durationNanos == null) { - return startTimeNanos == null ? 0 : System.nanoTime() - startTimeNanos; + if (this.durationNanos == null) { + return this.startTimeNanos == null ? 0 : System.nanoTime() - this.startTimeNanos; } - return durationNanos; + return this.durationNanos; } public long timeMillis() { diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/thread/ThreadPool.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/thread/ThreadPool.java index e2cc12db2..4fa59e343 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/thread/ThreadPool.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/thread/ThreadPool.java @@ -168,11 +168,11 @@ public void execute(String name, ThrowingRunnable runnable) { } public CompletableFuture async(Supplier supplier) { - return CompletableFuture.supplyAsync(supplier, pool); + return CompletableFuture.supplyAsync(supplier, this.pool); } public Future submit(Callable callable) { - return pool.submit(callable); + return this.pool.submit(callable); } } diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/util/json/TypeReference.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/util/json/TypeReference.java index 5297273a1..c1d607c46 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/util/json/TypeReference.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/util/json/TypeReference.java @@ -32,11 +32,11 @@ protected TypeReference() { throw new IllegalArgumentException( "Internal error: TypeReference constructed without actual type information"); } - type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; + this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; } public Type getType() { - return type; + return this.type; } @Override diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/util/tree/TreeUtils.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/util/tree/TreeUtils.java index 71a4c3c28..612fe5872 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/util/tree/TreeUtils.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/util/tree/TreeUtils.java @@ -30,15 +30,16 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import lombok.experimental.UtilityClass; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * @author Hccake 2020/6/21 17:21 */ -@UtilityClass -public class TreeUtils { +public final class TreeUtils { + + private TreeUtils() { + } /** * 根据一个TreeNode集合,返回构建好的树列表 @@ -48,7 +49,7 @@ public class TreeUtils { * @param TreeNodeId的类型 * @return 树列表 */ - public , I> List buildTree(List nodes, I rootId) { + public static , I> List buildTree(List nodes, I rootId) { return TreeUtils.buildTree(nodes, rootId, Function.identity(), null); } @@ -61,7 +62,8 @@ public , I> List buildTree(List nodes, I rootId) { * @param TreeNodeId的类型 * @return 树列表 */ - public , I> List buildTree(List nodes, I rootId, Comparator comparator) { + public static , I> List buildTree(List nodes, I rootId, + Comparator comparator) { return TreeUtils.buildTree(nodes, rootId, Function.identity(), comparator); } @@ -75,7 +77,8 @@ public , I> List buildTree(List nodes, I rootId, Com * @param 源数据类型 * @return 树列表 */ - public , I, R> List buildTree(List list, I rootId, Function convertToTree) { + public static , I, R> List buildTree(List list, I rootId, + Function convertToTree) { return TreeUtils.buildTree(list, rootId, convertToTree, null); } @@ -90,7 +93,7 @@ public , I, R> List buildTree(List list, I rootId, F * @param 源数据类型 * @return 树列表 */ - public , I, R> List buildTree(List list, I rootId, Function convertToTree, + public static , I, R> List buildTree(List list, I rootId, Function convertToTree, Comparator comparator) { if (list == null || list.isEmpty()) { return new ArrayList<>(); @@ -120,7 +123,7 @@ public , I, R> List buildTree(List list, I rootId, F * @param parent 父节点 * @param childrenMap 子节点集合Map(k: parentId, v: Node) */ - public , I> void setChildren(T parent, Map> childrenMap) { + public static , I> void setChildren(T parent, Map> childrenMap) { I parentId = parent.getKey(); List children = childrenMap.get(parentId); // 如果有孩子节点则赋值,且给孩子节点的孩子节点赋值 @@ -140,7 +143,7 @@ public , I> void setChildren(T parent, Map> chi * @param 树节点的 id 类型 * @return 叶子节点 */ - public , I> List getLeafs(T parent) { + public static , I> List getLeafs(T parent) { List leafs = new ArrayList<>(); fillLeaf(parent, leafs); return leafs; @@ -152,7 +155,7 @@ public , I> List getLeafs(T parent) { * @param leafs 叶子节点列表 * @param 实际节点类型 */ - public , I> void fillLeaf(T parent, List leafs) { + public static , I> void fillLeaf(T parent, List leafs) { List children = parent.getChildren(); // 如果节点没有子节点则说明为叶子节点 if (CollectionUtils.isEmpty(children)) { @@ -172,7 +175,7 @@ public , I> void fillLeaf(T parent, List leafs) { * @param TreeNodeId 类型 * @return List 节点Id列表 */ - public , I> List getTreeNodeIds(List treeList) { + public static , I> List getTreeNodeIds(List treeList) { List ids = new ArrayList<>(); fillTreeNodeIds(ids, treeList); return ids; @@ -185,7 +188,7 @@ public , I> List getTreeNodeIds(List treeList) { * @param TreeNode实现类 * @param TreeNodeId 类型 */ - public , I> void fillTreeNodeIds(List ids, List treeList) { + public static , I> void fillTreeNodeIds(List ids, List treeList) { // 如果节点没有子节点则说明为叶子节点 if (CollectionUtils.isEmpty(treeList)) { return; @@ -206,7 +209,7 @@ public , I> void fillTreeNodeIds(List ids, List tree * @param 树节点的 id 类型 * @return 所有树节点组成的列表 */ - public , I> List treeToList(T treeNode) { + public static , I> List treeToList(T treeNode) { return treeToList(treeNode, Function.identity()); } @@ -219,7 +222,7 @@ public , I> List treeToList(T treeNode) { * @param 转换器转换后的类型 * @return List */ - public , I, R> List treeToList(T treeNode, Function converter) { + public static , I, R> List treeToList(T treeNode, Function converter) { List list = new ArrayList<>(); // 使用队列存储未处理的树节点 @@ -254,7 +257,7 @@ public , I, R> List treeToList(T treeNode, Function 树节点的 id 类型 * @return 所有树节点组成的列表 */ - public , I> List treeToList(List treeNodes) { + public static , I> List treeToList(List treeNodes) { return treeToList(treeNodes, Function.identity()); } @@ -267,7 +270,7 @@ public , I> List treeToList(List treeNodes) { * @param 转换器转换后的类型 * @return 所有树节点组成的列表 */ - public , I, R> List treeToList(List treeNodes, Function converter) { + public static , I, R> List treeToList(List treeNodes, Function converter) { return treeNodes.stream() .map(node -> treeToList(node, converter)) .flatMap(Collection::stream) @@ -281,7 +284,7 @@ public , I, R> List treeToList(List treeNodes, Funct * @param matcher 匹配规则 * @return 剪枝完成后的树节点列表 */ - public , I> List pruneTree(List treeNodes, Predicate matcher) { + public static , I> List pruneTree(List treeNodes, Predicate matcher) { List result = new ArrayList<>(); if (CollectionUtils.isEmpty(treeNodes)) { return result; @@ -307,7 +310,7 @@ else if (matcher.test(treeNode)) { * @param matcher 匹配规则 * @return 剪枝完成后的树节点 */ - public , I> T pruneTree(T treeNode, Predicate matcher) { + public static , I> T pruneTree(T treeNode, Predicate matcher) { List children = pruneTree(treeNode.getChildren(), matcher); boolean childrenMatched = !CollectionUtils.isEmpty(children); if (childrenMatched) { @@ -320,7 +323,7 @@ public , I> T pruneTree(T treeNode, Predicate matcher) /** * 遍历树节点(深度优先) */ - public , I> void forEachDFS(T treeNode, T parentTreeNode, BiConsumer action) { + public static , I> void forEachDFS(T treeNode, T parentTreeNode, BiConsumer action) { action.accept(treeNode, parentTreeNode); List children = treeNode.getChildren(); forEachDFS(children, parentTreeNode, action); @@ -329,7 +332,8 @@ public , I> void forEachDFS(T treeNode, T parentTreeNode, /** * 遍历树节点(深度优先) */ - public , I> void forEachDFS(List treeNodes, T parentTreeNode, BiConsumer action) { + public static , I> void forEachDFS(List treeNodes, T parentTreeNode, + BiConsumer action) { if (treeNodes == null || treeNodes.isEmpty()) { return; } diff --git a/common/ballcat-common-util/src/main/java/org/ballcat/common/value/WaitValue.java b/common/ballcat-common-util/src/main/java/org/ballcat/common/value/WaitValue.java index 063456c30..a47a5dfd3 100644 --- a/common/ballcat-common-util/src/main/java/org/ballcat/common/value/WaitValue.java +++ b/common/ballcat-common-util/src/main/java/org/ballcat/common/value/WaitValue.java @@ -53,9 +53,9 @@ public void update(T t) throws InterruptedException { } public void update(UnaryOperator operator) throws InterruptedException { - lock.runByInterruptibly(() -> { - value = operator.apply(value); - lock.signalAll(); + this.lock.runByInterruptibly(() -> { + this.value = operator.apply(this.value); + this.lock.signalAll(); }); } @@ -84,18 +84,18 @@ else if (v instanceof String) { } public T wait(Predicate predicate) throws InterruptedException { - lock.lockInterruptibly(); + this.lock.lockInterruptibly(); try { while (true) { - if (predicate.test(value)) { - return value; + if (predicate.test(this.value)) { + return this.value; } - lock.await(1, TimeUnit.HOURS); + this.lock.await(1, TimeUnit.HOURS); } } finally { - lock.unlock(); + this.lock.unlock(); } } diff --git a/common/ballcat-common-util/src/main/java/org/bson/types/ObjectId.java b/common/ballcat-common-util/src/main/java/org/bson/types/ObjectId.java index 20dda72ae..25bddaa5c 100644 --- a/common/ballcat-common-util/src/main/java/org/bson/types/ObjectId.java +++ b/common/ballcat-common-util/src/main/java/org/bson/types/ObjectId.java @@ -234,10 +234,10 @@ public ObjectId(final ByteBuffer buffer) { // Note: Cannot use ByteBuffer.getInt because it depends on tbe buffer's byte // order // and ObjectId's are always in big-endian order. - timestamp = makeInt(buffer.get(), buffer.get(), buffer.get(), buffer.get()); - randomValue1 = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get()); - randomValue2 = makeShort(buffer.get(), buffer.get()); - counter = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get()); + this.timestamp = makeInt(buffer.get(), buffer.get(), buffer.get(), buffer.get()); + this.randomValue1 = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get()); + this.randomValue2 = makeShort(buffer.get(), buffer.get()); + this.counter = makeInt((byte) 0, buffer.get(), buffer.get(), buffer.get()); } /** @@ -267,18 +267,18 @@ public void putToByteBuffer(final ByteBuffer buffer) { throw new IllegalArgumentException("state should be: buffer.remaining() >=12"); } - buffer.put(int3(timestamp)); - buffer.put(int2(timestamp)); - buffer.put(int1(timestamp)); - buffer.put(int0(timestamp)); - buffer.put(int2(randomValue1)); - buffer.put(int1(randomValue1)); - buffer.put(int0(randomValue1)); - buffer.put(short1(randomValue2)); - buffer.put(short0(randomValue2)); - buffer.put(int2(counter)); - buffer.put(int1(counter)); - buffer.put(int0(counter)); + buffer.put(int3(this.timestamp)); + buffer.put(int2(this.timestamp)); + buffer.put(int1(this.timestamp)); + buffer.put(int0(this.timestamp)); + buffer.put(int2(this.randomValue1)); + buffer.put(int1(this.randomValue1)); + buffer.put(int0(this.randomValue1)); + buffer.put(short1(this.randomValue2)); + buffer.put(short0(this.randomValue2)); + buffer.put(int2(this.counter)); + buffer.put(int1(this.counter)); + buffer.put(int0(this.counter)); } /** @@ -286,7 +286,7 @@ public void putToByteBuffer(final ByteBuffer buffer) { * @return the timestamp */ public int getTimestamp() { - return timestamp; + return this.timestamp; } /** @@ -294,7 +294,7 @@ public int getTimestamp() { * @return the Date */ public Date getDate() { - return new Date((timestamp & 0xFFFFFFFFL) * 1000L); + return new Date((this.timestamp & 0xFFFFFFFFL) * 1000L); } /** @@ -322,18 +322,18 @@ public boolean equals(final Object o) { ObjectId objectId = (ObjectId) o; - if (counter != objectId.counter) { + if (this.counter != objectId.counter) { return false; } - if (timestamp != objectId.timestamp) { + if (this.timestamp != objectId.timestamp) { return false; } - if (randomValue1 != objectId.randomValue1) { + if (this.randomValue1 != objectId.randomValue1) { return false; } - if (randomValue2 != objectId.randomValue2) { + if (this.randomValue2 != objectId.randomValue2) { return false; } @@ -342,10 +342,10 @@ public boolean equals(final Object o) { @Override public int hashCode() { - int result = timestamp; - result = 31 * result + counter; - result = 31 * result + randomValue1; - result = 31 * result + randomValue2; + int result = this.timestamp; + result = 31 * result + this.counter; + result = 31 * result + this.randomValue1; + result = 31 * result + this.randomValue2; return result; } @@ -402,11 +402,11 @@ private static class SerializationProxy implements Serializable { private final byte[] bytes; SerializationProxy(final ObjectId objectId) { - bytes = objectId.toByteArray(); + this.bytes = objectId.toByteArray(); } private Object readResolve() { - return new ObjectId(bytes); + return new ObjectId(this.bytes); } } @@ -494,4 +494,4 @@ private static byte short0(final short x) { return (byte) (x); } -} \ No newline at end of file +} diff --git a/common/ballcat-common-util/src/test/java/org/ballcat/common/util/TreeUtilsTest.java b/common/ballcat-common-util/src/test/java/org/ballcat/common/util/TreeUtilsTest.java index 4618ec798..cf0709002 100644 --- a/common/ballcat-common-util/src/test/java/org/ballcat/common/util/TreeUtilsTest.java +++ b/common/ballcat-common-util/src/test/java/org/ballcat/common/util/TreeUtilsTest.java @@ -74,6 +74,8 @@ void treeTest() { Assertions.assertEquals(list, abstractIdTreeNodes); } + @lombok.Setter + @lombok.Getter static class TestTreeNode implements TreeNode { /** @@ -93,12 +95,12 @@ static class TestTreeNode implements TreeNode { @Override public Long getKey() { - return id; + return this.id; } @Override public Long getParentKey() { - return parentId; + return this.parentId; } @Override @@ -110,23 +112,7 @@ public > void setChildren(List children) { @Override @SuppressWarnings("unchecked") public > List getChildren() { - return (List) children; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Long getParentId() { - return parentId; - } - - public void setParentId(Long parentId) { - this.parentId = parentId; + return (List) this.children; } } diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DataPermissionRule.java b/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DataPermissionRule.java index be3a8ab92..eb3d8a65c 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DataPermissionRule.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DataPermissionRule.java @@ -56,7 +56,7 @@ public DataPermissionRule(DataPermission dataPermission) { * @return boolean 默认返回 false */ public boolean ignore() { - return ignore; + return this.ignore; } /** @@ -65,7 +65,7 @@ public boolean ignore() { * @return 资源类型数组 */ public String[] includeResources() { - return includeResources; + return this.includeResources; } /** @@ -74,7 +74,7 @@ public String[] includeResources() { * @return 资源类型数组 */ public String[] excludeResources() { - return excludeResources; + return this.excludeResources; } public DataPermissionRule setIgnore(boolean ignore) { diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DefaultDataPermissionHandler.java b/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DefaultDataPermissionHandler.java index 5f35e4d89..a4ccf8661 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DefaultDataPermissionHandler.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/handler/DefaultDataPermissionHandler.java @@ -45,7 +45,7 @@ public class DefaultDataPermissionHandler implements DataPermissionHandler { */ @Override public List dataScopes() { - return dataScopes; + return this.dataScopes; } /** @@ -85,7 +85,7 @@ public boolean ignorePermissionControl(List dataScopeList, String map */ protected List filterDataScopes(DataPermissionRule dataPermissionRule) { if (dataPermissionRule == null) { - return dataScopes; + return this.dataScopes; } if (dataPermissionRule.ignore()) { @@ -95,16 +95,16 @@ protected List filterDataScopes(DataPermissionRule dataPermissionRule // 当指定了只包含的资源时,只对该资源的DataScope if (dataPermissionRule.includeResources().length > 0) { Set a = new HashSet<>(Arrays.asList(dataPermissionRule.includeResources())); - return dataScopes.stream().filter(x -> a.contains(x.getResource())).collect(Collectors.toList()); + return this.dataScopes.stream().filter(x -> a.contains(x.getResource())).collect(Collectors.toList()); } // 当未指定只包含的资源,且指定了排除的资源时,则排除此部分资源的 DataScope if (dataPermissionRule.excludeResources().length > 0) { Set a = new HashSet<>(Arrays.asList(dataPermissionRule.excludeResources())); - return dataScopes.stream().filter(x -> !a.contains(x.getResource())).collect(Collectors.toList()); + return this.dataScopes.stream().filter(x -> !a.contains(x.getResource())).collect(Collectors.toList()); } - return dataScopes; + return this.dataScopes; } } diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/interceptor/DataPermissionInterceptor.java b/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/interceptor/DataPermissionInterceptor.java index 6805d1a33..948119193 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/interceptor/DataPermissionInterceptor.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/main/java/org/ballcat/datascope/interceptor/DataPermissionInterceptor.java @@ -62,13 +62,13 @@ public Object intercept(Invocation invocation) throws Throwable { String mappedStatementId = ms.getId(); // 获取当前需要控制的 dataScope 集合 - List filterDataScopes = dataPermissionHandler.filterDataScopes(mappedStatementId); + List filterDataScopes = this.dataPermissionHandler.filterDataScopes(mappedStatementId); if (filterDataScopes == null || filterDataScopes.isEmpty()) { return invocation.proceed(); } // 根据用户权限判断是否需要拦截,例如管理员可以查看所有,则直接放行 - if (dataPermissionHandler.ignorePermissionControl(filterDataScopes, mappedStatementId)) { + if (this.dataPermissionHandler.ignorePermissionControl(filterDataScopes, mappedStatementId)) { return invocation.proceed(); } @@ -77,14 +77,14 @@ public Object intercept(Invocation invocation) throws Throwable { try { // 根据 DataScopes 进行数据权限的 sql 处理 if (sct == SqlCommandType.SELECT) { - mpBs.sql(dataScopeSqlProcessor.parserSingle(mpBs.sql(), filterDataScopes)); + mpBs.sql(this.dataScopeSqlProcessor.parserSingle(mpBs.sql(), filterDataScopes)); } else if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) { - mpBs.sql(dataScopeSqlProcessor.parserMulti(mpBs.sql(), filterDataScopes)); + mpBs.sql(this.dataScopeSqlProcessor.parserMulti(mpBs.sql(), filterDataScopes)); } // 如果解析后发现当前 mappedStatementId 对应的 sql,没有任何数据权限匹配,则记录下来,后续可以直接跳过不解析 Integer matchNum = DataScopeMatchNumHolder.pollMatchNum(); - List allDataScopes = dataPermissionHandler.dataScopes(); + List allDataScopes = this.dataPermissionHandler.dataScopes(); if (allDataScopes.size() == filterDataScopes.size() && matchNum != null && matchNum == 0) { MappedStatementIdsWithoutDataScope.addToWithoutSet(filterDataScopes, mappedStatementId); } diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datapermission/DataPermissionTest.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datapermission/DataPermissionTest.java index 13cf6b9c6..ba19abfd2 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datapermission/DataPermissionTest.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datapermission/DataPermissionTest.java @@ -39,7 +39,7 @@ class DataPermissionTest { @Test void testAnnotationMatchingPointcut() throws NoSuchMethodException { - MethodMatcher methodMatcher = dataPermissionAnnotationAdvisor.getPointcut().getMethodMatcher(); + MethodMatcher methodMatcher = this.dataPermissionAnnotationAdvisor.getPointcut().getMethodMatcher(); boolean match = methodMatcher.matches(TestServiceImpl.class.getMethod("methodA"), TestServiceImpl.class); Assertions.assertTrue(match, "切点未正确匹配被注解的方法"); } @@ -47,17 +47,17 @@ void testAnnotationMatchingPointcut() throws NoSuchMethodException { @Test void test() { // 使用方法本身注解 - DataPermissionRule dataPermissionA = testService.methodA(); + DataPermissionRule dataPermissionA = this.testService.methodA(); Assertions.assertArrayEquals(new String[] { "order" }, dataPermissionA.excludeResources(), "dataPermission 解析错误"); // 继承自类注解 - DataPermissionRule dataPermissionB = testService.methodB(); + DataPermissionRule dataPermissionB = this.testService.methodB(); Assertions.assertArrayEquals(new String[] { "class" }, dataPermissionB.excludeResources(), "dataPermission 解析错误"); // 继承自类注解 - DataPermissionRule dataPermissionC = testService.methodC(); + DataPermissionRule dataPermissionC = this.testService.methodC(); Assertions.assertArrayEquals(new String[] { "class" }, dataPermissionC.excludeResources(), "dataPermission 解析错误"); diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/StudentMapperTest.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/StudentMapperTest.java index 7a02a7a90..73bcf0d21 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/StudentMapperTest.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/StudentMapperTest.java @@ -81,21 +81,21 @@ void testExclude() { DataPermissionRule dataPermissionRule = new DataPermissionRule() .setExcludeResources(new String[] { ClassDataScope.RESOURCE_NAME, SchoolDataScope.RESOURCE_NAME }); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule, - () -> Assertions.assertEquals(10, studentService.listStudent().size())); + () -> Assertions.assertEquals(10, this.studentService.listStudent().size())); Integer size = DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule, - () -> studentService.listStudent().size()); + () -> this.studentService.listStudent().size()); Assertions.assertEquals(10, size); // 再使用完整的 datascope 规则进行查询 - List studentList1 = studentService.listStudent(); + List studentList1 = this.studentService.listStudent(); Assertions.assertEquals(2, studentList1.size()); } @Test void testTeacherSelect() { // 实验中学,一班总共有 2 名学生 - List studentList1 = studentService.listStudent(); + List studentList1 = this.studentService.listStudent(); Assertions.assertEquals(2, studentList1.size()); // 更改当前登录用户权限,让它只能看德高中学的学生 @@ -103,14 +103,15 @@ void testTeacherSelect() { loginUser.setSchoolNameList(Collections.singletonList("德高中学")); // 德高中学,一班总共有 3 名学生 - List studentList2 = studentService.listStudent(); + List studentList2 = this.studentService.listStudent(); Assertions.assertEquals(3, studentList2.size()); /* 忽略权限控制,一共有 10 名学生 */ // === 编程式 === - DataPermissionUtils.executeAndIgnoreAll(() -> Assertions.assertEquals(10, studentService.listStudent().size())); + DataPermissionUtils + .executeAndIgnoreAll(() -> Assertions.assertEquals(10, this.studentService.listStudent().size())); // === 注解 ==== - List studentList4 = studentService.listStudentWithoutDataPermission(); + List studentList4 = this.studentService.listStudentWithoutDataPermission(); Assertions.assertEquals(10, studentList4.size()); /* 只控制班级的数据权限,实验中学 + 德高中学 一班总共有 5 名学生 */ @@ -118,9 +119,9 @@ void testTeacherSelect() { DataPermissionRule dataPermissionRule1 = new DataPermissionRule() .setIncludeResources(new String[] { ClassDataScope.RESOURCE_NAME }); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule1, - () -> Assertions.assertEquals(5, studentService.listStudent().size())); + () -> Assertions.assertEquals(5, this.studentService.listStudent().size())); // === 注解 ==== - List studentList5 = studentService.listStudentOnlyFilterClass(); + List studentList5 = this.studentService.listStudentOnlyFilterClass(); Assertions.assertEquals(5, studentList5.size()); /* 只控制学校的数据权限,"德高中学"、一班、二班 总共有 6 名学生 */ @@ -128,9 +129,9 @@ void testTeacherSelect() { DataPermissionRule dataPermissionRule2 = new DataPermissionRule() .setIncludeResources(new String[] { SchoolDataScope.RESOURCE_NAME }); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule2, - () -> Assertions.assertEquals(6, studentService.listStudent().size())); + () -> Assertions.assertEquals(6, this.studentService.listStudent().size())); // === 注解 ==== - List studentList6 = studentService.listStudentOnlyFilterSchool(); + List studentList6 = this.studentService.listStudentOnlyFilterSchool(); Assertions.assertEquals(6, studentList6.size()); } @@ -143,13 +144,13 @@ void testStudentSelect() { // id 为 1 的学生叫 张三 loginUser.setId(1L); - List studentList1 = studentService.listStudent(); + List studentList1 = this.studentService.listStudent(); Assertions.assertEquals(1, studentList1.size()); Assertions.assertEquals("张三", studentList1.get(0).getName()); // id 为 2 的学生叫 李四 loginUser.setId(2L); - List studentList2 = studentService.listStudent(); + List studentList2 = this.studentService.listStudent(); Assertions.assertEquals(1, studentList2.size()); Assertions.assertEquals("李四", studentList2.get(0).getName()); @@ -161,7 +162,7 @@ void testStudentSelect() { @Test void testRulePriority() { // 全局数据权限,默认是全部 DataScope 都控制 - List studentList = studentService.listStudent(); + List studentList = this.studentService.listStudent(); Assertions.assertEquals(2, studentList.size()); // 编程式数据权限, @@ -169,21 +170,21 @@ void testRulePriority() { .setIncludeResources(new String[] { ClassDataScope.RESOURCE_NAME }); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule, () -> { // 编程式数据权限内部方法,走指定的规则 - List studentList2 = studentService.listStudent(); + List studentList2 = this.studentService.listStudent(); Assertions.assertEquals(5, studentList2.size()); // 嵌套的权限控制 DataPermissionRule dataPermissionRule1 = new DataPermissionRule(true); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule1, () -> { // 规则嵌套时,优先使用内部规则 - List studentList1 = studentService.listStudent(); + List studentList1 = this.studentService.listStudent(); Assertions.assertEquals(10, studentList1.size()); // 由于调用的方法上添加了注解,走该方法注解的权限规则 - List students1 = studentService.listStudentOnlyFilterClass(); + List students1 = this.studentService.listStudentOnlyFilterClass(); Assertions.assertEquals(5, students1.size()); // 注解权限控制 - List students2 = studentService.listStudentOnlyFilterSchool(); + List students2 = this.studentService.listStudentOnlyFilterSchool(); Assertions.assertEquals(4, students2.size()); }); }); @@ -193,20 +194,20 @@ void testRulePriority() { void testExecuteWithDataPermissionRule() { DataPermissionUtils.executeAndIgnoreAll(() -> { - List dataScopes = dataPermissionHandler.filterDataScopes(null); + List dataScopes = this.dataPermissionHandler.filterDataScopes(null); Assertions.assertTrue(dataScopes.isEmpty()); }); DataPermissionRule dataPermissionRule = new DataPermissionRule(true); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule, () -> { - List dataScopes = dataPermissionHandler.filterDataScopes(null); + List dataScopes = this.dataPermissionHandler.filterDataScopes(null); Assertions.assertTrue(dataScopes.isEmpty()); }); DataPermissionRule dataPermissionRule1 = new DataPermissionRule() .setIncludeResources(new String[] { ClassDataScope.RESOURCE_NAME }); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule1, () -> { - List dataScopes = dataPermissionHandler.filterDataScopes(null); + List dataScopes = this.dataPermissionHandler.filterDataScopes(null); Assertions.assertFalse(dataScopes.isEmpty()); Assertions.assertEquals(1, dataScopes.size()); Assertions.assertEquals(ClassDataScope.RESOURCE_NAME, dataScopes.get(0).getResource()); @@ -215,7 +216,7 @@ void testExecuteWithDataPermissionRule() { DataPermissionRule dataPermissionRule2 = new DataPermissionRule() .setExcludeResources(new String[] { SchoolDataScope.RESOURCE_NAME, StudentDataScope.RESOURCE_NAME }); DataPermissionUtils.executeWithDataPermissionRule(dataPermissionRule2, () -> { - List dataScopes = dataPermissionHandler.filterDataScopes(null); + List dataScopes = this.dataPermissionHandler.filterDataScopes(null); Assertions.assertFalse(dataScopes.isEmpty()); Assertions.assertEquals(1, dataScopes.size()); Assertions.assertEquals(ClassDataScope.RESOURCE_NAME, dataScopes.get(0).getResource()); diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/ClassDataScope.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/ClassDataScope.java index a03210f88..ffaf88995 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/ClassDataScope.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/ClassDataScope.java @@ -50,7 +50,7 @@ public class ClassDataScope implements DataScope { private final Set tableNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); public ClassDataScope() { - tableNames.addAll(Arrays.asList("h2student", "h2teacher")); + this.tableNames.addAll(Arrays.asList("h2student", "h2teacher")); } @Override @@ -61,7 +61,7 @@ public String getResource() { @Override public boolean includes(String tableName) { // 使用 new TreeSet<>(String.CASE_INSENSITIVE_ORDER) 的形式判断,可忽略表名大小写 - return tableNames.contains(tableName); + return this.tableNames.contains(tableName); } @Override @@ -85,7 +85,7 @@ public Expression getExpression(String tableName, Alias tableAlias) { .stream() .map(StringValue::new) .collect(Collectors.toList()); - Column column = new Column(tableAlias == null ? columnId : tableAlias.getName() + "." + columnId); + Column column = new Column(tableAlias == null ? this.columnId : tableAlias.getName() + "." + this.columnId); ExpressionList expressionList = new ExpressionList(); expressionList.setExpressions(list); return new InExpression(column, expressionList); diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/SchoolDataScope.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/SchoolDataScope.java index f5922481c..2e1327349 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/SchoolDataScope.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/datascope/SchoolDataScope.java @@ -76,7 +76,7 @@ public Expression getExpression(String tableName, Alias tableAlias) { .stream() .map(StringValue::new) .collect(Collectors.toList()); - Column column = new Column(tableAlias == null ? columnId : tableAlias.getName() + "." + columnId); + Column column = new Column(tableAlias == null ? this.columnId : tableAlias.getName() + "." + this.columnId); ExpressionList expressionList = new ExpressionList(); expressionList.setExpressions(list); return new InExpression(column, expressionList); diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/service/StudentService.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/service/StudentService.java index 92198d172..9c1515c70 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/service/StudentService.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datarule/service/StudentService.java @@ -36,22 +36,22 @@ public class StudentService { private StudentMapper studentMapper; public List listStudent() { - return studentMapper.listStudent(); + return this.studentMapper.listStudent(); } @DataPermission(includeResources = ClassDataScope.RESOURCE_NAME) public List listStudentOnlyFilterClass() { - return studentMapper.listStudent(); + return this.studentMapper.listStudent(); } @DataPermission(includeResources = SchoolDataScope.RESOURCE_NAME) public List listStudentOnlyFilterSchool() { - return studentMapper.listStudent(); + return this.studentMapper.listStudent(); } @DataPermission(ignore = true) public List listStudentWithoutDataPermission() { - return studentMapper.listStudent(); + return this.studentMapper.listStudent(); } } diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/DataScopeMatchTest.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/DataScopeMatchTest.java index bf29a19da..a7a85853f 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/DataScopeMatchTest.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/DataScopeMatchTest.java @@ -53,7 +53,7 @@ public boolean includes(String tableName) { @Override public Expression getExpression(String tableName, Alias tableAlias) { - Column column = new Column(tableAlias == null ? columnId : tableAlias.getName() + "." + columnId); + Column column = new Column(tableAlias == null ? this.columnId : tableAlias.getName() + "." + this.columnId); ExpressionList expressionList = new ExpressionList(); expressionList.setExpressions(Arrays.asList(new StringValue("1"), new StringValue("2"))); return new InExpression(column, expressionList); @@ -61,7 +61,7 @@ public Expression getExpression(String tableName, Alias tableAlias) { }; DataPermissionHandler dataPermissionHandler = new DefaultDataPermissionHandler( - Collections.singletonList(dataScope)); + Collections.singletonList(this.dataScope)); DataScopeSqlProcessor dataScopeSqlProcessor = new DataScopeSqlProcessor(); @@ -73,7 +73,7 @@ void testMatchNum() { DataScopeMatchNumHolder.initMatchNum(); try { - String parseSql = dataScopeSqlProcessor.parserSingle(sql, dataPermissionHandler.dataScopes()); + String parseSql = this.dataScopeSqlProcessor.parserSingle(sql, this.dataPermissionHandler.dataScopes()); System.out.println(parseSql); Integer matchNum = DataScopeMatchNumHolder.pollMatchNum(); @@ -93,7 +93,7 @@ void testNoMatch() { + "where oi.order_price > 100"; DataScopeMatchNumHolder.initMatchNum(); try { - String parseSql = dataScopeSqlProcessor.parserSingle(sql, dataPermissionHandler.dataScopes()); + String parseSql = this.dataScopeSqlProcessor.parserSingle(sql, this.dataPermissionHandler.dataScopes()); System.out.println(parseSql); Integer matchNum = DataScopeMatchNumHolder.pollMatchNum(); @@ -120,7 +120,7 @@ void testNestedMatchNum() { testNoMatch(); - String parseSql = dataScopeSqlProcessor.parserSingle(sql, dataPermissionHandler.dataScopes()); + String parseSql = this.dataScopeSqlProcessor.parserSingle(sql, this.dataPermissionHandler.dataScopes()); System.out.println(parseSql); Integer matchNum = DataScopeMatchNumHolder.pollMatchNum(); diff --git a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/SqlParseTest.java b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/SqlParseTest.java index 6006c08d3..720f8624f 100644 --- a/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/SqlParseTest.java +++ b/datascope/ballcat-spring-boot-starter-datascope/src/test/java/org/ballcat/datascope/test/datascope/SqlParseTest.java @@ -42,7 +42,7 @@ class SqlParseTest { DataScope tenantDataScope = new TenantDataScope(); DataPermissionHandler dataPermissionHandler = new DefaultDataPermissionHandler( - Collections.singletonList(tenantDataScope)); + Collections.singletonList(this.tenantDataScope)); DataScopeSqlProcessor dataScopeSqlProcessor = new DataScopeSqlProcessor(); @@ -350,13 +350,13 @@ void testJsqlParseAlias() { String sql = "SELECT\n" + "r.id, r.name, r.code, r.type, r.scope_type, r.scope_resources\n" + "FROM\n" + "sys_user_role ur\n" + "left join\n" + "sys_role r\n" + "on r.code = ur.role_code\n" + "WHERE ur.user_id = ?\n" + "and r.deleted = 0"; - Assertions - .assertDoesNotThrow(() -> dataScopeSqlProcessor.parserSingle(sql, dataPermissionHandler.dataScopes())); + Assertions.assertDoesNotThrow( + () -> this.dataScopeSqlProcessor.parserSingle(sql, this.dataPermissionHandler.dataScopes())); } void assertSql(String sql, String targetSql) { - String parsedSql = dataScopeSqlProcessor.parserSingle(sql, dataPermissionHandler.dataScopes()); + String parsedSql = this.dataScopeSqlProcessor.parserSingle(sql, this.dataPermissionHandler.dataScopes()); Assertions.assertEquals(targetSql, parsedSql); } @@ -381,7 +381,7 @@ public boolean includes(String tableName) { @Override public Expression getExpression(String tableName, Alias tableAlias) { - Column column = SqlParseUtils.getAliasColumn(tableName, tableAlias, columnName); + Column column = SqlParseUtils.getAliasColumn(tableName, tableAlias, this.columnName); return new EqualsTo(column, new LongValue("1")); } diff --git a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/AnnotationHandlerHolder.java b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/AnnotationHandlerHolder.java index 561c9a87e..4062e5142 100644 --- a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/AnnotationHandlerHolder.java +++ b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/AnnotationHandlerHolder.java @@ -46,9 +46,9 @@ public final class AnnotationHandlerHolder { private final Map, DesensitizeFunction> annotationHandlers; private AnnotationHandlerHolder() { - annotationHandlers = new ConcurrentHashMap<>(); + this.annotationHandlers = new ConcurrentHashMap<>(); - annotationHandlers.put(JsonSimpleDesensitize.class, (annotation, value) -> { + this.annotationHandlers.put(JsonSimpleDesensitize.class, (annotation, value) -> { // Simple 类型处理 JsonSimpleDesensitize an = (JsonSimpleDesensitize) annotation; Class handlerClass = an.handler(); @@ -60,7 +60,7 @@ private AnnotationHandlerHolder() { return desensitizationHandler.handle(value); }); - annotationHandlers.put(JsonRegexDesensitize.class, (annotation, value) -> { + this.annotationHandlers.put(JsonRegexDesensitize.class, (annotation, value) -> { // 正则类型脱敏处理 JsonRegexDesensitize an = (JsonRegexDesensitize) annotation; RegexDesensitizationTypeEnum type = an.type(); @@ -71,7 +71,7 @@ private AnnotationHandlerHolder() { : regexDesensitizationHandler.handle(value, type); }); - annotationHandlers.put(JsonSlideDesensitize.class, (annotation, value) -> { + this.annotationHandlers.put(JsonSlideDesensitize.class, (annotation, value) -> { // 滑动类型脱敏处理 JsonSlideDesensitize an = (JsonSlideDesensitize) annotation; SlideDesensitizationTypeEnum type = an.type(); diff --git a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/DesensitizationHandlerHolder.java b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/DesensitizationHandlerHolder.java index 13b72d06d..3b8fb50d8 100644 --- a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/DesensitizationHandlerHolder.java +++ b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/DesensitizationHandlerHolder.java @@ -42,16 +42,16 @@ public final class DesensitizationHandlerHolder { private final Map, DesensitizationHandler> desensitizationHandlerMap; private DesensitizationHandlerHolder() { - desensitizationHandlerMap = new ConcurrentHashMap<>(16); + this.desensitizationHandlerMap = new ConcurrentHashMap<>(16); // 滑动脱敏处理器 - desensitizationHandlerMap.put(SlideDesensitizationHandler.class, new SlideDesensitizationHandler()); + this.desensitizationHandlerMap.put(SlideDesensitizationHandler.class, new SlideDesensitizationHandler()); // 正则脱敏处理器 - desensitizationHandlerMap.put(RegexDesensitizationHandler.class, new RegexDesensitizationHandler()); + this.desensitizationHandlerMap.put(RegexDesensitizationHandler.class, new RegexDesensitizationHandler()); // SPI 加载所有的 Simple脱敏类型处理 ServiceLoader loadedDrivers = ServiceLoader .load(SimpleDesensitizationHandler.class); for (SimpleDesensitizationHandler desensitizationHandler : loadedDrivers) { - desensitizationHandlerMap.put(desensitizationHandler.getClass(), desensitizationHandler); + this.desensitizationHandlerMap.put(desensitizationHandler.getClass(), desensitizationHandler); } } diff --git a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializer.java b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializer.java index 6b3a9c254..b053c7d0f 100644 --- a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializer.java +++ b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializer.java @@ -56,17 +56,17 @@ public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvi String fieldName = jsonGenerator.getOutputContext().getCurrentName(); // 未开启脱敏 - if (desensitizeStrategy != null && desensitizeStrategy.ignoreField(fieldName)) { + if (this.desensitizeStrategy != null && this.desensitizeStrategy.ignoreField(fieldName)) { jsonGenerator.writeString(str); return; } DesensitizeFunction handleFunction = AnnotationHandlerHolder - .getHandleFunction(jsonDesensitizeAnnotation.annotationType()); + .getHandleFunction(this.jsonDesensitizeAnnotation.annotationType()); if (handleFunction == null) { jsonGenerator.writeString(str); return; } - jsonGenerator.writeString(handleFunction.desensitize(jsonDesensitizeAnnotation, str)); + jsonGenerator.writeString(handleFunction.desensitize(this.jsonDesensitizeAnnotation, str)); } } diff --git a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializerModifier.java b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializerModifier.java index d7fe919f1..75d262ee8 100644 --- a/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializerModifier.java +++ b/desensitize/ballcat-desensitize/src/main/java/org/ballcat/desensitize/json/JsonDesensitizeSerializerModifier.java @@ -48,7 +48,7 @@ public List changeProperties(SerializationConfig config, Bea Annotation annotation = getDesensitizeAnnotation(beanProperty); if (annotation != null && beanProperty.getType().isTypeOrSubTypeOf(String.class)) { - beanProperty.assignSerializer(new JsonDesensitizeSerializer(annotation, desensitizeStrategy)); + beanProperty.assignSerializer(new JsonDesensitizeSerializer(annotation, this.desensitizeStrategy)); } } return beanProperties; diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkBalancedSender.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkBalancedSender.java index ce5d12a5f..ac712fd87 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkBalancedSender.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkBalancedSender.java @@ -33,19 +33,19 @@ public class DingTalkBalancedSender { public DingTalkBalancedSender add(DingTalkSender... senders) { for (DingTalkSender sender : senders) { - queue.add(sender); + this.queue.add(sender); } return this; } public DingTalkBalancedSender addAll(Collection collection) { - queue.addAll(collection); + this.queue.addAll(collection); return this; } @SneakyThrows protected DingTalkSender sender() { - return queue.poll(); + return this.queue.poll(); } public void send(DingTalkMessage message) { @@ -54,7 +54,7 @@ public void send(DingTalkMessage message) { sender.sendMessage(message); } finally { - queue.add(sender); + this.queue.add(sender); } } diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkResponse.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkResponse.java index 113ac789d..d7c4ba183 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkResponse.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkResponse.java @@ -73,7 +73,7 @@ public static DingTalkResponse of(String res) { @Override public String toString() { - return response; + return this.response; } } diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkSender.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkSender.java index e09483a7a..960fae708 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkSender.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/DingTalkSender.java @@ -82,7 +82,7 @@ public DingTalkSender(String url) { * */ public DingTalkResponse sendMessage(DingTalkMessage message) { - if (!StringUtils.hasText(secret)) { + if (!StringUtils.hasText(this.secret)) { return sendNormalMessage(message); } else { @@ -118,17 +118,17 @@ public DingTalkSender setSecret(String secret) { */ @SneakyThrows({ UnsupportedEncodingException.class, NoSuchAlgorithmException.class, InvalidKeyException.class }) public String secret(long timestamp) { - SecretKeySpec key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); + SecretKeySpec key = new SecretKeySpec(this.secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); - byte[] secretBytes = (timestamp + "\n" + secret).getBytes(StandardCharsets.UTF_8); + byte[] secretBytes = (timestamp + "\n" + this.secret).getBytes(StandardCharsets.UTF_8); byte[] bytes = mac.doFinal(secretBytes); String base64 = java.util.Base64.getEncoder().encodeToString(bytes); String sign = URLEncoder.encode(base64, "UTF-8"); - return String.format("%s×tamp=%s&sign=%s", url, timestamp, sign); + return String.format("%s×tamp=%s&sign=%s", this.url, timestamp, sign); } /** @@ -146,7 +146,7 @@ public DingTalkResponse request(DingTalkMessage dingTalkMessage, boolean isSecre Request request = new Request.Builder().url(requestUrl).post(requestBody).build(); - Call call = client.newCall(request); + Call call = this.client.newCall(request); try (Response response = call.execute()) { ResponseBody responseBody = response.body(); diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/AbstractDingTalkMessage.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/AbstractDingTalkMessage.java index ac9bee85e..a5aac6b7d 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/AbstractDingTalkMessage.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/AbstractDingTalkMessage.java @@ -40,7 +40,7 @@ public abstract class AbstractDingTalkMessage implements DingTalkMessage { private boolean atAll = false; public AbstractDingTalkMessage atAll() { - atAll = true; + this.atAll = true; return this; } @@ -48,7 +48,7 @@ public AbstractDingTalkMessage atAll() { * 添加 at 对象的手机号 */ public AbstractDingTalkMessage addPhone(String phone) { - atPhones.add(phone); + this.atPhones.add(phone); return this; } @@ -68,7 +68,7 @@ public AbstractDingTalkMessage addPhone(String phone) { @Override public String generate() { DingTalkParams params = put(new DingTalkParams().setType(getType().getVal()) - .setAt(new DingTalkParams.At().setAtAll(atAll).setAtMobiles(atPhones))); + .setAt(new DingTalkParams.At().setAtAll(this.atAll).setAtMobiles(this.atPhones))); return params.toString(); } diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkActionCardMessage.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkActionCardMessage.java index b0b8480a3..b00caadab 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkActionCardMessage.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkActionCardMessage.java @@ -69,7 +69,7 @@ public class DingTalkActionCardMessage extends AbstractDingTalkMessage { * 添加按钮 */ public DingTalkActionCardMessage addButton(String title, String url) { - buttons.add(new Button(title, url)); + this.buttons.add(new Button(title, url)); return this; } @@ -80,16 +80,16 @@ public MessageTypeEnum getType() { @Override public DingTalkParams put(DingTalkParams params) { - DingTalkParams.ActionCard card = new DingTalkParams.ActionCard().setTitle(title) - .setText(text.build()) - .setBtnOrientation(orientation.getVal()); + DingTalkParams.ActionCard card = new DingTalkParams.ActionCard().setTitle(this.title) + .setText(this.text.build()) + .setBtnOrientation(this.orientation.getVal()); // 当 单按钮的 文本和链接都不为空时 - if (buttons.isEmpty()) { - card.setSingleTitle(singleTitle).setSingleUrl(singleUrl); + if (this.buttons.isEmpty()) { + card.setSingleTitle(this.singleTitle).setSingleUrl(this.singleUrl); } else { - card.setButtons(buttons); + card.setButtons(this.buttons); } return params.setActionCard(card); } diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkLinkMessage.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkLinkMessage.java index 8dbcc5c7d..ded203913 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkLinkMessage.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkLinkMessage.java @@ -57,8 +57,10 @@ public MessageTypeEnum getType() { @Override public DingTalkParams put(DingTalkParams params) { - return params.setLink( - new DingTalkParams.Link().setText(text).setTitle(title).setPicUrl(picUrl).setMessageUrl(messageUrl)); + return params.setLink(new DingTalkParams.Link().setText(this.text) + .setTitle(this.title) + .setPicUrl(this.picUrl) + .setMessageUrl(this.messageUrl)); } } diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkMarkDownMessage.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkMarkDownMessage.java index f710d2094..f39f08c37 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkMarkDownMessage.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkMarkDownMessage.java @@ -48,7 +48,7 @@ public MessageTypeEnum getType() { @Override public DingTalkParams put(DingTalkParams params) { - return params.setMarkdown(new DingTalkParams.Markdown().setTitle(title).setText(text.build())); + return params.setMarkdown(new DingTalkParams.Markdown().setTitle(this.title).setText(this.text.build())); } } diff --git a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkTextMessage.java b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkTextMessage.java index 7c8585c68..58641f42a 100644 --- a/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkTextMessage.java +++ b/dingtalk/ballcat-dingtalk/src/main/java/org/ballcat/dingtalk/message/DingTalkTextMessage.java @@ -42,7 +42,7 @@ public MessageTypeEnum getType() { @Override public DingTalkParams put(DingTalkParams params) { - return params.setText(new DingTalkParams.Text().setContent(content)); + return params.setText(new DingTalkParams.Text().setContent(this.content)); } } diff --git a/dingtalk/ballcat-dingtalk/src/test/java/org/ballcat/dingtalk/DingTalkTest.java b/dingtalk/ballcat-dingtalk/src/test/java/org/ballcat/dingtalk/DingTalkTest.java index 342b903d8..60339c3de 100644 --- a/dingtalk/ballcat-dingtalk/src/test/java/org/ballcat/dingtalk/DingTalkTest.java +++ b/dingtalk/ballcat-dingtalk/src/test/java/org/ballcat/dingtalk/DingTalkTest.java @@ -40,16 +40,16 @@ class DingTalkTest { @BeforeEach void before() { - sender = new DingTalkSender(webhook).setSecret(secret); + this.sender = new DingTalkSender(this.webhook).setSecret(this.secret); } @Test void send() { - assertTrue(StringUtils.hasText(sender.getUrl())); - assertTrue(StringUtils.hasText(sender.getSecret())); + assertTrue(StringUtils.hasText(this.sender.getUrl())); + assertTrue(StringUtils.hasText(this.sender.getSecret())); DingTalkTextMessage message = new DingTalkTextMessage(); message.setContent("测试机器人消息通知"); - DingTalkResponse response = sender.sendMessage(message); + DingTalkResponse response = this.sender.sendMessage(message); assertTrue(response.isSuccess()); } diff --git a/dingtalk/ballcat-spring-boot-starter-dingtalk/src/main/java/org/ballcat/autoconfigure/dingtalk/DingTalkAutoConfiguration.java b/dingtalk/ballcat-spring-boot-starter-dingtalk/src/main/java/org/ballcat/autoconfigure/dingtalk/DingTalkAutoConfiguration.java index c14bfc47f..a51521f1e 100644 --- a/dingtalk/ballcat-spring-boot-starter-dingtalk/src/main/java/org/ballcat/autoconfigure/dingtalk/DingTalkAutoConfiguration.java +++ b/dingtalk/ballcat-spring-boot-starter-dingtalk/src/main/java/org/ballcat/autoconfigure/dingtalk/DingTalkAutoConfiguration.java @@ -40,7 +40,7 @@ public class DingTalkAutoConfiguration { @Bean @ConditionalOnMissingBean public DingTalkSender dingTalkSender() { - return new DingTalkSender(dingTalkProperties.getUrl()).setSecret(dingTalkProperties.getSecret()); + return new DingTalkSender(this.dingTalkProperties.getUrl()).setSecret(this.dingTalkProperties.getSecret()); } } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ExcelHandlerConfiguration.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ExcelHandlerConfiguration.java index 2a15638f0..52dcc02b4 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ExcelHandlerConfiguration.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ExcelHandlerConfiguration.java @@ -63,7 +63,7 @@ public WriterBuilderEnhancer writerBuilderEnhancer() { @Bean @ConditionalOnMissingBean public SingleSheetWriteHandler singleSheetWriteHandler() { - return new SingleSheetWriteHandler(configProperties, converterProvider, writerBuilderEnhancer()); + return new SingleSheetWriteHandler(this.configProperties, this.converterProvider, writerBuilderEnhancer()); } /** @@ -72,7 +72,7 @@ public SingleSheetWriteHandler singleSheetWriteHandler() { @Bean @ConditionalOnMissingBean public ManySheetWriteHandler manySheetWriteHandler() { - return new ManySheetWriteHandler(configProperties, converterProvider, writerBuilderEnhancer()); + return new ManySheetWriteHandler(this.configProperties, this.converterProvider, writerBuilderEnhancer()); } /** diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ResponseExcelAutoConfiguration.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ResponseExcelAutoConfiguration.java index 84b607b5b..620d033e0 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ResponseExcelAutoConfiguration.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/ResponseExcelAutoConfiguration.java @@ -89,14 +89,14 @@ public EmptyHeadGenerator emptyHeadGenerator() { */ @PostConstruct public void setReturnValueHandlers() { - List returnValueHandlers = requestMappingHandlerAdapter + List returnValueHandlers = this.requestMappingHandlerAdapter .getReturnValueHandlers(); List newHandlers = new ArrayList<>(); - newHandlers.add(responseExcelReturnValueHandler); + newHandlers.add(this.responseExcelReturnValueHandler); assert returnValueHandlers != null; newHandlers.addAll(returnValueHandlers); - requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers); + this.requestMappingHandlerAdapter.setReturnValueHandlers(newHandlers); } /** @@ -104,11 +104,12 @@ public void setReturnValueHandlers() { */ @PostConstruct public void setRequestExcelArgumentResolver() { - List argumentResolvers = requestMappingHandlerAdapter.getArgumentResolvers(); + List argumentResolvers = this.requestMappingHandlerAdapter + .getArgumentResolvers(); List resolverList = new ArrayList<>(); resolverList.add(new RequestExcelArgumentResolver()); resolverList.addAll(argumentResolvers); - requestMappingHandlerAdapter.setArgumentResolvers(resolverList); + this.requestMappingHandlerAdapter.setArgumentResolvers(resolverList); } } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/DynamicNameAspect.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/DynamicNameAspect.java index acb28bde8..d6b2bccd1 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/DynamicNameAspect.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/DynamicNameAspect.java @@ -51,7 +51,7 @@ public void before(JoinPoint point, ResponseExcel excel) { name = LocalDateTime.now().toString(); } else { - name = processor.doDetermineName(point.getArgs(), ms.getMethod(), excel.name()); + name = this.processor.doDetermineName(point.getArgs(), ms.getMethod(), excel.name()); } RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/RequestExcelArgumentResolver.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/RequestExcelArgumentResolver.java index 88ccad9ca..daa609641 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/RequestExcelArgumentResolver.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/RequestExcelArgumentResolver.java @@ -142,7 +142,7 @@ public String resolverSheetName(HttpServletRequest request, Method method, Strin evaluationContext.setVariable(name, request.getParameter(name)); } } - Expression expression = expressionParser.parseExpression(sheetName); + Expression expression = this.expressionParser.parseExpression(sheetName); String value = expression.getValue(evaluationContext, String.class); return value == null || value.isEmpty() ? null : value; } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/ResponseExcelReturnValueHandler.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/ResponseExcelReturnValueHandler.java index f15901624..d2fdbf272 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/ResponseExcelReturnValueHandler.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/aop/ResponseExcelReturnValueHandler.java @@ -68,7 +68,7 @@ public void handleReturnValue(Object o, MethodParameter parameter, ModelAndViewC Assert.state(responseExcel != null, "No @ResponseExcel"); mavContainer.setRequestHandled(true); - sheetWriteHandlerList.stream() + this.sheetWriteHandlerList.stream() .filter(handler -> handler.support(o)) .findFirst() .ifPresent(handler -> handler.export(o, response, responseExcel)); diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/domain/SheetBuildProperties.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/domain/SheetBuildProperties.java index 08c584182..b7661aaf3 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/domain/SheetBuildProperties.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/domain/SheetBuildProperties.java @@ -63,7 +63,7 @@ public SheetBuildProperties(Sheet sheetAnnotation) { public SheetBuildProperties(int index) { this.sheetNo = index; - this.sheetName = "sheet" + (sheetNo + 1); + this.sheetName = "sheet" + (this.sheetNo + 1); } } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/AbstractSheetWriteHandler.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/AbstractSheetWriteHandler.java index 90d6ddf11..bd6ddeca5 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/AbstractSheetWriteHandler.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/AbstractSheetWriteHandler.java @@ -148,8 +148,8 @@ public ExcelWriter getExcelWriter(HttpServletResponse response, ResponseExcel re } // 开启国际化头信息处理 - if (responseExcel.i18nHeader() && i18nHeaderCellWriteHandler != null) { - writerBuilder.registerWriteHandler(i18nHeaderCellWriteHandler); + if (responseExcel.i18nHeader() && this.i18nHeaderCellWriteHandler != null) { + writerBuilder.registerWriteHandler(this.i18nHeaderCellWriteHandler); } // 自定义注入的转换器 @@ -159,7 +159,7 @@ public ExcelWriter getExcelWriter(HttpServletResponse response, ResponseExcel re writerBuilder.registerConverter(BeanUtils.instantiateClass(clazz)); } - String templatePath = configProperties.getTemplatePath(); + String templatePath = this.configProperties.getTemplatePath(); if (StringUtils.hasText(responseExcel.template())) { ClassPathResource classPathResource = new ClassPathResource( templatePath + File.separator + responseExcel.template()); @@ -167,7 +167,8 @@ public ExcelWriter getExcelWriter(HttpServletResponse response, ResponseExcel re writerBuilder.withTemplate(inputStream); } - writerBuilder = excelWriterBuilderEnhance.enhanceExcel(writerBuilder, response, responseExcel, templatePath); + writerBuilder = this.excelWriterBuilderEnhance.enhanceExcel(writerBuilder, response, responseExcel, + templatePath); return writerBuilder.build(); } @@ -177,7 +178,7 @@ public ExcelWriter getExcelWriter(HttpServletResponse response, ResponseExcel re * @param builder ExcelWriterBuilder */ public void registerCustomConverter(ExcelWriterBuilder builder) { - converterProvider.ifAvailable(converters -> converters.forEach(builder::registerConverter)); + this.converterProvider.ifAvailable(converters -> converters.forEach(builder::registerConverter)); } /** @@ -240,8 +241,8 @@ else if (dataClass != null) { } // sheetBuilder 增强 - writerSheetBuilder = excelWriterBuilderEnhance.enhanceSheet(writerSheetBuilder, sheetNo, sheetName, dataClass, - template, headGenerateClass); + writerSheetBuilder = this.excelWriterBuilderEnhance.enhanceSheet(writerSheetBuilder, sheetNo, sheetName, + dataClass, template, headGenerateClass); return writerSheetBuilder.build(); } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/DefaultAnalysisEventListener.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/DefaultAnalysisEventListener.java index 1c83abec5..ca2dc8962 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/DefaultAnalysisEventListener.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/handler/DefaultAnalysisEventListener.java @@ -52,10 +52,10 @@ public void invoke(Object o, AnalysisContext analysisContext) { Set messageSet = violations.stream() .map(ConstraintViolation::getMessage) .collect(Collectors.toSet()); - errorMessageList.add(new ErrorMessage(lineNum, messageSet)); + this.errorMessageList.add(new ErrorMessage(lineNum, messageSet)); } else { - list.add(o); + this.list.add(o); } } @@ -66,12 +66,12 @@ public void doAfterAllAnalysed(AnalysisContext analysisContext) { @Override public List getList() { - return list; + return this.list; } @Override public List getErrors() { - return errorMessageList; + return this.errorMessageList; } } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/head/I18nHeaderCellWriteHandler.java b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/head/I18nHeaderCellWriteHandler.java index f45f3f7af..99f384969 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/head/I18nHeaderCellWriteHandler.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/main/java/org/ballcat/easyexcel/head/I18nHeaderCellWriteHandler.java @@ -67,7 +67,8 @@ public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder if (CollectionUtils.isNotEmpty(originHeadNameList)) { // 国际化处理 List i18nHeadNames = originHeadNameList.stream() - .map(headName -> propertyPlaceholderHelper.replacePlaceholders(headName, placeholderResolver)) + .map(headName -> this.propertyPlaceholderHelper.replacePlaceholders(headName, + this.placeholderResolver)) .collect(Collectors.toList()); head.setHeadNameList(i18nHeadNames); } diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelExportTest.java b/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelExportTest.java index a6ff92e2b..9c06c28ea 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelExportTest.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelExportTest.java @@ -55,7 +55,7 @@ class ExcelExportTest { */ @Test void simpleExport() throws Exception { - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/export/simple")) + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/export/simple")) .andExpect(status().isOk()) .andReturn(); ByteArrayInputStream inputStream = new ByteArrayInputStream(mvcResult.getResponse().getContentAsByteArray()); @@ -79,7 +79,7 @@ void simpleExport() throws Exception { */ @Test void templateExportIgnoreHeader() throws Exception { - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/export/templateExportIgnoreHeader")) + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/export/templateExportIgnoreHeader")) .andExpect(status().isOk()) .andReturn(); ByteArrayInputStream inputStream = new ByteArrayInputStream(mvcResult.getResponse().getContentAsByteArray()); diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelFillTest.java b/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelFillTest.java index 1dd642e2e..2746dd123 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelFillTest.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelFillTest.java @@ -53,7 +53,7 @@ class ExcelFillTest { */ @Test void simpleFill() throws Exception { - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/fill/simple")) + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/fill/simple")) .andExpect(status().isOk()) .andReturn(); ByteArrayInputStream inputStream = new ByteArrayInputStream(mvcResult.getResponse().getContentAsByteArray()); diff --git a/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelImportTest.java b/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelImportTest.java index 10e214371..b7bf25474 100644 --- a/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelImportTest.java +++ b/excel/ballcat-spring-boot-starter-easyexcel/src/test/java/org/ballcat/easyexcel/test/ExcelImportTest.java @@ -70,7 +70,7 @@ void simpleTest() throws Exception { ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); MockMultipartFile multipartFile = new MockMultipartFile("file", bis); - MvcResult mvcResult = mockMvc + MvcResult mvcResult = this.mockMvc .perform(MockMvcRequestBuilders.multipart("/import/simple") .file(multipartFile) .accept(MediaType.APPLICATION_JSON)) @@ -78,7 +78,7 @@ void simpleTest() throws Exception { .andReturn(); String contentAsString = mvcResult.getResponse().getContentAsString(); - List demoDataList = objectMapper.readValue(contentAsString, new TypeReference>() { + List demoDataList = this.objectMapper.readValue(contentAsString, new TypeReference>() { }); Assertions.assertEquals(2, demoDataList.size()); @@ -104,7 +104,7 @@ void ignoreEmptyRowTest() throws Exception { EasyExcel.write(bos, DemoData.class).sheet().doWrite(dataList); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); MockMultipartFile multipartFile = new MockMultipartFile("file", bis); - MvcResult mvcResult = mockMvc + MvcResult mvcResult = this.mockMvc .perform(MockMvcRequestBuilders.multipart("/import/ignore-empty-row-disabled") .file(multipartFile) .accept(MediaType.APPLICATION_JSON)) @@ -112,7 +112,7 @@ void ignoreEmptyRowTest() throws Exception { .andReturn(); String contentAsString = mvcResult.getResponse().getContentAsString(); - List demoDataList = objectMapper.readValue(contentAsString, new TypeReference>() { + List demoDataList = this.objectMapper.readValue(contentAsString, new TypeReference>() { }); Assertions.assertEquals(3, demoDataList.size()); @@ -122,14 +122,14 @@ void ignoreEmptyRowTest() throws Exception { Assertions.assertNull(demoDataList.get(1).getPassword()); // 忽略空行 - mvcResult = mockMvc + mvcResult = this.mockMvc .perform(MockMvcRequestBuilders.multipart("/import/ignore-empty-row-enabled") .file(multipartFile) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); contentAsString = mvcResult.getResponse().getContentAsString(); - demoDataList = objectMapper.readValue(contentAsString, new TypeReference>() { + demoDataList = this.objectMapper.readValue(contentAsString, new TypeReference>() { }); Assertions.assertEquals(2, demoDataList.size()); diff --git a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/core/AbstractFileClient.java b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/core/AbstractFileClient.java index d16eec2dd..15d844b45 100644 --- a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/core/AbstractFileClient.java +++ b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/core/AbstractFileClient.java @@ -29,7 +29,7 @@ public abstract class AbstractFileClient implements FileClient { * 获取操作的根路径 */ public String getRoot() { - return rootPath; + return this.rootPath; } /** @@ -37,7 +37,7 @@ public String getRoot() { * @param relativePath 文件相对 getRoot() 的路径 */ public String getWholePath(String relativePath) { - if (relativePath.startsWith(slash)) { + if (relativePath.startsWith(this.slash)) { return getRoot() + relativePath.substring(1); } return getRoot() + relativePath; diff --git a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/FtpFileClient.java b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/FtpFileClient.java index 33b752718..f0d19f037 100644 --- a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/FtpFileClient.java +++ b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/FtpFileClient.java @@ -44,12 +44,12 @@ public class FtpFileClient extends AbstractFileClient { public FtpFileClient(FtpProperties properties) throws IOException { final FtpMode mode = properties.getMode(); if (properties.isSftp()) { - client = new SftpHelper(); + this.client = new SftpHelper(); } else { - client = new StandardFtpHelper(); + this.client = new StandardFtpHelper(); } - client.loginFtpServer(properties.getUsername(), properties.getPassword(), properties.getIp(), + this.client.loginFtpServer(properties.getUsername(), properties.getPassword(), properties.getIp(), properties.getPort(), null, mode); if (!StringUtils.hasText(properties.getPath())) { @@ -69,7 +69,7 @@ public FtpFileClient(FtpProperties properties) throws IOException { @Override public String upload(InputStream stream, String relativePath) throws IOException { final String path = getWholePath(relativePath); - try (OutputStream outputStream = client.getOutputStream(path)) { + try (OutputStream outputStream = this.client.getOutputStream(path)) { copy(stream, outputStream); } catch (IOException e) { @@ -90,7 +90,7 @@ public File download(String relativePath) throws IOException { // 临时文件 .tmp后缀 File tmpFile = Files.createTempFile("", null).toFile(); try (FileOutputStream outputStream = new FileOutputStream(tmpFile); - InputStream inputStream = client.getInputStream(path)) { + InputStream inputStream = this.client.getInputStream(path)) { copy(inputStream, outputStream); } // JVM退出时删除临时文件 @@ -106,8 +106,8 @@ public File download(String relativePath) throws IOException { @Override public boolean delete(String relativePath) throws IOException { final String path = getWholePath(relativePath); - client.deleteFiles(Collections.singleton(path)); - return !client.isFileExist(path); + this.client.deleteFiles(Collections.singleton(path)); + return !this.client.isFileExist(path); } /** diff --git a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/SftpHelper.java b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/SftpHelper.java index 9718f5bb7..de62e28f8 100644 --- a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/SftpHelper.java +++ b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/SftpHelper.java @@ -59,28 +59,28 @@ public void loginFtpServer(String username, String password, String host, int po throws IOException { JSch jsch = new JSch(); try { - session = jsch.getSession(username, host, port); + this.session = jsch.getSession(username, host, port); // 根据用户名,主机ip,端口获取一个Session对象 // 如果服务器连接不上,则抛出异常 - if (session == null) { + if (this.session == null) { throw new FileException("session is null,无法通过sftp与服务器建立链接,请检查主机名和用户名是否正确."); } // 设置密码 - session.setPassword(password); + this.session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); // 为Session对象设置properties - session.setConfig(config); + this.session.setConfig(config); // 设置timeout时间 if (null != timeout) { - session.setTimeout(timeout); + this.session.setTimeout(timeout); } // 通过Session建立链接 - session.connect(); + this.session.connect(); // 打开SFTP通道 - channelSftp = (ChannelSftp) session.openChannel("sftp"); + this.channelSftp = (ChannelSftp) this.session.openChannel("sftp"); // 建立SFTP通道的连接 - channelSftp.connect(); + this.channelSftp.connect(); // 设置命令传输编码 /// String fileEncoding = System.getProperty("file.encoding"); @@ -123,18 +123,18 @@ else if (illegalArgumentException.equals(cause) || wrongPort.equals(cause)) { @Override public void logoutFtpServer() { - if (channelSftp != null) { - channelSftp.disconnect(); + if (this.channelSftp != null) { + this.channelSftp.disconnect(); } - if (session != null) { - session.disconnect(); + if (this.session != null) { + this.session.disconnect(); } } @Override public boolean isDirExist(String directoryPath) throws IOException { try { - SftpATTRS attrs = channelSftp.lstat(directoryPath); + SftpATTRS attrs = this.channelSftp.lstat(directoryPath); return attrs.isDir(); } catch (SftpException e) { @@ -153,7 +153,7 @@ public boolean isDirExist(String directoryPath) throws IOException { public boolean isFileExist(String filePath) throws IOException { boolean isExitFlag = false; try { - SftpATTRS attrs = channelSftp.lstat(filePath); + SftpATTRS attrs = this.channelSftp.lstat(filePath); if (attrs.getSize() >= 0) { isExitFlag = true; } @@ -176,7 +176,7 @@ public boolean isFileExist(String filePath) throws IOException { @Override public boolean isSymbolicLink(String filePath) throws IOException { try { - SftpATTRS attrs = channelSftp.lstat(filePath); + SftpATTRS attrs = this.channelSftp.lstat(filePath); return attrs.isLink(); } catch (SftpException e) { @@ -232,8 +232,8 @@ else if (isSymbolicLink(directoryPath)) { } else if (isFileExist(directoryPath)) { // path指向具体文件 - sourceFiles.add(directoryPath); - return sourceFiles; + this.sourceFiles.add(directoryPath); + return this.sourceFiles; } else { String message = String.format(CONFIG_PATH_MISSING_ERROR, directoryPath); @@ -241,7 +241,7 @@ else if (isFileExist(directoryPath)) { throw new FileException(message); } try { - Vector files = channelSftp.ls(directoryPath); + Vector files = this.channelSftp.ls(directoryPath); for (Object o : files) { ChannelSftp.LsEntry le = (ChannelSftp.LsEntry) o; String strName = le.getFilename(); @@ -261,7 +261,7 @@ else if (isSymbolicLink(filePath)) { } else if (isFileExist(filePath)) { // 是文件 - sourceFiles.add(filePath); + this.sourceFiles.add(filePath); } else { String message = String.format("请确认path:[%s]存在,且配置的用户有权限读取", filePath); @@ -275,7 +275,7 @@ else if (isFileExist(filePath)) { LOGGER.error(message, e); throw new FileException(message, e); } - return sourceFiles; + return this.sourceFiles; } else { // 超出最大递归层数 @@ -288,7 +288,7 @@ else if (isFileExist(filePath)) { @Override public InputStream getInputStream(String filePath) throws IOException { try { - return channelSftp.get(filePath); + return this.channelSftp.get(filePath); } catch (SftpException e) { String message = String.format("读取文件 : [%s] 时出错,请确认文件:[%s]存在且配置的用户有权限读取", filePath, filePath); diff --git a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/StandardFtpHelper.java b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/StandardFtpHelper.java index 6f3221e71..6729bcf12 100644 --- a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/StandardFtpHelper.java +++ b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/ftp/support/StandardFtpHelper.java @@ -53,29 +53,29 @@ public class StandardFtpHelper extends FtpHelper { @Override public void loginFtpServer(String username, String password, String host, int port, Integer timeout, FtpMode mode) throws IOException { - ftpClient = new FTPClient(); + this.ftpClient = new FTPClient(); try { // 连接 - ftpClient.connect(host, port); + this.ftpClient.connect(host, port); // 登录 - ftpClient.login(username, password); + this.ftpClient.login(username, password); // 不需要写死ftp server的OS TYPE,FTPClient getSystemType()方法会自动识别 /// ftpClient.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX)); if (null != timeout) { - ftpClient.setConnectTimeout(timeout); - ftpClient.setDataTimeout(Duration.ofMillis(timeout)); + this.ftpClient.setConnectTimeout(timeout); + this.ftpClient.setDataTimeout(Duration.ofMillis(timeout)); } if (mode == FtpMode.PASSIVE) { - ftpClient.enterRemotePassiveMode(); - ftpClient.enterLocalPassiveMode(); + this.ftpClient.enterRemotePassiveMode(); + this.ftpClient.enterLocalPassiveMode(); } else if (mode == FtpMode.ACTIVE) { - ftpClient.enterLocalActiveMode(); + this.ftpClient.enterLocalActiveMode(); /// ftpClient.enterRemoteActiveMode(host, port); } - int reply = ftpClient.getReplyCode(); + int reply = this.ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { - ftpClient.disconnect(); + this.ftpClient.disconnect(); String message = String.format("与ftp服务器建立连接失败,请检查用户名和密码是否正确: [%s]", "message:host =" + host + ",username = " + username + ",port =" + port); LOGGER.error(message); @@ -83,7 +83,7 @@ else if (mode == FtpMode.ACTIVE) { } // 设置命令传输编码 String fileEncoding = System.getProperty("file.encoding"); - ftpClient.setControlEncoding(fileEncoding); + this.ftpClient.setControlEncoding(fileEncoding); } catch (UnknownHostException e) { String message = String.format("请确认ftp服务器地址是否正确,无法连接到地址为: [%s] 的ftp服务器", host); @@ -106,10 +106,10 @@ else if (mode == FtpMode.ACTIVE) { @Override public void logoutFtpServer() throws IOException { - if (ftpClient.isConnected()) { + if (this.ftpClient.isConnected()) { try { // fixme ftpClient.completePendingCommand();//打开流操作之后必须,原因还需要深究 - ftpClient.logout(); + this.ftpClient.logout(); } catch (IOException e) { String message = "与ftp服务器断开连接失败"; @@ -122,7 +122,8 @@ public void logoutFtpServer() throws IOException { @Override public boolean isDirExist(String directoryPath) throws IOException { try { - return ftpClient.changeWorkingDirectory(new String(directoryPath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); + return this.ftpClient + .changeWorkingDirectory(new String(directoryPath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); } catch (IOException e) { String message = String.format("进入目录:[%s]时发生I/O异常,请确认与ftp服务器的连接正常", directoryPath); @@ -135,7 +136,8 @@ public boolean isDirExist(String directoryPath) throws IOException { public boolean isFileExist(String filePath) throws IOException { boolean isExitFlag = false; try { - FTPFile[] ftpFiles = ftpClient.listFiles(new String(filePath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); + FTPFile[] ftpFiles = this.ftpClient + .listFiles(new String(filePath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); if (ftpFiles.length == 1 && ftpFiles[0].isFile()) { isExitFlag = true; } @@ -152,7 +154,8 @@ public boolean isFileExist(String filePath) throws IOException { public boolean isSymbolicLink(String filePath) throws IOException { boolean isExitFlag = false; try { - FTPFile[] ftpFiles = ftpClient.listFiles(new String(filePath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); + FTPFile[] ftpFiles = this.ftpClient + .listFiles(new String(filePath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); if (ftpFiles.length == 1 && ftpFiles[0].isSymbolicLink()) { isExitFlag = true; } @@ -196,8 +199,8 @@ else if (isDirExist(directoryPath)) { } else if (isFileExist(directoryPath)) { // path指向具体文件 - sourceFiles.add(directoryPath); - return sourceFiles; + this.sourceFiles.add(directoryPath); + return this.sourceFiles; } else if (isSymbolicLink(directoryPath)) { // path是链接文件 @@ -212,7 +215,8 @@ else if (isSymbolicLink(directoryPath)) { } try { - FTPFile[] fs = ftpClient.listFiles(new String(directoryPath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); + FTPFile[] fs = this.ftpClient + .listFiles(new String(directoryPath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); for (FTPFile ff : fs) { String strName = ff.getName(); String filePath = parentPath + strName; @@ -224,7 +228,7 @@ else if (isSymbolicLink(directoryPath)) { } else if (ff.isFile()) { // 是文件 - sourceFiles.add(filePath); + this.sourceFiles.add(filePath); } else if (ff.isSymbolicLink()) { // 是链接文件 @@ -244,7 +248,7 @@ else if (ff.isSymbolicLink()) { LOGGER.error(message, e); throw new FileException(message, e); } - return sourceFiles; + return this.sourceFiles; } else { // 超出最大递归层数 @@ -257,7 +261,7 @@ else if (ff.isSymbolicLink()) { @Override public InputStream getInputStream(String filePath) throws IOException { try { - return ftpClient.retrieveFileStream(new String(filePath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); + return this.ftpClient.retrieveFileStream(new String(filePath.getBytes(), FTP.DEFAULT_CONTROL_ENCODING)); } catch (IOException e) { String message = String.format("读取文件 : [%s] 时出错,请确认文件:[%s]存在且配置的用户有权限读取", filePath, filePath); diff --git a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/local/LocalFileClient.java b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/local/LocalFileClient.java index bd416778a..7904d2f1d 100644 --- a/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/local/LocalFileClient.java +++ b/file/ballcat-spring-boot-starter-file/src/main/java/org/ballcat/file/local/LocalFileClient.java @@ -43,7 +43,7 @@ public LocalFileClient(LocalProperties properties) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new FileException(String.format("路径: %s; 不存在且创建失败! 请检查是否拥有对该路径的操作权限!", dir.getPath())); } - parentDir = dir; + this.parentDir = dir; super.rootPath = dir.getPath(); super.slash = File.separator; } @@ -58,7 +58,7 @@ public LocalFileClient(LocalProperties properties) throws IOException { @Override public String upload(InputStream stream, String relativePath) throws IOException { // 目标文件 - final File file = new File(parentDir, relativePath); + final File file = new File(this.parentDir, relativePath); if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { throw new FileException("文件上传失败! 创建父级文件夹失败! 父级路径: " + file.getParentFile().getPath()); @@ -82,7 +82,7 @@ public String upload(InputStream stream, String relativePath) throws IOException */ @Override public File download(String relativePath) { - return new File(parentDir, relativePath); + return new File(this.parentDir, relativePath); } /** @@ -92,7 +92,7 @@ public File download(String relativePath) { */ @Override public boolean delete(String relativePath) { - final File file = new File(parentDir, relativePath); + final File file = new File(this.parentDir, relativePath); return file.exists() && file.delete(); } diff --git a/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/GrpcClientProvide.java b/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/GrpcClientProvide.java index c973ae6fa..c09c0d30f 100644 --- a/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/GrpcClientProvide.java +++ b/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/GrpcClientProvide.java @@ -50,7 +50,7 @@ public class GrpcClientProvide { protected final List interceptors; public ManagedChannel channel() { - return channel(properties.getHost(), properties.getPort()); + return channel(this.properties.getHost(), this.properties.getPort()); } public ManagedChannel channel(String host, Integer port) { @@ -72,26 +72,26 @@ public ManagedChannel channel(String target, UnaryOperator builder) { // 开启心跳 - if (properties.isEnableKeepAlive()) { - builder.keepAliveTime(properties.getKeepAliveTime(), TimeUnit.MILLISECONDS) - .keepAliveTimeout(properties.getKeepAliveTimeout(), TimeUnit.MILLISECONDS); + if (this.properties.isEnableKeepAlive()) { + builder.keepAliveTime(this.properties.getKeepAliveTime(), TimeUnit.MILLISECONDS) + .keepAliveTimeout(this.properties.getKeepAliveTimeout(), TimeUnit.MILLISECONDS); } // 使用明文 - if (properties.isUsePlaintext()) { + if (this.properties.isUsePlaintext()) { builder.usePlaintext(); } // 重试 - if (properties.isEnableRetry()) { + if (this.properties.isEnableRetry()) { builder.enableRetry(); } // 注册拦截器 - if (!CollectionUtils.isEmpty(interceptors)) { + if (!CollectionUtils.isEmpty(this.interceptors)) { // 按照spring生态的 @Order 排序 - interceptors.sort(AnnotationAwareOrderComparator.INSTANCE); - builder.intercept(interceptors); + this.interceptors.sort(AnnotationAwareOrderComparator.INSTANCE); + builder.intercept(this.interceptors); } // ssl配置 @@ -120,7 +120,7 @@ public > R future(Channel channel, Function builder) { // 关闭ssl - if (!properties.isUsePlaintext() && properties.isDisableSsl()) { + if (!this.properties.isUsePlaintext() && this.properties.isDisableSsl()) { if (builder instanceof NettyChannelBuilder) { SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE); diff --git a/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/configuration/GrpcClientAutoConfiguration.java b/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/configuration/GrpcClientAutoConfiguration.java index 9c95836e7..756c9deb3 100644 --- a/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/configuration/GrpcClientAutoConfiguration.java +++ b/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/configuration/GrpcClientAutoConfiguration.java @@ -41,13 +41,13 @@ public class GrpcClientAutoConfiguration { @Bean @ConditionalOnMissingBean public GrpcClientProvide grpcClientProvide(List interceptors) { - return new GrpcClientProvide(properties, interceptors); + return new GrpcClientProvide(this.properties, interceptors); } @Bean @ConditionalOnMissingBean public GrpcClientTraceIdInterceptor grpcClientTraceIdInterceptor() { - return new GrpcClientTraceIdInterceptor(properties); + return new GrpcClientTraceIdInterceptor(this.properties); } } diff --git a/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/interceptor/GrpcClientTraceIdInterceptor.java b/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/interceptor/GrpcClientTraceIdInterceptor.java index ebba25c72..4ead7d0e3 100644 --- a/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/interceptor/GrpcClientTraceIdInterceptor.java +++ b/grpc/ballcat-spring-boot-starter-grpc-client/src/main/java/org/ballcat/grpc/client/interceptor/GrpcClientTraceIdInterceptor.java @@ -61,7 +61,8 @@ public ClientCall interceptCall(MethodDescriptor method, Call @Override public void onStartBefore(Listener responseListener, Metadata headers) { if (StringUtils.hasText(traceId)) { - headers.put(traceIdKey, traceId); + headers.put(org.ballcat.grpc.client.interceptor.GrpcClientTraceIdInterceptor.this.traceIdKey, + traceId); } } }; diff --git a/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/GrpcServer.java b/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/GrpcServer.java index 778768b3d..8f2ec47c8 100644 --- a/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/GrpcServer.java +++ b/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/GrpcServer.java @@ -88,12 +88,12 @@ public GrpcServer(ServerBuilder builder, GrpcServerProperties properties, Lis ServerServiceDefinition serverServiceDefinition = service.bindService(); ServiceDescriptor serviceDescriptor = serverServiceDefinition.getServiceDescriptor(); - serviceNameMap.put(serviceDescriptor.getName(), cls); + this.serviceNameMap.put(serviceDescriptor.getName(), cls); for (ServerMethodDefinition serverMethodDefinition : serverServiceDefinition.getMethods()) { MethodDescriptor methodDescriptor = serverMethodDefinition.getMethodDescriptor(); String fullMethodName = methodDescriptor.getFullMethodName(); - fullMethodNameMap.put(fullMethodName, resolve(methodDescriptor, cls)); + this.fullMethodNameMap.put(fullMethodName, resolve(methodDescriptor, cls)); } } @@ -101,15 +101,15 @@ public GrpcServer(ServerBuilder builder, GrpcServerProperties properties, Lis } public boolean isRunning() { - return !server.isShutdown() && !server.isTerminated(); + return !this.server.isShutdown() && !this.server.isTerminated(); } public int port() { - return server.getPort(); + return this.server.getPort(); } public Class findClass(ServiceDescriptor descriptor) { - return serviceNameMap.get(descriptor.getName()); + return this.serviceNameMap.get(descriptor.getName()); } @SuppressWarnings("unchecked") @@ -119,7 +119,7 @@ public Class findClass(MethodDescriptor descrip } public Method findMethod(MethodDescriptor descriptor) { - return fullMethodNameMap.get(descriptor.getFullMethodName()); + return this.fullMethodNameMap.get(descriptor.getFullMethodName()); } protected Method resolve(MethodDescriptor descriptor, Class cls) { @@ -137,15 +137,15 @@ protected Method resolve(MethodDescriptor descriptor, Class interceptors, List services) { - return new GrpcServer(properties, interceptors, services); + return new GrpcServer(this.properties, interceptors, services); } @Bean @ConditionalOnMissingBean public GrpcServerTraceIdInterceptor grpcServerTraceIdInterceptor() { - return new GrpcServerTraceIdInterceptor(properties); + return new GrpcServerTraceIdInterceptor(this.properties); } } diff --git a/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/interceptor/GrpcServerTraceIdInterceptor.java b/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/interceptor/GrpcServerTraceIdInterceptor.java index 10bf1afe4..31267dce7 100644 --- a/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/interceptor/GrpcServerTraceIdInterceptor.java +++ b/grpc/ballcat-spring-boot-starter-grpc-server/src/main/java/org/ballcat/grpc/server/interceptor/GrpcServerTraceIdInterceptor.java @@ -47,8 +47,8 @@ public GrpcServerTraceIdInterceptor(GrpcServerProperties properties) { */ protected String traceId(Metadata headers) { String traceId = null; - if (headers.containsKey(traceIdKey)) { - traceId = headers.get(traceIdKey); + if (headers.containsKey(this.traceIdKey)) { + traceId = headers.get(this.traceIdKey); } if (StringUtils.hasText(traceId)) { return traceId; @@ -63,7 +63,7 @@ public ServerCall.Listener interceptCall(ServerCall call, Metada MDC.put(MDCConstants.TRACE_ID_KEY, traceId); try { // 返回traceId - headers.put(traceIdKey, traceId); + headers.put(this.traceIdKey, traceId); return next.startCall(call, headers); } finally { diff --git a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClient.java b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClient.java index 8f29c3acb..d00dc9e5f 100644 --- a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClient.java +++ b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClient.java @@ -47,27 +47,27 @@ public class GrpcClient, B extends AbstractBlocki private final F futureStub; public T async(Function function) { - return function.apply(asyncStub); + return function.apply(this.asyncStub); } public T blocking(Function function) { - return function.apply(blockingStub); + return function.apply(this.blockingStub); } public T future(Function function) { - return function.apply(futureStub); + return function.apply(this.futureStub); } public void async(Consumer consumer) { - consumer.accept(asyncStub); + consumer.accept(this.asyncStub); } public void blocking(Consumer consumer) { - consumer.accept(blockingStub); + consumer.accept(this.blockingStub); } public void future(Consumer consumer) { - consumer.accept(futureStub); + consumer.accept(this.futureStub); } } diff --git a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClientChannel.java b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClientChannel.java index a36eb72e3..d16d97826 100644 --- a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClientChannel.java +++ b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcClientChannel.java @@ -65,8 +65,8 @@ public GrpcClientChannel(GrpcClientProperties properties, UnaryOperator, B extends AbstractBlockingStub, F extends AbstractFutureStub> GrpcClient client( Function asyncFunction, Function blockingFunction, Function futureFunction) { - return new GrpcClient<>(properties, channel, asyncFunction.apply(channel), blockingFunction.apply(channel), - futureFunction.apply(channel)); + return new GrpcClient<>(this.properties, this.channel, asyncFunction.apply(this.channel), + blockingFunction.apply(this.channel), futureFunction.apply(this.channel)); } @Override @@ -75,7 +75,7 @@ public void destroy() { } public void close() { - channel.shutdown(); + this.channel.shutdown(); } } diff --git a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcServer.java b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcServer.java index 3d1b099c0..fa611a916 100644 --- a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcServer.java +++ b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/GrpcServer.java @@ -41,12 +41,12 @@ public GrpcServer(Server server) { @Override @SneakyThrows public void onApplicationStart() { - server.start(); - log.debug("grpc服务启动. 端口: {}", server.getPort()); + this.server.start(); + log.debug("grpc服务启动. 端口: {}", this.server.getPort()); THREAD_POOL.execute(() -> { Thread.currentThread().setName("GrpcServer"); try { - server.awaitTermination(); + this.server.awaitTermination(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); @@ -61,7 +61,7 @@ public void onApplicationStart() { @Override public void onApplicationStop() { log.warn("grpc服务开始关闭"); - server.shutdownNow(); + this.server.shutdownNow(); log.warn("grpc服务关闭"); } diff --git a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/interceptor/TraceIdInterceptor.java b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/interceptor/TraceIdInterceptor.java index 31b3e535d..c15926ff2 100644 --- a/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/interceptor/TraceIdInterceptor.java +++ b/grpc/ballcat-spring-boot-starter-grpc/src/main/java/org/ballcat/grpc/interceptor/TraceIdInterceptor.java @@ -50,8 +50,8 @@ public ServerCall.Listener interceptCall(ServerCall call, Metada ServerCallHandler next) { String traceId = null; - if (headers.containsKey(headerTraceId)) { - traceId = headers.get(headerTraceId); + if (headers.containsKey(this.headerTraceId)) { + traceId = headers.get(this.headerTraceId); } if (!StringUtils.hasText(traceId)) { @@ -61,7 +61,7 @@ public ServerCall.Listener interceptCall(ServerCall call, Metada MDC.put(MDCConstants.TRACE_ID_KEY, traceId); try { // 返回traceId - headers.put(headerTraceId, traceId); + headers.put(this.headerTraceId, traceId); return next.startCall(call, headers); } finally { diff --git a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/DynamicMessageSource.java b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/DynamicMessageSource.java index 6537abb22..8cfae1062 100644 --- a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/DynamicMessageSource.java +++ b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/DynamicMessageSource.java @@ -38,7 +38,7 @@ public class DynamicMessageSource extends AbstractMessageSource { @Override @Nullable protected MessageFormat resolveCode(String code, Locale locale) { - I18nMessage i18nMessage = i18nMessageProvider.getI18nMessage(code, locale); + I18nMessage i18nMessage = this.i18nMessageProvider.getI18nMessage(code, locale); if (i18nMessage != null) { return createMessageFormat(i18nMessage.getMessage(), locale); } diff --git a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/I18nResponseAdvice.java b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/I18nResponseAdvice.java index 7d2fbab86..6eb4e122a 100644 --- a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/I18nResponseAdvice.java +++ b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/I18nResponseAdvice.java @@ -79,7 +79,7 @@ public I18nResponseAdvice(MessageSource messageSource, I18nOptions i18nOptions) if (fallbackLanguageTag != null) { String[] arr = fallbackLanguageTag.split("-"); Assert.isTrue(arr.length == 2, "error fallbackLanguageTag!"); - fallbackLocale = new Locale(arr[0], arr[1]); + this.fallbackLocale = new Locale(arr[0], arr[1]); } this.useCodeAsDefaultMessage = i18nOptions.isUseCodeAsDefaultMessage(); @@ -162,7 +162,7 @@ public void switchLanguage(Object source) { // 把当前 field 的值更新为国际化后的属性 Locale locale = LocaleContextHolder.getLocale(); - String message = codeToMessage(code, locale, (String) fieldValue, fallbackLocale); + String message = codeToMessage(code, locale, (String) fieldValue, this.fallbackLocale); ReflectionUtils.setField(field, source, message); } else if (fieldValue instanceof Collection) { @@ -227,7 +227,7 @@ private String codeToMessage(String code, Locale locale, String defaultMessage, String message; try { - message = messageSource.getMessage(code, null, locale); + message = this.messageSource.getMessage(code, null, locale); return message; } catch (NoSuchMessageException e) { @@ -237,7 +237,7 @@ private String codeToMessage(String code, Locale locale, String defaultMessage, // 当配置了回退语言时,尝试回退 if (fallbackLocale != null && locale != fallbackLocale) { try { - message = messageSource.getMessage(code, null, fallbackLocale); + message = this.messageSource.getMessage(code, null, fallbackLocale); return message; } catch (NoSuchMessageException e) { @@ -246,7 +246,7 @@ private String codeToMessage(String code, Locale locale, String defaultMessage, } } - if (useCodeAsDefaultMessage) { + if (this.useCodeAsDefaultMessage) { return code; } else { diff --git a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/MessageSourceHierarchicalChanger.java b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/MessageSourceHierarchicalChanger.java index ec69367a5..9ee717a2d 100644 --- a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/MessageSourceHierarchicalChanger.java +++ b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/MessageSourceHierarchicalChanger.java @@ -43,14 +43,14 @@ public class MessageSourceHierarchicalChanger { @PostConstruct public void changeMessageSourceParent() { // 优先走 messageSource,从资源文件中查找 - if (messageSource instanceof HierarchicalMessageSource) { - HierarchicalMessageSource hierarchicalMessageSource = (HierarchicalMessageSource) messageSource; + if (this.messageSource instanceof HierarchicalMessageSource) { + HierarchicalMessageSource hierarchicalMessageSource = (HierarchicalMessageSource) this.messageSource; MessageSource parentMessageSource = hierarchicalMessageSource.getParentMessageSource(); - dynamicMessageSource.setParentMessageSource(parentMessageSource); - hierarchicalMessageSource.setParentMessageSource(dynamicMessageSource); + this.dynamicMessageSource.setParentMessageSource(parentMessageSource); + hierarchicalMessageSource.setParentMessageSource(this.dynamicMessageSource); } else { - dynamicMessageSource.setParentMessageSource(messageSource); + this.dynamicMessageSource.setParentMessageSource(this.messageSource); } } diff --git a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/WildcardReloadableResourceBundleMessageSource.java b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/WildcardReloadableResourceBundleMessageSource.java index 6e3f54aa7..485d24ebe 100644 --- a/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/WildcardReloadableResourceBundleMessageSource.java +++ b/i18n/ballcat-i18n/src/main/java/org/ballcat/i18n/WildcardReloadableResourceBundleMessageSource.java @@ -46,10 +46,11 @@ public class WildcardReloadableResourceBundleMessageSource extends ReloadableRes private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - private static final Pattern pattern = Pattern.compile(".*_([a-z]{2}(_[A-Z]{2})?(_[A-Z]+)?)\\.properties$"); + private static final Pattern LOCALE_PROPERTIES_FILE_NAME_PATTERN = Pattern + .compile(".*_([a-z]{2}(_[A-Z]{2})?(_[A-Z]+)?)\\.properties$"); public WildcardReloadableResourceBundleMessageSource() { - super.setResourceLoader(resolver); + super.setResourceLoader(this.resolver); } /** @@ -70,10 +71,11 @@ protected List calculateAllFilenames(String basename, Locale locale) { if (containsWildcard(basename)) { filenames.remove(basename); try { - Resource[] resources = resolver.getResources(basename + PROPERTIES_SUFFIX); + Resource[] resources = this.resolver.getResources(basename + PROPERTIES_SUFFIX); for (Resource resource : resources) { String resourceUriStr = resource.getURI().toString(); - if (!pattern.matcher(resourceUriStr).matches()) { + // 根据通配符匹配到的多个 basename 对应的文件添加到文件列表末尾,作为兜底匹配 + if (!LOCALE_PROPERTIES_FILE_NAME_PATTERN.matcher(resourceUriStr).matches()) { String sourcePath = resourceUriStr.replace(PROPERTIES_SUFFIX, ""); filenames.add(sourcePath); } @@ -97,7 +99,7 @@ protected List calculateFilenamesForLocale(String basename, Locale local List matchFilenames = super.calculateFilenamesForLocale(basename, locale); for (String matchFilename : matchFilenames) { try { - Resource[] resources = resolver.getResources(matchFilename + PROPERTIES_SUFFIX); + Resource[] resources = this.resolver.getResources(matchFilename + PROPERTIES_SUFFIX); for (Resource resource : resources) { String sourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX, ""); fileNames.add(sourcePath); diff --git a/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/IdempotentAspect.java b/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/IdempotentAspect.java index 3057efd4e..93273492d 100644 --- a/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/IdempotentAspect.java +++ b/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/IdempotentAspect.java @@ -41,10 +41,10 @@ public class IdempotentAspect { @Around("@annotation(idempotentAnnotation)") public Object around(ProceedingJoinPoint joinPoint, Idempotent idempotentAnnotation) throws Throwable { // 获取幂等标识 - String idempotentKey = idempotentKeyGenerator.generate(joinPoint, idempotentAnnotation); + String idempotentKey = this.idempotentKeyGenerator.generate(joinPoint, idempotentAnnotation); // 校验当前请求是否重复请求 - boolean saveSuccess = idempotentKeyStore.saveIfAbsent(idempotentKey, idempotentAnnotation.duration(), + boolean saveSuccess = this.idempotentKeyStore.saveIfAbsent(idempotentKey, idempotentAnnotation.duration(), idempotentAnnotation.timeUnit()); Assert.isTrue(saveSuccess, () -> { throw new IdempotentException(BaseResultCode.REPEATED_EXECUTE.getCode(), idempotentAnnotation.message()); @@ -53,14 +53,14 @@ public Object around(ProceedingJoinPoint joinPoint, Idempotent idempotentAnnotat try { Object result = joinPoint.proceed(); if (idempotentAnnotation.removeKeyWhenFinished()) { - idempotentKeyStore.remove(idempotentKey); + this.idempotentKeyStore.remove(idempotentKey); } return result; } catch (Throwable e) { // 异常时,根据配置决定是否删除幂等 key if (idempotentAnnotation.removeKeyWhenError()) { - idempotentKeyStore.remove(idempotentKey); + this.idempotentKeyStore.remove(idempotentKey); } throw e; } diff --git a/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/InMemoryIdempotentKeyStore.java b/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/InMemoryIdempotentKeyStore.java index 780b3f772..50c7f2f35 100644 --- a/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/InMemoryIdempotentKeyStore.java +++ b/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/InMemoryIdempotentKeyStore.java @@ -34,15 +34,15 @@ public class InMemoryIdempotentKeyStore implements IdempotentKeyStore { public InMemoryIdempotentKeyStore() { this.cache = CacheUtil.newTimedCache(Integer.MAX_VALUE); - cache.schedulePrune(1); + this.cache.schedulePrune(1); } @Override public synchronized boolean saveIfAbsent(String key, long duration, TimeUnit timeUnit) { - Long value = cache.get(key, false); + Long value = this.cache.get(key, false); if (value == null) { long timeOut = TimeUnit.MILLISECONDS.convert(duration, timeUnit); - cache.put(key, System.currentTimeMillis(), timeOut); + this.cache.put(key, System.currentTimeMillis(), timeOut); return true; } return false; @@ -50,7 +50,7 @@ public synchronized boolean saveIfAbsent(String key, long duration, TimeUnit tim @Override public void remove(String key) { - cache.remove(key); + this.cache.remove(key); } } diff --git a/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/RedisIdempotentKeyStore.java b/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/RedisIdempotentKeyStore.java index cae49bd06..95e85e3b3 100644 --- a/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/RedisIdempotentKeyStore.java +++ b/idempotent/ballcat-idempotent/src/main/java/org/ballcat/idempotent/key/store/RedisIdempotentKeyStore.java @@ -36,7 +36,7 @@ public class RedisIdempotentKeyStore implements IdempotentKeyStore { @Override public boolean saveIfAbsent(String key, long duration, TimeUnit timeUnit) { - ValueOperations opsForValue = stringRedisTemplate.opsForValue(); + ValueOperations opsForValue = this.stringRedisTemplate.opsForValue(); Boolean saveSuccess = opsForValue.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), duration, timeUnit); return saveSuccess != null && saveSuccess; @@ -44,7 +44,7 @@ public boolean saveIfAbsent(String key, long duration, TimeUnit timeUnit) { @Override public void remove(String key) { - stringRedisTemplate.delete(key); + this.stringRedisTemplate.delete(key); } } diff --git a/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/InMemoryIdempotentTest.java b/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/InMemoryIdempotentTest.java index a019bca50..b4e33f3dd 100644 --- a/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/InMemoryIdempotentTest.java +++ b/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/InMemoryIdempotentTest.java @@ -43,9 +43,9 @@ class InMemoryIdempotentTest { */ @Test void testIdempotent() { - Assertions.assertDoesNotThrow(() -> idempotentMethods.method("aaa")); + Assertions.assertDoesNotThrow(() -> this.idempotentMethods.method("aaa")); - Executable executable = () -> idempotentMethods.method("bbb"); + Executable executable = () -> this.idempotentMethods.method("bbb"); Assertions.assertDoesNotThrow(executable); Assertions.assertThrowsExactly(IdempotentException.class, executable); @@ -58,12 +58,12 @@ void testIdempotent() { @Test void testRepeatableWhenFinished() { // 异常时可重复执行 - Executable executable = () -> idempotentMethods.repeatableWhenFinished(); + Executable executable = () -> this.idempotentMethods.repeatableWhenFinished(); Assertions.assertDoesNotThrow(executable); Assertions.assertDoesNotThrow(executable); // 异常时不可重复执行 - Executable normal = () -> idempotentMethods.unRepeatableWhenFinished(); + Executable normal = () -> this.idempotentMethods.unRepeatableWhenFinished(); Assertions.assertDoesNotThrow(normal); Assertions.assertThrowsExactly(IdempotentException.class, normal); } @@ -71,14 +71,14 @@ void testRepeatableWhenFinished() { @Test void testRepeatableWhenError() { // 异常时可重复执行 - Executable executable = () -> idempotentMethods.repeatableWhenError(); - Assertions.assertThrowsExactly(TestException.class, () -> idempotentMethods.repeatableWhenError()); - Assertions.assertThrowsExactly(TestException.class, () -> idempotentMethods.repeatableWhenError()); + Executable executable = () -> this.idempotentMethods.repeatableWhenError(); + Assertions.assertThrowsExactly(TestException.class, () -> this.idempotentMethods.repeatableWhenError()); + Assertions.assertThrowsExactly(TestException.class, () -> this.idempotentMethods.repeatableWhenError()); // 异常时不可重复执行 - Executable normal = () -> idempotentMethods.unRepeatableWhenError(); - Assertions.assertThrowsExactly(TestException.class, () -> idempotentMethods.unRepeatableWhenError()); - Assertions.assertThrowsExactly(IdempotentException.class, () -> idempotentMethods.unRepeatableWhenError()); + Executable normal = () -> this.idempotentMethods.unRepeatableWhenError(); + Assertions.assertThrowsExactly(TestException.class, () -> this.idempotentMethods.unRepeatableWhenError()); + Assertions.assertThrowsExactly(IdempotentException.class, () -> this.idempotentMethods.unRepeatableWhenError()); } /** @@ -86,17 +86,17 @@ void testRepeatableWhenError() { */ @Test void testIdempotentMessage() { - idempotentMethods.method("ccc"); + this.idempotentMethods.method("ccc"); try { - idempotentMethods.method("ccc"); + this.idempotentMethods.method("ccc"); } catch (Exception ex) { Assertions.assertEquals("重复请求,请稍后重试", ex.getMessage()); } - idempotentMethods.differentMessage("ddd"); + this.idempotentMethods.differentMessage("ddd"); try { - idempotentMethods.differentMessage("ddd"); + this.idempotentMethods.differentMessage("ddd"); } catch (Exception ex) { Assertions.assertEquals("不允许短期内重复执行方法2", ex.getMessage()); diff --git a/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/WebIdempotentTest.java b/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/WebIdempotentTest.java index 7b8e6bba8..6ffa9f7c1 100644 --- a/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/WebIdempotentTest.java +++ b/idempotent/ballcat-idempotent/src/test/java/org/ballcat/idempotent/test/WebIdempotentTest.java @@ -90,7 +90,7 @@ void testIdempotent() { private boolean tryExecute(String key) { try { - idempotentMethods.method(key); + this.idempotentMethods.method(key); } catch (IdempotentException e) { System.out.println(e.getMessage()); diff --git a/idempotent/ballcat-spring-boot-starter-idempotent/src/test/java/org/ballcat/autoconfigure/idempotent/IdempotentTest.java b/idempotent/ballcat-spring-boot-starter-idempotent/src/test/java/org/ballcat/autoconfigure/idempotent/IdempotentTest.java index 21eeb593d..fd3c5986a 100644 --- a/idempotent/ballcat-spring-boot-starter-idempotent/src/test/java/org/ballcat/autoconfigure/idempotent/IdempotentTest.java +++ b/idempotent/ballcat-spring-boot-starter-idempotent/src/test/java/org/ballcat/autoconfigure/idempotent/IdempotentTest.java @@ -39,8 +39,8 @@ class IdempotentTest { @Test void test() { - Assertions.assertInstanceOf(InMemoryIdempotentKeyStore.class, idempotentKeyStore); - idempotentKeyStore.saveIfAbsent("test", 1, TimeUnit.SECONDS); + Assertions.assertInstanceOf(InMemoryIdempotentKeyStore.class, this.idempotentKeyStore); + this.idempotentKeyStore.saveIfAbsent("test", 1, TimeUnit.SECONDS); } } diff --git a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/core/IpInfo.java b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/core/IpInfo.java index 016d7edac..b1b2e6605 100644 --- a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/core/IpInfo.java +++ b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/core/IpInfo.java @@ -93,10 +93,10 @@ public String getAddress() { */ public String getAddress(String delimiter) { Set regionSet = new LinkedHashSet<>(); - regionSet.add(country); - regionSet.add(province); - regionSet.add(city); - regionSet.add(area); + regionSet.add(this.country); + regionSet.add(this.province); + regionSet.add(this.city); + regionSet.add(this.area); regionSet.removeIf(Objects::isNull); return StringUtils.collectionToDelimitedString(regionSet, delimiter); } @@ -116,11 +116,11 @@ public String getAddressAndIsp() { */ public String getAddressAndIsp(String delimiter) { Set regionSet = new LinkedHashSet<>(); - regionSet.add(country); - regionSet.add(province); - regionSet.add(city); - regionSet.add(area); - regionSet.add(isp); + regionSet.add(this.country); + regionSet.add(this.province); + regionSet.add(this.city); + regionSet.add(this.area); + regionSet.add(this.isp); regionSet.removeIf(Objects::isNull); return StringUtils.collectionToDelimitedString(regionSet, delimiter); } diff --git a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheVectorIndexIp2regionSearcher.java b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheVectorIndexIp2regionSearcher.java index ba5c2a3f8..088a1b21f 100644 --- a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheVectorIndexIp2regionSearcher.java +++ b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheVectorIndexIp2regionSearcher.java @@ -45,7 +45,7 @@ public CacheVectorIndexIp2regionSearcher(ResourceLoader resourceLoader, Ip2regio @Override public void afterPropertiesSet() throws Exception { - Resource resource = resourceLoader.getResource(properties.getFileLocation()); + Resource resource = this.resourceLoader.getResource(this.properties.getFileLocation()); String dbPath = resource.getFile().getPath(); this.searcher = Searcher.newWithVectorIndex(dbPath, Searcher.loadVectorIndexFromFile(dbPath)); } diff --git a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheXdbFileIp2regionSearcher.java b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheXdbFileIp2regionSearcher.java index 9723693eb..eb954094e 100644 --- a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheXdbFileIp2regionSearcher.java +++ b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/CacheXdbFileIp2regionSearcher.java @@ -47,7 +47,7 @@ public CacheXdbFileIp2regionSearcher(ResourceLoader resourceLoader, Ip2regionPro @Override public void afterPropertiesSet() throws Exception { - Resource resource = resourceLoader.getResource(properties.getFileLocation()); + Resource resource = this.resourceLoader.getResource(this.properties.getFileLocation()); try (InputStream inputStream = resource.getInputStream()) { this.searcher = Searcher.newWithBuffer(StreamUtils.copyToByteArray(inputStream)); } diff --git a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTemplate.java b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTemplate.java index e52996bcb..7377b3fa0 100644 --- a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTemplate.java +++ b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTemplate.java @@ -45,14 +45,14 @@ public abstract class Ip2regionSearcherTemplate implements DisposableBean, Initi @Override @SneakyThrows({ IOException.class }) public IpInfo search(long ip) { - return IpInfoUtils.toIpInfo(Searcher.long2ip(ip), searcher.search(ip)); + return IpInfoUtils.toIpInfo(Searcher.long2ip(ip), this.searcher.search(ip)); } @Override @SneakyThrows({ Exception.class }) public IpInfo search(String ip) { - return IpInfoUtils.toIpInfo(ip, searcher.search(ip)); + return IpInfoUtils.toIpInfo(ip, this.searcher.search(ip)); } @Override diff --git a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/NoneCacheIp2regionSearcher.java b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/NoneCacheIp2regionSearcher.java index 0264b7571..86dfe979a 100644 --- a/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/NoneCacheIp2regionSearcher.java +++ b/ip/ballcat-spring-boot-starter-ip2region/src/main/java/org/ballcat/ip2region/searcher/NoneCacheIp2regionSearcher.java @@ -37,8 +37,8 @@ public NoneCacheIp2regionSearcher(ResourceLoader resourceLoader, Ip2regionProper @Override public void afterPropertiesSet() throws Exception { - Resource resource = resourceLoader.getResource(properties.getFileLocation()); - searcher = Searcher.newWithFileOnly(resource.getFile().getPath()); + Resource resource = this.resourceLoader.getResource(this.properties.getFileLocation()); + this.searcher = Searcher.newWithFileOnly(resource.getFile().getPath()); } } diff --git a/ip/ballcat-spring-boot-starter-ip2region/src/test/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTest.java b/ip/ballcat-spring-boot-starter-ip2region/src/test/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTest.java index 00d074fe3..240cf27fb 100644 --- a/ip/ballcat-spring-boot-starter-ip2region/src/test/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTest.java +++ b/ip/ballcat-spring-boot-starter-ip2region/src/test/java/org/ballcat/ip2region/searcher/Ip2regionSearcherTest.java @@ -35,7 +35,7 @@ public abstract class Ip2regionSearcherTest { protected Ip2regionSearcher ip2regionSearcher; protected void testIpSearch() { - IpInfo localIp = ip2regionSearcher.search("127.0.0.1"); + IpInfo localIp = this.ip2regionSearcher.search("127.0.0.1"); Assertions.assertNull(localIp.getCountry()); Assertions.assertNull(localIp.getProvince()); Assertions.assertNull(localIp.getArea()); @@ -47,7 +47,7 @@ protected void testIpSearch() { Assertions.assertEquals("内网IP", localIp.getAddressAndIsp()); Assertions.assertEquals("内网IP", localIp.getAddressAndIsp(",")); - IpInfo remoteIp = ip2regionSearcher.search("39.188.108.178"); + IpInfo remoteIp = this.ip2regionSearcher.search("39.188.108.178"); Assertions.assertEquals("中国", remoteIp.getCountry()); Assertions.assertEquals("浙江省", remoteIp.getProvince()); Assertions.assertNull(localIp.getArea()); @@ -60,8 +60,8 @@ protected void testIpSearch() { Assertions.assertEquals("中国 浙江省 宁波市 移动", remoteIp.getAddressAndIsp(" ")); String errorIp = "BallCat.Is.N.B"; - Assertions.assertNull(ip2regionSearcher.searchQuietly(errorIp)); - Assertions.assertThrowsExactly(NumberFormatException.class, () -> ip2regionSearcher.search(errorIp)); + Assertions.assertNull(this.ip2regionSearcher.searchQuietly(errorIp)); + Assertions.assertThrowsExactly(NumberFormatException.class, () -> this.ip2regionSearcher.search(errorIp)); } diff --git a/job/ballcat-spring-boot-starter-xxljob/src/main/java/org/ballcat/autoconfigure/xxljob/XxlJobAutoConfiguration.java b/job/ballcat-spring-boot-starter-xxljob/src/main/java/org/ballcat/autoconfigure/xxljob/XxlJobAutoConfiguration.java index 633ec2564..cdb230465 100644 --- a/job/ballcat-spring-boot-starter-xxljob/src/main/java/org/ballcat/autoconfigure/xxljob/XxlJobAutoConfiguration.java +++ b/job/ballcat-spring-boot-starter-xxljob/src/main/java/org/ballcat/autoconfigure/xxljob/XxlJobAutoConfiguration.java @@ -73,7 +73,7 @@ private String getExecutorName(XxlExecutorProperties properties) { return appName; } else { - return environment.getProperty("spring.application.name"); + return this.environment.getProperty("spring.application.name"); } } @@ -102,9 +102,9 @@ private String getLogPath(XxlExecutorProperties properties) { if (StringUtils.hasText(logPath)) { return logPath; } - return environment.getProperty("logging.file.path", "logs") + return this.environment.getProperty("logging.file.path", "logs") .concat("/") - .concat(Objects.requireNonNull(environment.getProperty("spring.application.name"))) + .concat(Objects.requireNonNull(this.environment.getProperty("spring.application.name"))) .concat("/jobs"); } diff --git a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/KafkaStreamBuilder.java b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/KafkaStreamBuilder.java index 722eb3fa6..557e24801 100644 --- a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/KafkaStreamBuilder.java +++ b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/KafkaStreamBuilder.java @@ -76,12 +76,12 @@ public KafkaStreamBuilder valueSerde(String className) { * */ public KafkaStreamBuilder addBootstrapServers(String uri) { - bootstrapServers.add(uri); + this.bootstrapServers.add(uri); return this; } public KafkaStreamBuilder addAllBootstrapServers(Collection uris) { - bootstrapServers.addAll(uris); + this.bootstrapServers.addAll(uris); return this; } @@ -89,7 +89,7 @@ public KafkaStreamBuilder addAllBootstrapServers(Collection uris) { * 添加配置 */ public KafkaStreamBuilder put(Object key, Object val) { - properties.put(key, val); + this.properties.put(key, val); return this; } @@ -107,157 +107,158 @@ public KafkaStreamBuilder putAll(Map map) { } public KafkaStreamBuilder applicationId(String aId) { - properties.put(StreamsConfig.APPLICATION_ID_CONFIG, aId); + this.properties.put(StreamsConfig.APPLICATION_ID_CONFIG, aId); return this; } public synchronized KafkaStreamBuilder addSource(String name, String... topics) { - topology.addSource(name, topics); + this.topology.addSource(name, topics); return this; } public synchronized KafkaStreamBuilder addSource(String name, Pattern topicPattern) { - topology.addSource(name, topicPattern); + this.topology.addSource(name, topicPattern); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, String name, String... topics) { - topology.addSource(offsetReset, name, topics); + this.topology.addSource(offsetReset, name, topics); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, String name, Pattern topicPattern) { - topology.addSource(offsetReset, name, topicPattern); + this.topology.addSource(offsetReset, name, topicPattern); return this; } public synchronized KafkaStreamBuilder addSource(TimestampExtractor timestampExtractor, String name, String... topics) { - topology.addSource(timestampExtractor, name, topics); + this.topology.addSource(timestampExtractor, name, topics); return this; } public synchronized KafkaStreamBuilder addSource(TimestampExtractor timestampExtractor, String name, Pattern topicPattern) { - topology.addSource(timestampExtractor, name, topicPattern); + this.topology.addSource(timestampExtractor, name, topicPattern); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, TimestampExtractor timestampExtractor, String name, String... topics) { - topology.addSource(offsetReset, timestampExtractor, name, topics); + this.topology.addSource(offsetReset, timestampExtractor, name, topics); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, TimestampExtractor timestampExtractor, String name, Pattern topicPattern) { - topology.addSource(offsetReset, timestampExtractor, name, topicPattern); + this.topology.addSource(offsetReset, timestampExtractor, name, topicPattern); return this; } public synchronized KafkaStreamBuilder addSource(String name, Deserializer keyDeserializer, Deserializer valueDeserializer, String... topics) { - topology.addSource(name, keyDeserializer, valueDeserializer, topics); + this.topology.addSource(name, keyDeserializer, valueDeserializer, topics); return this; } public synchronized KafkaStreamBuilder addSource(String name, Deserializer keyDeserializer, Deserializer valueDeserializer, Pattern topicPattern) { - topology.addSource(name, keyDeserializer, valueDeserializer, topicPattern); + this.topology.addSource(name, keyDeserializer, valueDeserializer, topicPattern); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, String name, Deserializer keyDeserializer, Deserializer valueDeserializer, String... topics) { - topology.addSource(offsetReset, name, keyDeserializer, valueDeserializer, topics); + this.topology.addSource(offsetReset, name, keyDeserializer, valueDeserializer, topics); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, String name, Deserializer keyDeserializer, Deserializer valueDeserializer, Pattern topicPattern) { - topology.addSource(offsetReset, name, keyDeserializer, valueDeserializer, topicPattern); + this.topology.addSource(offsetReset, name, keyDeserializer, valueDeserializer, topicPattern); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, String name, TimestampExtractor timestampExtractor, Deserializer keyDeserializer, Deserializer valueDeserializer, String... topics) { - topology.addSource(offsetReset, name, timestampExtractor, keyDeserializer, valueDeserializer, topics); + this.topology.addSource(offsetReset, name, timestampExtractor, keyDeserializer, valueDeserializer, topics); return this; } public synchronized KafkaStreamBuilder addSource(Topology.AutoOffsetReset offsetReset, String name, TimestampExtractor timestampExtractor, Deserializer keyDeserializer, Deserializer valueDeserializer, Pattern topicPattern) { - topology.addSource(offsetReset, name, timestampExtractor, keyDeserializer, valueDeserializer, topicPattern); + this.topology.addSource(offsetReset, name, timestampExtractor, keyDeserializer, valueDeserializer, + topicPattern); return this; } public synchronized KafkaStreamBuilder addSink(String name, String topic, String... parentNames) { - topology.addSink(name, topic, parentNames); + this.topology.addSink(name, topic, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, String topic, StreamPartitioner partitioner, String... parentNames) { - topology.addSink(name, topic, partitioner, parentNames); + this.topology.addSink(name, topic, partitioner, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, String topic, Serializer keySerializer, Serializer valueSerializer, String... parentNames) { - topology.addSink(name, topic, keySerializer, valueSerializer, parentNames); + this.topology.addSink(name, topic, keySerializer, valueSerializer, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, String topic, Serializer keySerializer, Serializer valueSerializer, StreamPartitioner partitioner, String... parentNames) { - topology.addSink(name, topic, keySerializer, valueSerializer, partitioner, parentNames); + this.topology.addSink(name, topic, keySerializer, valueSerializer, partitioner, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, TopicNameExtractor topicExtractor, String... parentNames) { - topology.addSink(name, topicExtractor, parentNames); + this.topology.addSink(name, topicExtractor, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, TopicNameExtractor topicExtractor, StreamPartitioner partitioner, String... parentNames) { - topology.addSink(name, topicExtractor, partitioner, parentNames); + this.topology.addSink(name, topicExtractor, partitioner, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, TopicNameExtractor topicExtractor, Serializer keySerializer, Serializer valueSerializer, String... parentNames) { - topology.addSink(name, topicExtractor, keySerializer, valueSerializer, parentNames); + this.topology.addSink(name, topicExtractor, keySerializer, valueSerializer, parentNames); return this; } public synchronized KafkaStreamBuilder addSink(String name, TopicNameExtractor topicExtractor, Serializer keySerializer, Serializer valueSerializer, StreamPartitioner partitioner, String... parentNames) { - topology.addSink(name, topicExtractor, keySerializer, valueSerializer, partitioner, parentNames); + this.topology.addSink(name, topicExtractor, keySerializer, valueSerializer, partitioner, parentNames); return this; } public synchronized KafkaStreamBuilder addProcessor(String name, ProcessorSupplier supplier, String... parentNames) { - topology.addProcessor(name, supplier, parentNames); + this.topology.addProcessor(name, supplier, parentNames); return this; } public synchronized KafkaStreamBuilder addStateStore(StoreBuilder storeBuilder, String... processorNames) { - topology.addStateStore(storeBuilder, processorNames); + this.topology.addStateStore(storeBuilder, processorNames); return this; } public synchronized KafkaStreamBuilder addGlobalStore(StoreBuilder storeBuilder, String sourceName, Deserializer keyDeserializer, Deserializer valueDeserializer, String topic, String processorName, ProcessorSupplier stateUpdateSupplier) { - topology.addGlobalStore(storeBuilder, sourceName, keyDeserializer, valueDeserializer, topic, processorName, + this.topology.addGlobalStore(storeBuilder, sourceName, keyDeserializer, valueDeserializer, topic, processorName, stateUpdateSupplier); return this; } @@ -269,14 +270,14 @@ public synchronized KafkaStreamBuilder addGlobalStore(StoreBuilder sto public synchronized KafkaStreamBuilder addGlobalStore(StoreBuilder storeBuilder, String sourceName, TimestampExtractor timestampExtractor, Deserializer keyDeserializer, Deserializer valueDeserializer, String topic, String processorName, ProcessorSupplier stateUpdateSupplier) { - topology.addGlobalStore(storeBuilder, sourceName, timestampExtractor, keyDeserializer, valueDeserializer, topic, - processorName, stateUpdateSupplier); + this.topology.addGlobalStore(storeBuilder, sourceName, timestampExtractor, keyDeserializer, valueDeserializer, + topic, processorName, stateUpdateSupplier); return this; } public synchronized KafkaStreamBuilder connectProcessorAndStateStores(String processorName, String... stateStoreNames) { - topology.connectProcessorAndStateStores(processorName, stateStoreNames); + this.topology.connectProcessorAndStateStores(processorName, stateStoreNames); return this; } @@ -284,7 +285,7 @@ public synchronized KafkaStreamBuilder connectProcessorAndStateStores(String pro * 自定义的构筑方法, 传入 topology 和属性 */ public KafkaStreams build(BiFunction biFunction) { - return biFunction.apply(topology, getProperties()); + return biFunction.apply(this.topology, getProperties()); } public KafkaStreams build(Properties properties) { @@ -302,15 +303,16 @@ public KafkaStreams build() { public Set getBootstrapServers() { getProperties(); - return bootstrapServers; + return this.bootstrapServers; } public Properties getProperties() { - bootstrapServers.addAll(Arrays.asList(properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "") - .split(BOOTSTRAP_SERVERS_DELIMITER))); - properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, - String.join(BOOTSTRAP_SERVERS_DELIMITER, bootstrapServers)); - return properties; + this.bootstrapServers + .addAll(Arrays.asList(this.properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "") + .split(BOOTSTRAP_SERVERS_DELIMITER))); + this.properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, + String.join(BOOTSTRAP_SERVERS_DELIMITER, this.bootstrapServers)); + return this.properties; } } diff --git a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractProcessor.java b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractProcessor.java index 6527d6180..567b0fae9 100644 --- a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractProcessor.java +++ b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractProcessor.java @@ -55,7 +55,7 @@ public void initSchedule(ProcessorContext context) { * 用于构筑 Punctuator */ public void schedule(Duration interval, PunctuationType type, AbstractPunctuator callback) { - context.schedule(interval, type, callback); + this.context.schedule(interval, type, callback); } /** @@ -72,7 +72,7 @@ public void schedule(Duration interval, AbstractPunctuator callback) { * @param childName 目标名称 */ public void forward(K key, V value, String childName) { - context.forward(key, value, To.child(childName)); + this.context.forward(key, value, To.child(childName)); } /** @@ -82,15 +82,15 @@ public void forward(K key, V value, String childName) { * @param to 目标 */ public void forward(K key, V value, To to) { - context.forward(key, value, to); + this.context.forward(key, value, to); } public void startLog(K key, V value) { - log.debug("收到消息 {} key: {} value: {}", ProcessorContextUtil.toLogString(context), key, value); + log.debug("收到消息 {} key: {} value: {}", ProcessorContextUtil.toLogString(this.context), key, value); } public void errLog(Throwable e) { - log.error("processor 操作数据出错 " + ProcessorContextUtil.toLogString(context), e); + log.error("processor 操作数据出错 " + ProcessorContextUtil.toLogString(this.context), e); } @Override @@ -98,7 +98,7 @@ public void process(K key, V value) { // 由于测试中存在 处理过程报错,整个 topology 停止运行,所以直接捕获异常 try { startLog(key, value); - process(context, key, value); + process(this.context, key, value); } catch (Exception e) { errLog(e); diff --git a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractPunctuator.java b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractPunctuator.java index 49d247dd9..85aabbd62 100644 --- a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractPunctuator.java +++ b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/core/AbstractPunctuator.java @@ -56,7 +56,7 @@ public boolean isHandle() { * handle 开始日志 */ public void startLog() { - log.debug("任务开始执行, 类名 {} ,{}", this.getClass().getSimpleName(), ProcessorContextUtil.toLogString(context)); + log.debug("任务开始执行, 类名 {} ,{}", this.getClass().getSimpleName(), ProcessorContextUtil.toLogString(this.context)); } /** @@ -65,7 +65,7 @@ public void startLog() { */ public void endLog(long time) { log.debug("任务执行时长: {}, 类名 {}, {} ", time, this.getClass().getSimpleName(), - ProcessorContextUtil.toLogString(context)); + ProcessorContextUtil.toLogString(this.context)); } /** @@ -73,7 +73,7 @@ public void endLog(long time) { */ public void errLog(Throwable e) { log.error("punctuator 操作数据出错 类名 " + this.getClass().getSimpleName() + ", " - + ProcessorContextUtil.toLogString(context), e); + + ProcessorContextUtil.toLogString(this.context), e); } @Override @@ -88,7 +88,7 @@ public void punctuate(long timestamp) { endLog(watch.timeMillis()); // 清除数据 clean(); - context.commit(); + this.context.commit(); } finally { watch.stop(); diff --git a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/extend/AbstractKeyValueStorePunctuator.java b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/extend/AbstractKeyValueStorePunctuator.java index 7c95eeb81..97a660ad4 100644 --- a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/extend/AbstractKeyValueStorePunctuator.java +++ b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/extend/AbstractKeyValueStorePunctuator.java @@ -59,7 +59,7 @@ public AbstractKeyValueStorePunctuator init(ProcessorContext context) { public AbstractKeyValueStorePunctuator init(ProcessorContext context, String storeName, BiFunction signHandle) { super.init(context); - store = getStore(storeName); + this.store = getStore(storeName); this.signHandle = signHandle; return this; } @@ -73,7 +73,7 @@ public long getHandleSize() { @Override public void handle(long timestamp) { - KeyValueIterator iterator = store.all(); + KeyValueIterator iterator = this.store.all(); List list = new ArrayList<>(); while (iterator.hasNext()) { @@ -82,8 +82,8 @@ public void handle(long timestamp) { list.clear(); } KeyValue kv = iterator.next(); - list.add(signHandle.apply(kv.key, kv.value)); - store.delete(kv.key); + list.add(this.signHandle.apply(kv.key, kv.value)); + this.store.delete(kv.key); } runHandle(timestamp, list); } diff --git a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/store/KafkaKeyValueStore.java b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/store/KafkaKeyValueStore.java index 1ee554241..6bb0aea0d 100644 --- a/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/store/KafkaKeyValueStore.java +++ b/kafka/ballcat-kafka-stream/src/main/java/org/ballcat/kafka/stream/store/KafkaKeyValueStore.java @@ -57,7 +57,7 @@ public static KafkaKeyValueStore init(KeyValueStore store, Su } public KeyValueIterator all() { - return store.all(); + return this.store.all(); } public void forEachRemaining(Consumer> action) { @@ -81,16 +81,16 @@ public List values() { * @return 生成的key */ public K getKey() { - return supplier.get(); + return this.supplier.get(); } public void put(V v) { - pushValue(v, store); + pushValue(v, this.store); } public void put(K k, V v) { if (check(v)) { - forkPush(k, v, store); + forkPush(k, v, this.store); } } @@ -121,7 +121,7 @@ public void forkPush(K k, V v, KeyValueStore kvKeyValueStore) { } public V delete(K key) { - return store.delete(key); + return this.store.delete(key); } } diff --git a/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaConsumerBuilder.java b/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaConsumerBuilder.java index b3861d8c4..519bc7f7f 100644 --- a/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaConsumerBuilder.java +++ b/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaConsumerBuilder.java @@ -64,12 +64,12 @@ public KafkaConsumerBuilder valueDeserializer(String className) { * 添加 kafka 路径 host:port */ public KafkaConsumerBuilder addBootstrapServers(String uri) { - bootstrapServers.add(uri); + this.bootstrapServers.add(uri); return this; } public KafkaConsumerBuilder addAllBootstrapServers(Collection uris) { - bootstrapServers.addAll(uris); + this.bootstrapServers.addAll(uris); return this; } @@ -77,7 +77,7 @@ public KafkaConsumerBuilder addAllBootstrapServers(Collection uris) { * 添加配置 */ public KafkaConsumerBuilder put(Object key, Object val) { - properties.put(key, val); + this.properties.put(key, val); return this; } @@ -97,7 +97,7 @@ public KafkaConsumerBuilder groupId(String groupId) { } public KafkaConsumerBuilder addTopic(String topic) { - topics.add(topic); + this.topics.add(topic); return this; } @@ -108,7 +108,7 @@ public KafkaConsumerBuilder addAllTopic(Collection topics) { public KafkaConsumer build(Function> function) { KafkaConsumer consumer = function.apply(getProperties()); - consumer.subscribe(topics); + consumer.subscribe(this.topics); return consumer; } @@ -122,18 +122,18 @@ public KafkaConsumer build() { public Set getBootstrapServers() { getProperties(); - return bootstrapServers; + return this.bootstrapServers; } public Properties getProperties() { - String nowServes = properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, ""); + String nowServes = this.properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, ""); if (nowServes.length() > 0) { // 仅在存在配置时才插入 - bootstrapServers.addAll(Arrays.asList(nowServes.split(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER))); + this.bootstrapServers.addAll(Arrays.asList(nowServes.split(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER))); } - properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, - String.join(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER, bootstrapServers)); - return properties; + this.properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, + String.join(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER, this.bootstrapServers)); + return this.properties; } } diff --git a/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaExtendProducer.java b/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaExtendProducer.java index 43ccf3ab1..13c2f4638 100644 --- a/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaExtendProducer.java +++ b/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaExtendProducer.java @@ -68,7 +68,7 @@ public ProducerRecord record(String topic, V value) { } public Future send(ProducerRecord record, Callback callback) { - return producer.send(record, callback); + return this.producer.send(record, callback); } public Future send(String topic, Integer partition, Long timestamp, K key, V value, diff --git a/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaProducerBuilder.java b/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaProducerBuilder.java index fcffc6d67..bd230b61e 100644 --- a/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaProducerBuilder.java +++ b/kafka/ballcat-kafka/src/main/java/org/ballcat/kafka/KafkaProducerBuilder.java @@ -61,12 +61,12 @@ public KafkaProducerBuilder valueSerializer(String className) { * 添加 kafka 路径 host:port */ public KafkaProducerBuilder addBootstrapServers(String uri) { - bootstrapServers.add(uri); + this.bootstrapServers.add(uri); return this; } public KafkaProducerBuilder addAllBootstrapServers(Collection uris) { - bootstrapServers.addAll(uris); + this.bootstrapServers.addAll(uris); return this; } @@ -74,7 +74,7 @@ public KafkaProducerBuilder addAllBootstrapServers(Collection uris) { * 添加配置 */ public KafkaProducerBuilder put(Object key, Object val) { - properties.put(key, val); + this.properties.put(key, val); return this; } @@ -105,15 +105,16 @@ public KafkaExtendProducer build() { public Set getBootstrapServers() { getProperties(); - return bootstrapServers; + return this.bootstrapServers; } public Properties getProperties() { - bootstrapServers.addAll(Arrays.asList(properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "") - .split(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER))); - properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, - String.join(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER, bootstrapServers)); - return properties; + this.bootstrapServers + .addAll(Arrays.asList(this.properties.getProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "") + .split(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER))); + this.properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, + String.join(KafkaConstants.BOOTSTRAP_SERVERS_DELIMITER, this.bootstrapServers)); + return this.properties; } } diff --git a/kafka/ballcat-spring-boot-starter-kafka/src/main/java/org/ballcat/autoconfigure/kafka/KafkaProperties.java b/kafka/ballcat-spring-boot-starter-kafka/src/main/java/org/ballcat/autoconfigure/kafka/KafkaProperties.java index f2f2691d6..b5e27bbe5 100644 --- a/kafka/ballcat-spring-boot-starter-kafka/src/main/java/org/ballcat/autoconfigure/kafka/KafkaProperties.java +++ b/kafka/ballcat-spring-boot-starter-kafka/src/main/java/org/ballcat/autoconfigure/kafka/KafkaProperties.java @@ -91,29 +91,29 @@ public class KafkaProperties { private Map extend = new HashMap<>(); public String getKeyDeserializerClassName() { - if (StringUtils.hasText(keyDeserializerClassName)) { - return keyDeserializerClassName; + if (StringUtils.hasText(this.keyDeserializerClassName)) { + return this.keyDeserializerClassName; } return getKeyDeserializer().getName(); } public String getValueDeserializerClassName() { - if (StringUtils.hasText(valueDeserializerClassName)) { - return valueDeserializerClassName; + if (StringUtils.hasText(this.valueDeserializerClassName)) { + return this.valueDeserializerClassName; } return getValueDeserializer().getName(); } public String getKeySerializerClassName() { - if (StringUtils.hasText(keySerializerClassName)) { - return keySerializerClassName; + if (StringUtils.hasText(this.keySerializerClassName)) { + return this.keySerializerClassName; } return getKeySerializer().getName(); } public String getValueSerializerClassName() { - if (StringUtils.hasText(valueSerializerClassName)) { - return valueSerializerClassName; + if (StringUtils.hasText(this.valueSerializerClassName)) { + return this.valueSerializerClassName; } return getValueSerializer().getName(); } diff --git a/log/ballcat-log/src/main/java/org/ballcat/log/operation/aspect/OperationLogAspect.java b/log/ballcat-log/src/main/java/org/ballcat/log/operation/aspect/OperationLogAspect.java index 71a5e6765..05ea948d9 100644 --- a/log/ballcat-log/src/main/java/org/ballcat/log/operation/aspect/OperationLogAspect.java +++ b/log/ballcat-log/src/main/java/org/ballcat/log/operation/aspect/OperationLogAspect.java @@ -57,7 +57,7 @@ public Object around(ProceedingJoinPoint joinPoint) throws Throwable { // 获取操作日志 DTO Assert.notNull(operationLogging, "operationLogging annotation must not be null!"); - T operationLog = operationLogHandler.buildLog(operationLogging, joinPoint); + T operationLog = this.operationLogHandler.buildLog(operationLogging, joinPoint); Throwable throwable = null; Object result = null; @@ -83,10 +83,10 @@ private void handleLog(ProceedingJoinPoint joinPoint, long startTime, T operatio // 结束时间 long executionTime = System.currentTimeMillis() - startTime; // 记录执行信息 - operationLogHandler.recordExecutionInfo(operationLog, joinPoint, executionTime, throwable, isSaveResult, - result); + this.operationLogHandler.recordExecutionInfo(operationLog, joinPoint, executionTime, throwable, + isSaveResult, result); // 处理操作日志 - operationLogHandler.handleLog(operationLog); + this.operationLogHandler.handleLog(operationLog); } catch (Exception e) { log.error("记录操作日志异常:{}", operationLog); diff --git a/log/ballcat-log/src/main/java/org/ballcat/log/operation/handler/AbstractOperationLogHandler.java b/log/ballcat-log/src/main/java/org/ballcat/log/operation/handler/AbstractOperationLogHandler.java index a88e465d0..de575f1df 100644 --- a/log/ballcat-log/src/main/java/org/ballcat/log/operation/handler/AbstractOperationLogHandler.java +++ b/log/ballcat-log/src/main/java/org/ballcat/log/operation/handler/AbstractOperationLogHandler.java @@ -53,7 +53,7 @@ public abstract class AbstractOperationLogHandler implements OperationLogHand * @param clazz 参数类型 */ public void addIgnoredParamClass(Class clazz) { - ignoredParamClasses.add(clazz); + this.ignoredParamClasses.add(clazz); } /** @@ -83,7 +83,7 @@ public String getParams(ProceedingJoinPoint joinPoint) { } Class argClass = arg.getClass(); // 忽略部分类型的参数记录 - for (Class ignoredParamClass : ignoredParamClasses) { + for (Class ignoredParamClass : this.ignoredParamClasses) { if (ignoredParamClass.isAssignableFrom(argClass)) { arg = "ignored param type: " + argClass; break; diff --git a/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/model/MailSendInfo.java b/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/model/MailSendInfo.java index 68c16f9c2..a0bfa8706 100644 --- a/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/model/MailSendInfo.java +++ b/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/model/MailSendInfo.java @@ -51,11 +51,11 @@ public MailSendInfo(MailDetails mailDetails) { private String errorMsg; public MailDetails getMailDetails() { - return mailDetails; + return this.mailDetails; } public LocalDateTime getSentDate() { - return sentDate; + return this.sentDate; } public void setSentDate(LocalDateTime sentDate) { @@ -63,7 +63,7 @@ public void setSentDate(LocalDateTime sentDate) { } public Boolean getSuccess() { - return success; + return this.success; } public void setSuccess(Boolean success) { @@ -71,7 +71,7 @@ public void setSuccess(Boolean success) { } public String getErrorMsg() { - return errorMsg; + return this.errorMsg; } public void setErrorMsg(String errorMsg) { diff --git a/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/sender/MailSenderImpl.java b/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/sender/MailSenderImpl.java index 8f3464900..c28a024cf 100644 --- a/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/sender/MailSenderImpl.java +++ b/mail/ballcat-spring-boot-starter-mail/src/main/java/org/ballcat/mail/sender/MailSenderImpl.java @@ -73,7 +73,7 @@ public MailSendInfo sendMail(MailDetails mailDetails) { } finally { // 发布邮件发送事件 - eventPublisher.publishEvent(new MailSendEvent(mailSendInfo)); + this.eventPublisher.publishEvent(new MailSendEvent(mailSendInfo)); } return mailSendInfo; } @@ -84,8 +84,8 @@ public MailSendInfo sendMail(MailDetails mailDetails) { */ private void sendMimeMail(MailDetails mailDetails) throws MessagingException { // true表示支持复杂类型 - MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true); - String from = StringUtils.hasText(mailDetails.getFrom()) ? mailDetails.getFrom() : defaultFrom; + MimeMessageHelper messageHelper = new MimeMessageHelper(this.mailSender.createMimeMessage(), true); + String from = StringUtils.hasText(mailDetails.getFrom()) ? mailDetails.getFrom() : this.defaultFrom; messageHelper.setFrom(from); messageHelper.setSubject(mailDetails.getSubject()); if (mailDetails.getTo() != null && mailDetails.getTo().length > 0) { @@ -106,7 +106,7 @@ private void sendMimeMail(MailDetails mailDetails) throws MessagingException { } } - mailSender.send(messageHelper.getMimeMessage()); + this.mailSender.send(messageHelper.getMimeMessage()); log.info("发送邮件成功:[{}]", mailDetails); } diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaAliasQueryWrapperX.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaAliasQueryWrapperX.java index 9af39091a..e7110b1c7 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaAliasQueryWrapperX.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaAliasQueryWrapperX.java @@ -68,10 +68,10 @@ public LambdaAliasQueryWrapperX(Class entityClass) { * @return String allAliasSqlSelect */ public String getAllAliasSqlSelect() { - if (allAliasSqlSelect == null) { - allAliasSqlSelect = TableAliasHelper.tableAliasSelectSql(getEntityClass()); + if (this.allAliasSqlSelect == null) { + this.allAliasSqlSelect = TableAliasHelper.tableAliasSelectSql(getEntityClass()); } - return allAliasSqlSelect; + return this.allAliasSqlSelect; } /** @@ -82,9 +82,9 @@ public String getAllAliasSqlSelect() { */ @Override protected LambdaAliasQueryWrapperX instance() { - return new LambdaAliasQueryWrapperX<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs, - new MergeSegments(), this.paramAlias, SharedString.emptyString(), SharedString.emptyString(), - SharedString.emptyString()); + return new LambdaAliasQueryWrapperX<>(getEntity(), getEntityClass(), null, this.paramNameSeq, + this.paramNameValuePairs, new MergeSegments(), this.paramAlias, SharedString.emptyString(), + SharedString.emptyString(), SharedString.emptyString()); } /** @@ -100,7 +100,7 @@ protected String columnToString(SFunction column) { return columnFunction.apply(null); } String columnName = super.columnToString(column, true); - return tableAlias == null ? columnName : tableAlias + "." + columnName; + return this.tableAlias == null ? columnName : this.tableAlias + "." + columnName; } } diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaQueryWrapperX.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaQueryWrapperX.java index f743d3c46..545834bd8 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaQueryWrapperX.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/conditions/query/LambdaQueryWrapperX.java @@ -83,7 +83,7 @@ public LambdaQueryWrapperX select(boolean condition, List> co if (condition && CollectionUtils.isNotEmpty(columns)) { this.sqlSelect.setStringValue(columnsToString(false, columns)); } - return typedThis; + return this.typedThis; } /** @@ -116,12 +116,12 @@ public LambdaQueryWrapperX select(Class entityClass, Predicate instance() { - return new LambdaQueryWrapperX<>(getEntity(), getEntityClass(), null, paramNameSeq, paramNameValuePairs, - new MergeSegments(), paramAlias, SharedString.emptyString(), SharedString.emptyString(), - SharedString.emptyString()); + return new LambdaQueryWrapperX<>(getEntity(), getEntityClass(), null, this.paramNameSeq, + this.paramNameValuePairs, new MergeSegments(), this.paramAlias, SharedString.emptyString(), + SharedString.emptyString(), SharedString.emptyString()); } @Override public void clear() { super.clear(); - sqlSelect.toNull(); + this.sqlSelect.toNull(); } // ======= 分界线,以上 copy 自 mybatis-plus 源码 ===== diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/BaseInsertBatch.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/BaseInsertBatch.java index 2aec313fb..1f4e5b976 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/BaseInsertBatch.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/BaseInsertBatch.java @@ -39,7 +39,7 @@ protected BaseInsertBatch(String methodName) { @Override public MappedStatement injectMappedStatement(Class mapperClass, Class modelClass, TableInfo tableInfo) { - SqlSource sqlSource = languageDriver.createSqlSource(configuration, String.format(getSql(), + SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, String.format(getSql(), tableInfo.getTableName(), prepareFieldSql(tableInfo), prepareValuesSqlForMysqlBatch(tableInfo)), modelClass); @@ -58,7 +58,7 @@ public MappedStatement injectMappedStatement(Class mapperClass, Class mode } else { if (null != tableInfo.getKeySequence()) { - keyGenerator = TableInfoHelper.genKeyGenerator(this.methodName, tableInfo, builderAssistant); + keyGenerator = TableInfoHelper.genKeyGenerator(this.methodName, tableInfo, this.builderAssistant); keyProperty = getKeyProperty(tableInfo); keyColumn = tableInfo.getKeyColumn(); } diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertBatchSomeColumnByCollection.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertBatchSomeColumnByCollection.java index 2596960f8..3fc5f1f22 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertBatchSomeColumnByCollection.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertBatchSomeColumnByCollection.java @@ -73,10 +73,10 @@ public MappedStatement injectMappedStatement(Class mapperClass, Class mode SqlMethod sqlMethod = SqlMethod.INSERT_ONE; List fieldList = tableInfo.getFieldList(); String insertSqlColumn = tableInfo.getKeyInsertSqlColumn(true, null, false) - + this.filterTableFieldInfo(fieldList, predicate, TableFieldInfo::getInsertSqlColumn, EMPTY); + + this.filterTableFieldInfo(fieldList, this.predicate, TableFieldInfo::getInsertSqlColumn, EMPTY); String columnScript = LEFT_BRACKET + insertSqlColumn.substring(0, insertSqlColumn.length() - 1) + RIGHT_BRACKET; String insertSqlProperty = tableInfo.getKeyInsertSqlProperty(true, ENTITY_DOT, false) - + this.filterTableFieldInfo(fieldList, predicate, i -> i.getInsertSqlProperty(ENTITY_DOT), EMPTY); + + this.filterTableFieldInfo(fieldList, this.predicate, i -> i.getInsertSqlProperty(ENTITY_DOT), EMPTY); insertSqlProperty = LEFT_BRACKET + insertSqlProperty.substring(0, insertSqlProperty.length() - 1) + RIGHT_BRACKET; // 从 list 改为 collection. 允许传入除 list外的参数类型 @@ -93,14 +93,14 @@ public MappedStatement injectMappedStatement(Class mapperClass, Class mode } else { if (null != tableInfo.getKeySequence()) { - keyGenerator = TableInfoHelper.genKeyGenerator(this.methodName, tableInfo, builderAssistant); + keyGenerator = TableInfoHelper.genKeyGenerator(this.methodName, tableInfo, this.builderAssistant); keyProperty = tableInfo.getKeyProperty(); keyColumn = tableInfo.getKeyColumn(); } } } String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript); - SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass); + SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sql, modelClass); return this.addInsertMappedStatement(mapperClass, modelClass, this.methodName, sqlSource, keyGenerator, keyProperty, keyColumn); } diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertOrUpdateByBatch.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertOrUpdateByBatch.java index 8a02d5767..d6a293aeb 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertOrUpdateByBatch.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/methods/InsertOrUpdateByBatch.java @@ -58,7 +58,7 @@ protected String prepareValuesSqlForMysqlBatch(TableInfo tableInfo) { // 默认忽略逻辑删除字段 if (!field.isLogicDelete()) { // 默认忽略字段 - if (!predicate.test(field)) { + if (!this.predicate.test(field)) { sql.append(field.getColumn()).append("=").append("VALUES(").append(field.getColumn()).append("),"); } else { diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/service/impl/ExtendServiceImpl.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/service/impl/ExtendServiceImpl.java index 7dd9ad41b..c3a204cbd 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/service/impl/ExtendServiceImpl.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/service/impl/ExtendServiceImpl.java @@ -59,14 +59,14 @@ public class ExtendServiceImpl, T> implements ExtendSe @Override public M getBaseMapper() { - return baseMapper; + return this.baseMapper; } protected Class entityClass = currentModelClass(); @Override public Class getEntityClass() { - return entityClass; + return this.entityClass; } protected Class mapperClass = currentMapperClass(); @@ -110,7 +110,7 @@ public boolean saveBatch(Collection entityList, int batchSize) { * @since 3.4.0 */ protected String getSqlStatement(SqlMethod sqlMethod) { - return SqlHelper.getSqlStatement(mapperClass, sqlMethod); + return SqlHelper.getSqlStatement(this.mapperClass, sqlMethod); } /** @@ -136,7 +136,7 @@ public boolean saveOrUpdate(T entity) { @Transactional(rollbackFor = Exception.class) @Override public boolean saveOrUpdateBatch(Collection entityList, int batchSize) { - TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass); + TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass); Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!"); String keyProperty = tableInfo.getKeyProperty(); Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!"); @@ -200,9 +200,9 @@ public boolean removeByIds(Collection list) { @Override public boolean removeById(Serializable id, boolean useFill) { - TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass); + TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass); if (useFill && tableInfo.isWithLogicDelete()) { - if (entityClass.isAssignableFrom(id.getClass())) { + if (this.entityClass.isAssignableFrom(id.getClass())) { return SqlHelper.retBool(getBaseMapper().deleteById(id)); } T instance = tableInfo.newInstance(); @@ -215,7 +215,7 @@ public boolean removeById(Serializable id, boolean useFill) { @Override @Transactional(rollbackFor = Exception.class) public boolean removeBatchByIds(Collection list, int batchSize) { - TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass); + TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass); return removeBatchByIds(list, batchSize, tableInfo.isWithLogicDelete() && tableInfo.isWithUpdateFill()); } @@ -223,10 +223,10 @@ public boolean removeBatchByIds(Collection list, int batchSize) { @Transactional(rollbackFor = Exception.class) public boolean removeBatchByIds(Collection list, int batchSize, boolean useFill) { String sqlStatement = getSqlStatement(SqlMethod.DELETE_BY_ID); - TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass); + TableInfo tableInfo = TableInfoHelper.getTableInfo(this.entityClass); return executeBatch(list, batchSize, (sqlSession, e) -> { if (useFill && tableInfo.isWithLogicDelete()) { - if (entityClass.isAssignableFrom(e.getClass())) { + if (this.entityClass.isAssignableFrom(e.getClass())) { sqlSession.update(sqlStatement, e); } else { @@ -260,13 +260,13 @@ public boolean saveBatchSomeColumn(Collection list, int batchSize) { List subList = new ArrayList<>(batch); for (T t : list) { if (subList.size() >= batch) { - baseMapper.insertBatchSomeColumn(subList); + this.baseMapper.insertBatchSomeColumn(subList); subList = new ArrayList<>(batch); } subList.add(t); } if (CollectionUtils.isEmpty(subList)) { - baseMapper.insertBatchSomeColumn(subList); + this.baseMapper.insertBatchSomeColumn(subList); } return true; } diff --git a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/type/EnumNameTypeHandler.java b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/type/EnumNameTypeHandler.java index 00dbc81a2..b97a371b0 100644 --- a/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/type/EnumNameTypeHandler.java +++ b/mybatis-plus/ballcat-mybatis-plus/src/main/java/org/ballcat/mybatisplus/type/EnumNameTypeHandler.java @@ -89,7 +89,7 @@ Object getValByEnum(E e) { * @author lingting 2021-06-07 13:50 */ E getEnumByName(String val) { - for (E e : type.getEnumConstants()) { + for (E e : this.type.getEnumConstants()) { Object ev = getValByEnum(e); if (ev == null) { if (val == null) { diff --git a/ntp/ballcat-ntp/src/main/java/org/ballcat/ntp/Ntp.java b/ntp/ballcat-ntp/src/main/java/org/ballcat/ntp/Ntp.java index 5ab417872..abfe8284c 100644 --- a/ntp/ballcat-ntp/src/main/java/org/ballcat/ntp/Ntp.java +++ b/ntp/ballcat-ntp/src/main/java/org/ballcat/ntp/Ntp.java @@ -50,8 +50,8 @@ public static long diff(String host) { public Ntp(String host) { try { - diff = diff(host); - log.warn("授时中心时间与系统时间差为 {} 毫秒", diff); + this.diff = diff(host); + log.warn("授时中心时间与系统时间差为 {} 毫秒", this.diff); } catch (Exception e) { throw new NtpException("ntp初始化异常!", e); @@ -59,7 +59,7 @@ public Ntp(String host) { } public long currentMillis() { - return System.currentTimeMillis() + diff; + return System.currentTimeMillis() + this.diff; } /** diff --git a/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/autoconfigure/openapi/OpenApiAutoConfiguration.java b/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/autoconfigure/openapi/OpenApiAutoConfiguration.java index af503f9c8..67921ba40 100644 --- a/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/autoconfigure/openapi/OpenApiAutoConfiguration.java +++ b/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/autoconfigure/openapi/OpenApiAutoConfiguration.java @@ -67,18 +67,18 @@ public OpenAPI openAPI() { OpenAPI openAPI = new OpenAPI(); // 文档基本信息 - OpenApiProperties.InfoProperties infoProperties = openApiProperties.getInfo(); + OpenApiProperties.InfoProperties infoProperties = this.openApiProperties.getInfo(); Info info = convertInfo(infoProperties); openAPI.info(info); // 扩展文档信息 - openAPI.externalDocs(openApiProperties.getExternalDocs()); - openAPI.servers(openApiProperties.getServers()); - openAPI.security(openApiProperties.getSecurity()); - openAPI.tags(openApiProperties.getTags()); - openAPI.paths(openApiProperties.getPaths()); - openAPI.components(openApiProperties.getComponents()); - openAPI.extensions(openApiProperties.getExtensions()); + openAPI.externalDocs(this.openApiProperties.getExternalDocs()); + openAPI.servers(this.openApiProperties.getServers()); + openAPI.security(this.openApiProperties.getSecurity()); + openAPI.tags(this.openApiProperties.getTags()); + openAPI.paths(this.openApiProperties.getPaths()); + openAPI.components(this.openApiProperties.getComponents()); + openAPI.extensions(this.openApiProperties.getExtensions()); return openAPI; } @@ -104,7 +104,7 @@ private Info convertInfo(OpenApiProperties.InfoProperties infoProperties) { @ConditionalOnProperty(prefix = OpenApiProperties.PREFIX + ".cors-config", name = "enabled", havingValue = "true") public FilterRegistrationBean corsFilterRegistrationBean() { // 获取 CORS 配置 - OpenApiProperties.CorsConfig corsConfig = openApiProperties.getCorsConfig(); + OpenApiProperties.CorsConfig corsConfig = this.openApiProperties.getCorsConfig(); // 转换 CORS 配置 CorsConfiguration corsConfiguration = new CorsConfiguration(); @@ -147,17 +147,17 @@ PageParamOpenAPIConverter pageParamAPIConverter(ObjectMapperProvider objectMappe Map map = new HashMap<>(); - String page = pageableProperties.getPageParameterName(); + String page = this.pageableProperties.getPageParameterName(); if (!PageableConstants.DEFAULT_PAGE_PARAMETER.equals(page)) { map.put(PageableConstants.DEFAULT_PAGE_PARAMETER, page); } - String size = pageableProperties.getSizeParameterName(); + String size = this.pageableProperties.getSizeParameterName(); if (!PageableConstants.DEFAULT_SIZE_PARAMETER.equals(size)) { map.put(PageableConstants.DEFAULT_SIZE_PARAMETER, size); } - String sort = pageableProperties.getSortParameterName(); + String sort = this.pageableProperties.getSortParameterName(); if (!PageableConstants.DEFAULT_SORT_PARAMETER.equals(sort)) { map.put(PageableConstants.DEFAULT_SORT_PARAMETER, sort); } diff --git a/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageParamOpenAPIConverter.java b/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageParamOpenAPIConverter.java index e1b7176ec..1c5862030 100644 --- a/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageParamOpenAPIConverter.java +++ b/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageParamOpenAPIConverter.java @@ -66,7 +66,7 @@ public PageParamOpenAPIConverter(ObjectMapperProvider springDocObjectMapper) { */ @Override public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator chain) { - JavaType javaType = springDocObjectMapper.jsonMapper().constructType(type.getType()); + JavaType javaType = this.springDocObjectMapper.jsonMapper().constructType(type.getType()); if (javaType != null) { Class cls = javaType.getRawClass(); if (PAGE_PARAM_TO_REPLACE.equals(cls.getCanonicalName())) { diff --git a/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageableRequestClassCreator.java b/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageableRequestClassCreator.java index 46e655532..6a31a6902 100644 --- a/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageableRequestClassCreator.java +++ b/openapi/ballcat-spring-boot-starter-openapi/src/main/java/org/ballcat/openapi/pageable/PageableRequestClassCreator.java @@ -73,25 +73,25 @@ protected ModifyFieldNameAdapter(int api, ClassVisitor classVisitor, Map listObjects(String prefix) { - return listObjects(ossProperties.getBucket(), prefix); + return listObjects(this.ossProperties.getBucket(), prefix); } /** @@ -169,7 +169,8 @@ public List listObjects(String bucket, String prefix) { */ @Override public List listObjects(String bucket, String prefix, Integer maxKeys) { - return s3Client.listObjects(ListObjectsRequest.builder().maxKeys(maxKeys).prefix(prefix).bucket(bucket).build()) + return this.s3Client + .listObjects(ListObjectsRequest.builder().maxKeys(maxKeys).prefix(prefix).bucket(bucket).build()) .contents(); } @@ -189,7 +190,7 @@ public List listObjects(String bucket, String prefix, Integer maxKeys) @Override public PutObjectResponse putObject(String bucket, String key, File file) throws AwsServiceException, SdkClientException, S3Exception, IOException { - return s3Client.putObject(PutObjectRequest.builder() + return this.s3Client.putObject(PutObjectRequest.builder() .bucket(bucket) .key(key) .contentLength(file.length()) @@ -212,7 +213,7 @@ public PutObjectResponse putObject(String bucket, String key, File file) @Override public PutObjectResponse putObject(String bucket, String key, Path sourcePath) throws AwsServiceException, SdkClientException, S3Exception { - return s3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key).build(), sourcePath); + return this.s3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key).build(), sourcePath); } /** @@ -231,7 +232,7 @@ public PutObjectResponse putObject(String bucket, String key, Path sourcePath) @Override public PutObjectResponse putObject(String bucket, String key, InputStream inputStream, long contentLength) throws AwsServiceException, SdkClientException, S3Exception { - return s3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key).build(), + return this.s3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key).build(), RequestBody.fromInputStream(inputStream, contentLength)); } @@ -247,7 +248,7 @@ public PutObjectResponse putObject(String bucket, String key, InputStream inputS */ @Override public DeleteObjectResponse deleteObject(DeleteObjectRequest deleteObjectRequest) { - return s3Client.deleteObject(deleteObjectRequest); + return this.s3Client.deleteObject(deleteObjectRequest); } /** @@ -262,7 +263,7 @@ public DeleteObjectResponse deleteObject(DeleteObjectRequest deleteObjectRequest */ @Override public DeleteObjectsResponse deleteObjects(DeleteObjectsRequest deleteObjectsRequest) { - return s3Client.deleteObjects(deleteObjectsRequest); + return this.s3Client.deleteObjects(deleteObjectsRequest); } /** @@ -277,7 +278,7 @@ public DeleteObjectsResponse deleteObjects(DeleteObjectsRequest deleteObjectsReq */ @Override public DeleteObjectResponse deleteObject(String key) { - return deleteObject(ossProperties.getBucket(), key); + return deleteObject(this.ossProperties.getBucket(), key); } /** @@ -292,7 +293,7 @@ public DeleteObjectResponse deleteObject(String key) { */ @Override public DeleteObjectsResponse deleteObjects(Set keys) { - return deleteObjects(ossProperties.getBucket(), keys); + return deleteObjects(this.ossProperties.getBucket(), keys); } /** @@ -346,7 +347,7 @@ public DeleteObjectsResponse deleteObjects(String bucket, Set keys) { */ @Override public CopyObjectResponse copyObject(String sourceKey, String destinationKey) { - return copyObject(ossProperties.getBucket(), sourceKey, destinationKey); + return copyObject(this.ossProperties.getBucket(), sourceKey, destinationKey); } /** @@ -379,7 +380,7 @@ public CopyObjectResponse copyObject(String bucket, String sourceKey, String des @Override public CopyObjectResponse copyObject(String sourceBucket, String sourceKey, String destinationBucket, String destinationKey) { - return s3Client.copyObject(CopyObjectRequest.builder() + return this.s3Client.copyObject(CopyObjectRequest.builder() .sourceBucket(sourceBucket) .sourceKey(sourceKey) .destinationBucket(destinationBucket) @@ -416,7 +417,8 @@ public String getObjectPresignedUrl(String bucket, String key, Duration duration .getObjectRequest(getObjectRequest) .build(); - PresignedGetObjectRequest presignedGetObjectRequest = s3Presigner.presignGetObject(getObjectPresignRequest); + PresignedGetObjectRequest presignedGetObjectRequest = this.s3Presigner + .presignGetObject(getObjectPresignRequest); URL url = presignedGetObjectRequest.url(); return url.toString(); } @@ -439,7 +441,8 @@ public String putObjectPresignedUrl(String bucket, String key, Duration duration .putObjectRequest(putObjectRequest) .build(); - PresignedPutObjectRequest presignedGetObjectRequest = s3Presigner.presignPutObject(getObjectPresignRequest); + PresignedPutObjectRequest presignedGetObjectRequest = this.s3Presigner + .presignPutObject(getObjectPresignRequest); URL url = presignedGetObjectRequest.url(); return url.toString(); } diff --git a/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/ObjectWithGlobalKeyPrefixOssTemplate.java b/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/ObjectWithGlobalKeyPrefixOssTemplate.java index a729d44a3..8431d1e96 100644 --- a/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/ObjectWithGlobalKeyPrefixOssTemplate.java +++ b/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/ObjectWithGlobalKeyPrefixOssTemplate.java @@ -77,20 +77,20 @@ public ObjectWithGlobalKeyPrefixOssTemplate(OssProperties ossProperties, S3Clien @Override public List listObjects(String bucket, String prefix, Integer maxKeys) { // 构造API_ListObjects请求 - List contents = s3Client + List contents = this.s3Client .listObjects(ListObjectsRequest.builder() .bucket(bucket) .maxKeys(maxKeys) - .prefix(objectKeyPrefixConverter.wrap(prefix)) + .prefix(this.objectKeyPrefixConverter.wrap(prefix)) .build()) .contents(); - return objectKeyPrefixConverter.match() ? contents.stream() + return this.objectKeyPrefixConverter.match() ? contents.stream() .map(ele -> S3Object.builder() .checksumAlgorithm(ele.checksumAlgorithm()) .checksumAlgorithmWithStrings(ele.checksumAlgorithmAsStrings()) .eTag(ele.eTag()) .lastModified(ele.lastModified()) - .key(objectKeyPrefixConverter.unwrap(ele.key())) + .key(this.objectKeyPrefixConverter.unwrap(ele.key())) .owner(ele.owner()) .size(ele.size()) .storageClass(ele.storageClass()) @@ -114,7 +114,7 @@ public List listObjects(String bucket, String prefix, Integer maxKeys) @Override public PutObjectResponse putObject(String bucket, String key, File file) throws AwsServiceException, SdkClientException, S3Exception, IOException { - return super.putObject(bucket, objectKeyPrefixConverter.wrap(key), file); + return super.putObject(bucket, this.objectKeyPrefixConverter.wrap(key), file); } /** @@ -132,7 +132,7 @@ public PutObjectResponse putObject(String bucket, String key, File file) @Override public PutObjectResponse putObject(String bucket, String key, Path sourcePath) throws AwsServiceException, SdkClientException, S3Exception { - return super.putObject(bucket, objectKeyPrefixConverter.wrap(key), sourcePath); + return super.putObject(bucket, this.objectKeyPrefixConverter.wrap(key), sourcePath); } /** @@ -151,7 +151,7 @@ public PutObjectResponse putObject(String bucket, String key, Path sourcePath) @Override public PutObjectResponse putObject(String bucket, String key, InputStream inputStream, long contentLength) throws AwsServiceException, SdkClientException, S3Exception { - return super.putObject(bucket, objectKeyPrefixConverter.wrap(key), inputStream, contentLength); + return super.putObject(bucket, this.objectKeyPrefixConverter.wrap(key), inputStream, contentLength); } /** @@ -172,7 +172,7 @@ public PutObjectResponse putObject(PutObjectRequest putObjectRequest, RequestBod return super.putObject(PutObjectRequest.builder() .acl(putObjectRequest.acl()) .contentType(putObjectRequest.contentType()) - .key(objectKeyPrefixConverter.wrap(putObjectRequest.key())) + .key(this.objectKeyPrefixConverter.wrap(putObjectRequest.key())) .bucket(putObjectRequest.bucket()) .contentLength(putObjectRequest.contentLength()) .cacheControl(putObjectRequest.cacheControl()) @@ -224,7 +224,7 @@ public PutObjectResponse putObject(PutObjectRequest putObjectRequest, RequestBod */ @Override public DeleteObjectResponse deleteObject(String bucket, String key) { - return super.deleteObject(bucket, objectKeyPrefixConverter.wrap(key)); + return super.deleteObject(bucket, this.objectKeyPrefixConverter.wrap(key)); } /** @@ -241,7 +241,7 @@ public DeleteObjectResponse deleteObject(String bucket, String key) { @Override public DeleteObjectsResponse deleteObjects(String bucket, Set keys) { return super.deleteObjects(bucket, - keys.stream().map(objectKeyPrefixConverter::wrap).collect(Collectors.toSet())); + keys.stream().map(this.objectKeyPrefixConverter::wrap).collect(Collectors.toSet())); } /** @@ -260,7 +260,7 @@ public DeleteObjectResponse deleteObject(DeleteObjectRequest deleteObjectRequest if (StringUtils.hasText(deleteObjectRequest.key())) { return super.deleteObject(DeleteObjectRequest.builder() .bucket(deleteObjectRequest.bucket()) - .key(objectKeyPrefixConverter.wrap(deleteObjectRequest.key())) + .key(this.objectKeyPrefixConverter.wrap(deleteObjectRequest.key())) .bypassGovernanceRetention(deleteObjectRequest.bypassGovernanceRetention()) .expectedBucketOwner(deleteObjectRequest.expectedBucketOwner()) .mfa(deleteObjectRequest.mfa()) @@ -290,7 +290,7 @@ public DeleteObjectsResponse deleteObjects(DeleteObjectsRequest deleteObjectsReq List toDelete = deleteObjectsRequest.delete() .objects() .stream() - .map(e -> ObjectIdentifier.builder().key(objectKeyPrefixConverter.wrap(e.key())).build()) + .map(e -> ObjectIdentifier.builder().key(this.objectKeyPrefixConverter.wrap(e.key())).build()) .collect(Collectors.toList()); return super.deleteObjects(DeleteObjectsRequest.builder() .bucket(deleteObjectsRequest.bucket()) @@ -321,8 +321,8 @@ public DeleteObjectsResponse deleteObjects(DeleteObjectsRequest deleteObjectsReq @Override public CopyObjectResponse copyObject(String bucket, String sourceKey, String destinationBucket, String destinationKey) { - return super.copyObject(bucket, objectKeyPrefixConverter.wrap(sourceKey), destinationBucket, - objectKeyPrefixConverter.wrap(destinationKey)); + return super.copyObject(bucket, this.objectKeyPrefixConverter.wrap(sourceKey), destinationBucket, + this.objectKeyPrefixConverter.wrap(destinationKey)); } /** @@ -333,7 +333,7 @@ public CopyObjectResponse copyObject(String bucket, String sourceKey, String des */ @Override public String getURL(String bucket, String key) { - return super.getURL(bucket, objectKeyPrefixConverter.wrap(key)); + return super.getURL(bucket, this.objectKeyPrefixConverter.wrap(key)); } /** @@ -347,7 +347,7 @@ public String getURL(String bucket, String key) { */ @Override public String getObjectPresignedUrl(String bucket, String key, Duration duration) { - return super.getObjectPresignedUrl(bucket, objectKeyPrefixConverter.wrap(key), duration); + return super.getObjectPresignedUrl(bucket, this.objectKeyPrefixConverter.wrap(key), duration); } /** @@ -361,7 +361,7 @@ public String getObjectPresignedUrl(String bucket, String key, Duration duration */ @Override public String putObjectPresignedUrl(String bucket, String key, Duration duration) { - return super.putObjectPresignedUrl(bucket, objectKeyPrefixConverter.wrap(key), duration); + return super.putObjectPresignedUrl(bucket, this.objectKeyPrefixConverter.wrap(key), duration); } /** @@ -388,7 +388,7 @@ public String putObjectPresignedUrl(String bucket, String key, Duration duration */ @Override public FileUpload uploadFile(String bucket, String key, File file) { - return super.uploadFile(bucket, objectKeyPrefixConverter.wrap(key), file); + return super.uploadFile(bucket, this.objectKeyPrefixConverter.wrap(key), file); } } diff --git a/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/prefix/DefaultObjectKeyPrefixConverter.java b/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/prefix/DefaultObjectKeyPrefixConverter.java index 9fa023535..d4f2211b3 100644 --- a/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/prefix/DefaultObjectKeyPrefixConverter.java +++ b/oss/ballcat-spring-boot-starter-oss/src/main/java/org/ballcat/oss/prefix/DefaultObjectKeyPrefixConverter.java @@ -45,7 +45,7 @@ public class DefaultObjectKeyPrefixConverter implements ObjectKeyPrefixConverter @Override public String getPrefix() { - return properties.getObjectKeyPrefix(); + return this.properties.getObjectKeyPrefix(); } /** @@ -99,7 +99,7 @@ public void afterPropertiesSet() { log.info("全局前缀组织对象功能启用,全局前缀配置路径为:[{}],标准化前缀全局前缀路径为:[{}]", configPrefix, this.globalObjectPrefix); log.info("存在全局前缀时,针对用户操作OSS对象(上传、删除)的部分会自动拼接全局前缀,针对用户读取OSS对象的部分,返回的OSS对象会自动移除全局前缀,但实际存储在OSS的位置也会包含全局路径"); log.info("例如,存在`abc`桶时,全局前缀设置为`d`时,上传OSS对象`e.txt`时,OSS对象会按照`d/e.txt`保存,用户在具有权限时可通过资源`{}/abc/d/e.txt`访问该资源", - properties.getEndpoint()); + this.properties.getEndpoint()); log.info("用户试图查找该资源时,只需要传入`e.txt`,插件会自动发起对`d/e.txt`路径的查询,返回的OSS对象也会去除查询到的对象名称将为`e.txt`"); log.info("用户试图删除该资源时,只需要传入`e.txt`,插件会自动发起对`d/e.txt`路径对象的删除"); } diff --git a/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/AbstractOssTemplateTest.java b/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/AbstractOssTemplateTest.java index 0df5ed890..aed64e62d 100644 --- a/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/AbstractOssTemplateTest.java +++ b/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/AbstractOssTemplateTest.java @@ -35,11 +35,11 @@ public abstract class AbstractOssTemplateTest { protected ObjectKeyPrefixConverter objectKeyPrefixConverter; protected void createBucket(String bucket) { - ossTemplate.createBucket(bucket); + this.ossTemplate.createBucket(bucket); } protected void deleteBucket(String bucket) { - ossTemplate.deleteBucket(bucket); + this.ossTemplate.deleteBucket(bucket); } } diff --git a/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/MinioOssTemplateTest.java b/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/MinioOssTemplateTest.java index 925ca5174..c30a1ac3e 100644 --- a/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/MinioOssTemplateTest.java +++ b/oss/ballcat-spring-boot-starter-oss/src/test/java/org/ballcat/oss/MinioOssTemplateTest.java @@ -64,7 +64,7 @@ class MinioOssTemplateTest extends AbstractOssTemplateTest { @Test void createBucket() { String bucket = UUID.randomUUID().toString(); - CreateBucketResponse bucketResponse = ossTemplate.createBucket(bucket); + CreateBucketResponse bucketResponse = this.ossTemplate.createBucket(bucket); Assertions.assertTrue(bucketResponse.location().endsWith(bucket)); deleteBucket(bucket); } @@ -76,7 +76,7 @@ void createBucket() { void listBuckets() { String bucket = UUID.randomUUID().toString(); createBucket(bucket); - List newBuckets = ossTemplate.listBuckets().buckets(); + List newBuckets = this.ossTemplate.listBuckets().buckets(); List bucketNames = newBuckets.stream().map(Bucket::name).collect(Collectors.toList()); Assertions.assertTrue(bucketNames.contains(bucket)); deleteBucket(bucket); @@ -87,31 +87,31 @@ void listBuckets() { */ @Test void deleteBucket() { - ossTemplate.deleteBucket(TEST_BUCKET_NAME); + this.ossTemplate.deleteBucket(TEST_BUCKET_NAME); } @Test void getObjectPresignedUrl() { - String objectPresignedUrl = ossTemplate.getObjectPresignedUrl(ossTemplate.getOssProperties().getBucket(), - TEST_OBJECT_NAME, Duration.ofDays(1)); + String objectPresignedUrl = this.ossTemplate.getObjectPresignedUrl( + this.ossTemplate.getOssProperties().getBucket(), TEST_OBJECT_NAME, Duration.ofDays(1)); System.out.println(objectPresignedUrl); } @Test void getUrl() { - String url = ossTemplate.getURL(ossTemplate.getOssProperties().getBucket(), TEST_OBJECT_NAME); + String url = this.ossTemplate.getURL(this.ossTemplate.getOssProperties().getBucket(), TEST_OBJECT_NAME); System.out.println(url); } @Test void getUrlWithCustomPrefix() { - URL url = ossTemplate.getS3Client() + URL url = this.ossTemplate.getS3Client() .utilities() .getUrl(GetUrlRequest.builder() - .bucket(ossTemplate.getOssProperties().getBucket()) + .bucket(this.ossTemplate.getOssProperties().getBucket()) .key(TEST_OBJECT_NAME) - .endpoint(URI.create(ossTemplate.getOssProperties().getEndpoint() + "/测试/")) - .region(Region.of(ossTemplate.getOssProperties().getRegion())) + .endpoint(URI.create(this.ossTemplate.getOssProperties().getEndpoint() + "/测试/")) + .region(Region.of(this.ossTemplate.getOssProperties().getRegion())) .build()); System.out.println(url); @@ -123,8 +123,8 @@ void getUrlWithCustomPrefix() { @Test void listObjects() { // 使用上传时自己构建的的对象名字查询 - List s3ObjectsWithUploadKey = ossTemplate.listObjects(ossTemplate.getOssProperties().getBucket(), - TEST_OBJECT_NAME); + List s3ObjectsWithUploadKey = this.ossTemplate + .listObjects(this.ossTemplate.getOssProperties().getBucket(), TEST_OBJECT_NAME); Assertions.assertEquals(1, s3ObjectsWithUploadKey.size()); Assertions.assertEquals(TEST_OBJECT_NAME, s3ObjectsWithUploadKey.get(0).key()); } @@ -134,8 +134,9 @@ void listObjects() { */ @Test void putObject() throws IOException { - PutObjectResponse putObjectResponse = ossTemplate.putObject(ossTemplate.getOssProperties().getBucket(), - TEST_OBJECT_NAME, ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "test.txt")); + PutObjectResponse putObjectResponse = this.ossTemplate.putObject( + this.ossTemplate.getOssProperties().getBucket(), TEST_OBJECT_NAME, + ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "test.txt")); System.out.println(putObjectResponse); } @@ -145,25 +146,25 @@ void upload() throws FileNotFoundException { String bucket = UUID.randomUUID().toString(); String key = UUID.randomUUID().toString(); createBucket(bucket); - FileUpload fileUpload = ossTemplate.uploadFile(key, + FileUpload fileUpload = this.ossTemplate.uploadFile(key, ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "test.txt")); fileUpload.completionFuture().join(); - List s3Objects = ossTemplate.listObjects(key); + List s3Objects = this.ossTemplate.listObjects(key); Assertions.assertEquals(1, s3Objects.size()); S3Object s3Object = s3Objects.get(0); Assertions.assertEquals(key, s3Object.key()); Assertions.assertEquals(13, s3Object.size()); - ossTemplate.deleteObject(key); + this.ossTemplate.deleteObject(key); deleteBucket(bucket); } @Test void testBean() { - if (objectKeyPrefixConverter.match()) { - Assertions.assertInstanceOf(ObjectWithGlobalKeyPrefixOssTemplate.class, ossTemplate); + if (this.objectKeyPrefixConverter.match()) { + Assertions.assertInstanceOf(ObjectWithGlobalKeyPrefixOssTemplate.class, this.ossTemplate); } else { - Assertions.assertInstanceOf(DefaultOssTemplate.class, ossTemplate); + Assertions.assertInstanceOf(DefaultOssTemplate.class, this.ossTemplate); } } diff --git a/pay/ballcat-pay-ali/src/main/java/org/ballcat/pay/ali/AliPay.java b/pay/ballcat-pay-ali/src/main/java/org/ballcat/pay/ali/AliPay.java index 825695e18..df39866fb 100644 --- a/pay/ballcat-pay-ali/src/main/java/org/ballcat/pay/ali/AliPay.java +++ b/pay/ballcat-pay-ali/src/main/java/org/ballcat/pay/ali/AliPay.java @@ -98,7 +98,7 @@ public AliPay(String serverUrl, String appId, String privateKey, String format, */ public AlipayTradeWapPayResponse mobileWapPay(String sn, BigDecimal amount, String subject) throws AlipayApiException { - return mobileWapPay(sn, amount, subject, returnUrl, notifyUrl); + return mobileWapPay(sn, amount, subject, this.returnUrl, this.notifyUrl); } /** @@ -122,7 +122,7 @@ public AlipayTradeWapPayResponse mobileWapPay(String sn, BigDecimal amount, Stri * 手机网站支付-复杂支付 */ public AlipayTradeWapPayResponse mobileWapPay(AlipayTradePayModel model) throws AlipayApiException { - return mobileWapPay(model, returnUrl, notifyUrl); + return mobileWapPay(model, this.returnUrl, this.notifyUrl); } /** @@ -135,7 +135,7 @@ public AlipayTradeWapPayResponse mobileWapPay(AlipayTradePayModel model, String request.setReturnUrl(returnUrl); request.setNotifyUrl(notifyUrl); // 网页支付方式, 将 返回值 .getBody() 内容作为 form 表单进行提交, 会跳转到一个 url, 具体参考文档 - return client.pageExecute(request); + return this.client.pageExecute(request); } /** @@ -147,7 +147,7 @@ public AlipayTradeWapPayResponse mobileWapPay(AlipayTradePayModel model, String */ public AlipayTradePagePayResponse computerWapPay(String sn, BigDecimal amount, String subject) throws AlipayApiException { - return computerWapPay(sn, amount, subject, returnUrl, notifyUrl); + return computerWapPay(sn, amount, subject, this.returnUrl, this.notifyUrl); } /** @@ -172,7 +172,7 @@ public AlipayTradePagePayResponse computerWapPay(String sn, BigDecimal amount, S * 电脑网站支付-复杂支付 */ public AlipayTradePagePayResponse computerWapPay(AlipayTradePayModel model) throws AlipayApiException { - return computerWapPay(model, returnUrl, notifyUrl); + return computerWapPay(model, this.returnUrl, this.notifyUrl); } /** @@ -185,7 +185,7 @@ public AlipayTradePagePayResponse computerWapPay(AlipayTradePayModel model, Stri request.setReturnUrl(returnUrl); request.setNotifyUrl(notifyUrl); // 网页支付方式, 将 返回值 .getBody() 内容作为 form 表单进行提交, 会跳转到一个 url, 具体参考文档 - return client.pageExecute(request); + return this.client.pageExecute(request); } /** @@ -196,7 +196,7 @@ public AlipayTradePagePayResponse computerWapPay(AlipayTradePayModel model, Stri * @return com.alipay.api.response.AlipayTradeWapPayResponse */ public AlipayTradeAppPayResponse appPay(String sn, BigDecimal amount, String subject) throws AlipayApiException { - return appPay(sn, amount, subject, notifyUrl); + return appPay(sn, amount, subject, this.notifyUrl); } /** @@ -220,7 +220,7 @@ public AlipayTradeAppPayResponse appPay(String sn, BigDecimal amount, String sub * APP支付-复杂支付 */ public AlipayTradeAppPayResponse appPay(AlipayTradePayModel model) throws AlipayApiException { - return appPay(model, notifyUrl); + return appPay(model, this.notifyUrl); } /** @@ -230,7 +230,7 @@ public AlipayTradeAppPayResponse appPay(AlipayTradePayModel model, String notify AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); request.setBizModel(model); request.setNotifyUrl(notifyUrl); - return client.sdkExecute(request); + return this.client.sdkExecute(request); } /** @@ -243,7 +243,7 @@ public AlipayTradeAppPayResponse appPay(AlipayTradePayModel model, String notify */ public AlipayTradePayResponse codePay(String sn, BigDecimal amount, String code, String subject) throws AlipayApiException { - return codePay(sn, amount, code, subject, notifyUrl); + return codePay(sn, amount, code, subject, this.notifyUrl); } /** @@ -270,7 +270,7 @@ public AlipayTradePayResponse codePay(String sn, BigDecimal amount, String code, * 付款码支付-复杂支付 */ public AlipayTradePayResponse codePay(AlipayTradePayModel model) throws AlipayApiException { - return codePay(model, notifyUrl); + return codePay(model, this.notifyUrl); } /** @@ -282,7 +282,7 @@ public AlipayTradePayResponse codePay(AlipayTradePayModel model, String notifyUr // 付款码场景固定 model.setScene("bar_code"); request.setNotifyUrl(notifyUrl); - return client.execute(request); + return this.client.execute(request); } /** @@ -293,7 +293,7 @@ public AlipayTradePayResponse codePay(AlipayTradePayModel model, String notifyUr * @return com.alipay.api.response.AlipayTradePrecreateResponse */ public AlipayTradePrecreateResponse qrPay(String sn, BigDecimal amount, String subject) throws AlipayApiException { - return qrPay(sn, amount, subject, notifyUrl); + return qrPay(sn, amount, subject, this.notifyUrl); } /** @@ -317,7 +317,7 @@ public AlipayTradePrecreateResponse qrPay(String sn, BigDecimal amount, String s * 二维码付款-复杂支付 */ public AlipayTradePrecreateResponse qrPay(AlipayTradePrecreateModel model) throws AlipayApiException { - return qrPay(model, notifyUrl); + return qrPay(model, this.notifyUrl); } /** @@ -328,7 +328,7 @@ public AlipayTradePrecreateResponse qrPay(AlipayTradePrecreateModel model, Strin AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); request.setBizModel(model); request.setNotifyUrl(notifyUrl); - return client.execute(request); + return this.client.execute(request); } /** @@ -360,7 +360,7 @@ public AliPayQuery query(String sn, String tradeNo) throws AlipayApiException { public AliPayQuery query(AlipayTradeQueryModel model) throws AlipayApiException { AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); request.setBizModel(model); - return AliPayQuery.of(client.execute(request)); + return AliPayQuery.of(this.client.execute(request)); } /** @@ -395,7 +395,7 @@ public AlipayTradeRefundResponse refund(String sn, String tradeNo, BigDecimal am public AlipayTradeRefundResponse refund(AlipayTradeRefundModel model) throws AlipayApiException { AlipayTradeRefundRequest request = new AlipayTradeRefundRequest(); request.setBizModel(model); - return client.execute(request); + return this.client.execute(request); } /** @@ -407,7 +407,7 @@ public boolean checkSignV1(Map map) throws AlipayApiException { // 验签需要先移除 fund_bill_list 参数值中的 " 否则会导致正确的签名验签失败 map.put(AliPayConstant.FIELD_FUND_BILL_LIST, map.get(AliPayConstant.FIELD_FUND_BILL_LIST).replace(""", "\"")); - return AlipaySignature.rsaCheckV1(map, alipayPublicKey, charset, signType); + return AlipaySignature.rsaCheckV1(map, this.alipayPublicKey, this.charset, this.signType); } /** @@ -419,7 +419,7 @@ public boolean checkSignV2(Map map) throws AlipayApiException { // 验签需要先移除 fund_bill_list 参数值中的 " 否则会导致正确的签名验签失败 map.put(AliPayConstant.FIELD_FUND_BILL_LIST, map.get(AliPayConstant.FIELD_FUND_BILL_LIST).replace(""", "\"")); - return AlipaySignature.rsaCheckV2(map, alipayPublicKey, charset, signType); + return AlipaySignature.rsaCheckV2(map, this.alipayPublicKey, this.charset, this.signType); } } diff --git a/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/WxPay.java b/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/WxPay.java index 8f6adf89b..654469e79 100644 --- a/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/WxPay.java +++ b/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/WxPay.java @@ -87,7 +87,7 @@ public WxPay(String appId, String mchId, String mckKey, boolean sandbox, WxDomai * @param body 商品描述 */ public WxPayResponse jsApiPay(String sn, BigDecimal amount, String ip, String body) { - return jsApiPay(sn, amount, ip, body, notifyUrl); + return jsApiPay(sn, amount, ip, body, this.notifyUrl); } public WxPayResponse jsApiPay(String sn, BigDecimal amount, String ip, String body, String notifyUrl) { @@ -102,7 +102,7 @@ public WxPayResponse jsApiPay(String sn, BigDecimal amount, String ip, String bo * @param body 商品描述 */ public WxPayResponse appPay(String sn, BigDecimal amount, String ip, String body) { - return appPay(sn, amount, ip, body, notifyUrl); + return appPay(sn, amount, ip, body, this.notifyUrl); } public WxPayResponse appPay(String sn, BigDecimal amount, String ip, String body, String notifyUrl) { @@ -116,7 +116,7 @@ public WxPayResponse appPay(String sn, BigDecimal amount, String ip, String body * @param body 商品描述 */ public WxPayResponse nativePay(String sn, BigDecimal amount, String body) { - return nativePay(sn, amount, body, notifyUrl); + return nativePay(sn, amount, body, this.notifyUrl); } public WxPayResponse nativePay(String sn, BigDecimal amount, String body, String notifyUrl) { @@ -131,7 +131,7 @@ public WxPayResponse nativePay(String sn, BigDecimal amount, String body, String * @param body 商品描述 */ public WxPayResponse webPay(String sn, BigDecimal amount, String ip, String body) { - return webPay(sn, amount, ip, body, notifyUrl); + return webPay(sn, amount, ip, body, this.notifyUrl); } public WxPayResponse webPay(String sn, BigDecimal amount, String ip, String body, String notifyUrl) { @@ -186,15 +186,15 @@ public Map request(Map params, RequestSuffix rs) map.putAll(params); // 添加必须参数 - map.put("appid", appId); - map.put("mch_id", mchId); + map.put("appid", this.appId); + map.put("mch_id", this.mchId); map.put("nonce_str", WxPayUtil.generateNonceStr()); // 设置签名类型; 沙箱使用 md5, 正式使用 hmac sha256 - map.put(WxPayConstant.FIELD_SIGN_TYPE, sandbox ? SignType.MD5.getStr() : SignType.HMAC_SHA256.getStr()); + map.put(WxPayConstant.FIELD_SIGN_TYPE, this.sandbox ? SignType.MD5.getStr() : SignType.HMAC_SHA256.getStr()); // 签名 - map.put(WxPayConstant.FIELD_SIGN, WxPayUtil.sign(map, mckKey)); + map.put(WxPayConstant.FIELD_SIGN, WxPayUtil.sign(map, this.mckKey)); - return domain.request(map, rs); + return this.domain.request(map, rs); } /** @@ -222,15 +222,15 @@ public boolean checkSign(WxPayCallback callback) { // 存在签名类型, 直接验签 if (params.containsKey(WxPayConstant.FIELD_SIGN_TYPE)) { - return WxPayUtil.sign(params, mckKey).equals(sign); + return WxPayUtil.sign(params, this.mckKey).equals(sign); } // 两种签名类型都试一次 - if (WxPayUtil.sign(params, SignType.HMAC_SHA256, mckKey).equals(sign)) { + if (WxPayUtil.sign(params, SignType.HMAC_SHA256, this.mckKey).equals(sign)) { return true; } - return WxPayUtil.sign(params, SignType.MD5, mckKey).equals(sign); + return WxPayUtil.sign(params, SignType.MD5, this.mckKey).equals(sign); } } diff --git a/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/domain/DefaultWxDomain.java b/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/domain/DefaultWxDomain.java index 637ccacc2..f881103c9 100644 --- a/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/domain/DefaultWxDomain.java +++ b/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/domain/DefaultWxDomain.java @@ -72,7 +72,7 @@ public String sendRequest(Map params, RequestSuffix rs) { final String url = getUrl(rs.getSuffix()); RequestBody requestBody = RequestBody.create(WxPayUtil.mapToXml(params), MediaType.parse("text/xml")); Request request = new Request.Builder().url(url).post(requestBody).build(); - Call call = client.newCall(request); + Call call = this.client.newCall(request); try (Response response = call.execute()) { ResponseBody responseBody = response.body(); if (responseBody == null) { @@ -95,7 +95,7 @@ public String getUrl(String suffix) { suffix = suffix.substring(1); } - if (sandbox) { + if (this.sandbox) { return getDomain() + "sandboxnew/pay/" + suffix; } return getDomain() + "pay/" + suffix; diff --git a/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/response/WxPayOrderQueryResponse.java b/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/response/WxPayOrderQueryResponse.java index 25f7dbae1..5af3323f2 100644 --- a/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/response/WxPayOrderQueryResponse.java +++ b/pay/ballcat-pay-wx/src/main/java/org/ballcat/pay/wx/response/WxPayOrderQueryResponse.java @@ -114,8 +114,8 @@ public static WxPayOrderQueryResponse of(Map res) { */ public boolean isSuccess() { // 交易成功 - return returnCode == ResponseCode.SUCCESS && resultCode == ResponseCode.SUCCESS - && tradeState == TradeState.SUCCESS; + return this.returnCode == ResponseCode.SUCCESS && this.resultCode == ResponseCode.SUCCESS + && this.tradeState == TradeState.SUCCESS; } } diff --git a/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/AbstractRedisModuleHelper.java b/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/AbstractRedisModuleHelper.java index 2b1ba113d..c14dad51b 100644 --- a/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/AbstractRedisModuleHelper.java +++ b/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/AbstractRedisModuleHelper.java @@ -69,13 +69,14 @@ protected Optional execute(String key, ProtocolKeyword type, CommandOutpu List extraArgs = Arrays.stream(args) .filter(StringUtils::hasLength) - .map(arg -> valueSerializer.serialize(arg)) + .map(arg -> this.valueSerializer.serialize(arg)) .collect(Collectors.toList()); - CommandArgs commandArgs = new CommandArgs<>(codec).addKey(keySerializer.serialize(key)) + CommandArgs commandArgs = new CommandArgs<>(this.codec) + .addKey(this.keySerializer.serialize(key)) .addValues(extraArgs); - try (LettuceConnection connection = (LettuceConnection) connectionFactory.getConnection()) { + try (LettuceConnection connection = (LettuceConnection) this.connectionFactory.getConnection()) { RedisFuture future = connection.getNativeConnection().dispatch(type, output, commandArgs); return Optional.ofNullable(future.get()); } diff --git a/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomInsertOptions.java b/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomInsertOptions.java index 1243fd6ad..72a0ef066 100644 --- a/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomInsertOptions.java +++ b/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomInsertOptions.java @@ -44,8 +44,8 @@ public BloomInsertOptions(long capacity, double errorRate) { * @return InsertOptions */ public BloomInsertOptions capacity(final long capacity) { - options.add(BloomInsertKeywordEnum.CAPACITY.name()); - options.add(String.valueOf(capacity)); + this.options.add(BloomInsertKeywordEnum.CAPACITY.name()); + this.options.add(String.valueOf(capacity)); return this; } @@ -56,8 +56,8 @@ public BloomInsertOptions capacity(final long capacity) { * @return InsertOptions */ public BloomInsertOptions error(final double errorRate) { - options.add(BloomInsertKeywordEnum.ERROR.name()); - options.add(String.valueOf(errorRate)); + this.options.add(BloomInsertKeywordEnum.ERROR.name()); + this.options.add(String.valueOf(errorRate)); return this; } @@ -68,12 +68,12 @@ public BloomInsertOptions error(final double errorRate) { * @return InsertOptions */ public BloomInsertOptions nocreate() { - options.add(BloomInsertKeywordEnum.NOCREATE.name()); + this.options.add(BloomInsertKeywordEnum.NOCREATE.name()); return this; } public Collection getOptions() { - return Collections.unmodifiableCollection(options); + return Collections.unmodifiableCollection(this.options); } } diff --git a/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomRedisModuleHelper.java b/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomRedisModuleHelper.java index 951c7c129..3523cbeca 100644 --- a/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomRedisModuleHelper.java +++ b/redis/ballcat-redis-module/src/main/java/org/ballcat/redis/moudle/bloom/BloomRedisModuleHelper.java @@ -62,7 +62,7 @@ private List getAllFalseBooleanList(long size) { * @return 成功返回 true,失败返回 false */ public boolean createFilter(String key, double errorRate, long initCapacity) { - return execute(key, BloomCommandEnum.RESERVE, new BooleanOutput<>(codec), String.valueOf(errorRate), + return execute(key, BloomCommandEnum.RESERVE, new BooleanOutput<>(this.codec), String.valueOf(errorRate), String.valueOf(initCapacity)) .orElse(false); } @@ -74,7 +74,7 @@ public boolean createFilter(String key, double errorRate, long initCapacity) { * @return 如果元素不在过滤器中,则可以添加成功,返回 true */ public boolean add(String key, String item) { - return execute(key, BloomCommandEnum.ADD, new BooleanOutput<>(codec), item).orElse(false); + return execute(key, BloomCommandEnum.ADD, new BooleanOutput<>(this.codec), item).orElse(false); } /** @@ -84,7 +84,8 @@ public boolean add(String key, String item) { * @return 一个长度与值的个数相同的布尔集合。 每个布尔值指示相应的元素之前是否在过滤器中。 一个真值意味着该元素以前不存在,而一个假值意味着它以前可能存在。 */ public List multiAdd(String key, String... items) { - Optional> result = execute(key, BloomCommandEnum.MADD, new BooleanListOutput<>(codec), items); + Optional> result = execute(key, BloomCommandEnum.MADD, new BooleanListOutput<>(this.codec), + items); return result.orElseGet(() -> getAllFalseBooleanList(items.length)); } @@ -95,7 +96,7 @@ public List multiAdd(String key, String... items) { * @return 如果该项目在筛选器中存在,则为 true; 如果该项目在筛选器中不存在,则为false */ public boolean exists(String key, String item) { - return execute(key, BloomCommandEnum.EXISTS, new BooleanOutput<>(codec), item).orElse(false); + return execute(key, BloomCommandEnum.EXISTS, new BooleanOutput<>(this.codec), item).orElse(false); } /** @@ -105,7 +106,8 @@ public boolean exists(String key, String item) { * @return 一个布尔集合。 true表示对应的值可能存在,false表示不存在 */ public List multiExists(String key, String... items) { - Optional> result = execute(key, BloomCommandEnum.MEXISTS, new BooleanListOutput<>(codec), items); + Optional> result = execute(key, BloomCommandEnum.MEXISTS, new BooleanListOutput<>(this.codec), + items); return result.orElseGet(() -> getAllFalseBooleanList(items.length)); } @@ -133,7 +135,7 @@ public List insert(String key, BloomInsertOptions bloomInsertOptions, S args.add(BloomInsertKeywordEnum.ITEMS.name()); Collections.addAll(args, items); - Optional> result = execute(key, BloomCommandEnum.INSERT, new BooleanListOutput<>(codec), + Optional> result = execute(key, BloomCommandEnum.INSERT, new BooleanListOutput<>(this.codec), args.toArray(new String[0])); return result.orElseGet(() -> getAllFalseBooleanList(items.length)); } @@ -144,7 +146,7 @@ public List insert(String key, BloomInsertOptions bloomInsertOptions, S * @return Return information */ public Map info(String key) { - Optional> result = execute(key, BloomCommandEnum.INFO, new ArrayOutput<>(codec)); + Optional> result = execute(key, BloomCommandEnum.INFO, new ArrayOutput<>(this.codec)); List values = result.orElseGet(ArrayList::new); Map infoMap = new HashMap<>(values.size() / 2); @@ -166,7 +168,7 @@ public Map info(String key) { * @return 删除成功返回 true */ public boolean delete(String key) { - return execute(key, CommandType.DEL, new BooleanOutput<>(codec)).orElse(false); + return execute(key, CommandType.DEL, new BooleanOutput<>(this.codec)).orElse(false); } } diff --git a/redis/ballcat-redis-module/src/main/java/org/springframework/data/redis/connection/lettuce/BloomCommandEnum.java b/redis/ballcat-redis-module/src/main/java/org/springframework/data/redis/connection/lettuce/BloomCommandEnum.java index 005bd7610..5a3507a8b 100644 --- a/redis/ballcat-redis-module/src/main/java/org/springframework/data/redis/connection/lettuce/BloomCommandEnum.java +++ b/redis/ballcat-redis-module/src/main/java/org/springframework/data/redis/connection/lettuce/BloomCommandEnum.java @@ -65,7 +65,7 @@ public enum BloomCommandEnum implements ProtocolKeyword { BloomCommandEnum(String command) { this.command = command; - bytes = command().getBytes(StandardCharsets.US_ASCII); + this.bytes = command().getBytes(StandardCharsets.US_ASCII); } public String command() { @@ -74,7 +74,7 @@ public String command() { @Override public byte[] getBytes() { - return bytes; + return this.bytes; } } diff --git a/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/BloomRedisModuleHelperConfig.java b/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/BloomRedisModuleHelperConfig.java index a46862bc7..4749c72c5 100644 --- a/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/BloomRedisModuleHelperConfig.java +++ b/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/BloomRedisModuleHelperConfig.java @@ -34,7 +34,7 @@ public class BloomRedisModuleHelperConfig { @Bean @DependsOn("cachePropertiesHolder") // 防止 CachePropertiesHolder 初始化落后导致的空指针 public BloomRedisModuleHelper bloomRedisModuleHelper(IRedisPrefixConverter redisPrefixConverter) { - BloomRedisModuleHelper bloomRedisModuleHelper = new BloomRedisModuleHelper(lettuceConnectionFactory); + BloomRedisModuleHelper bloomRedisModuleHelper = new BloomRedisModuleHelper(this.lettuceConnectionFactory); // 可选操作,配合 ballcat-spring-boot-starter-redis 的 key 前缀使用 bloomRedisModuleHelper.setKeySerializer(new PrefixStringRedisSerializer(redisPrefixConverter)); return bloomRedisModuleHelper; diff --git a/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/RedisBloomDemoApplicationTests.java b/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/RedisBloomDemoApplicationTests.java index dfffa3e81..3ac102045 100644 --- a/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/RedisBloomDemoApplicationTests.java +++ b/redis/ballcat-redis-module/src/test/java/org/ballcat/redis/module/RedisBloomDemoApplicationTests.java @@ -47,11 +47,11 @@ public void init() { LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisHost, redisPort); lettuceConnectionFactory.afterPropertiesSet(); // 获取布隆过滤器操作助手 - bloomRedisModuleHelper = new BloomRedisModuleHelper(lettuceConnectionFactory); + this.bloomRedisModuleHelper = new BloomRedisModuleHelper(lettuceConnectionFactory); // 可选操作:配合 ballcat-spring-boot-starter-redis 提供的 PrefixStringRedisSerializer,可以给 // redis key 添加默认的 key 前缀 IRedisPrefixConverter redisPrefixConverter = new DefaultRedisPrefixConverter("keyprefix:"); - bloomRedisModuleHelper.setKeySerializer(new PrefixStringRedisSerializer(redisPrefixConverter)); + this.bloomRedisModuleHelper.setKeySerializer(new PrefixStringRedisSerializer(redisPrefixConverter)); } @Test @@ -59,34 +59,34 @@ void commandTest() { String filterKey = "TEST_FILTER"; // 1.创建布隆过滤器 - boolean create = bloomRedisModuleHelper.createFilter(filterKey, 0.01, 1000000000); + boolean create = this.bloomRedisModuleHelper.createFilter(filterKey, 0.01, 1000000000); log.info("test createFilter result: {}", create); // 2.添加一个元素 - Boolean foo = bloomRedisModuleHelper.add(filterKey, "foo"); + Boolean foo = this.bloomRedisModuleHelper.add(filterKey, "foo"); log.info("test add result: {}", foo); // 3.批量添加元素 - List addMulti = bloomRedisModuleHelper.multiAdd(filterKey, "foo", "bar"); + List addMulti = this.bloomRedisModuleHelper.multiAdd(filterKey, "foo", "bar"); log.info("test addMulti result: {}", addMulti); // 4.校验一个元素是否存在 - Boolean existsFoo = bloomRedisModuleHelper.exists(filterKey, "foo"); + Boolean existsFoo = this.bloomRedisModuleHelper.exists(filterKey, "foo"); log.info("test existsFoo result: {}", existsFoo); - Boolean existsBar = bloomRedisModuleHelper.exists(filterKey, "bar"); + Boolean existsBar = this.bloomRedisModuleHelper.exists(filterKey, "bar"); log.info("test existsBar result: {}", existsBar); // 5.批量校验元素是否存在 - List existsMulti = bloomRedisModuleHelper.multiExists(filterKey, "foo", "foo1"); + List existsMulti = this.bloomRedisModuleHelper.multiExists(filterKey, "foo", "foo1"); log.info("test existsMulti result: {}", existsMulti); // 6.获取 filter info - Map info = bloomRedisModuleHelper.info(filterKey); + Map info = this.bloomRedisModuleHelper.info(filterKey); log.info("test info result: {}", info); // 7.删除布隆过滤器 - Boolean delete = bloomRedisModuleHelper.delete(filterKey); + Boolean delete = this.bloomRedisModuleHelper.delete(filterKey); log.info("test delete result: {}", delete); } @@ -97,27 +97,27 @@ void insertTest() { BloomInsertOptions insertOptions = new BloomInsertOptions().capacity(1000).error(0.001); // 2. 判断元素是否存在 - List existsMulti1 = bloomRedisModuleHelper.multiExists(filterKey, "foo", "foo3", "foo5"); + List existsMulti1 = this.bloomRedisModuleHelper.multiExists(filterKey, "foo", "foo3", "foo5"); log.info("test existsMulti1 result: {}", existsMulti1); // 3. 插入部分数据 - List insert1 = bloomRedisModuleHelper.insert(filterKey, insertOptions, "foo1", "foo2", "foo3"); + List insert1 = this.bloomRedisModuleHelper.insert(filterKey, insertOptions, "foo1", "foo2", "foo3"); log.info("test insert1 result: {}", insert1); // 4. 再次执行 insert 进行插入 - List insert2 = bloomRedisModuleHelper.insert(filterKey, insertOptions, "foo2", "foo3", "foo4"); + List insert2 = this.bloomRedisModuleHelper.insert(filterKey, insertOptions, "foo2", "foo3", "foo4"); log.info("test insert2 result: {}", insert2); // 5. 再次判断元素是否存在 - List existsMulti2 = bloomRedisModuleHelper.multiExists(filterKey, "foo", "foo3", "foo4", "foo5"); + List existsMulti2 = this.bloomRedisModuleHelper.multiExists(filterKey, "foo", "foo3", "foo4", "foo5"); log.info("test existsMulti2 result: {}", existsMulti2); // 6.获取 filter info - Map info = bloomRedisModuleHelper.info(filterKey); + Map info = this.bloomRedisModuleHelper.info(filterKey); log.info("test info result: {}", info); // 7.删除布隆过滤器 - Boolean delete = bloomRedisModuleHelper.delete(filterKey); + Boolean delete = this.bloomRedisModuleHelper.delete(filterKey); log.info("test delete result: {}", delete); } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/CacheStringAspect.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/CacheStringAspect.java index 3ecb6f8be..ec72f5853 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/CacheStringAspect.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/CacheStringAspect.java @@ -83,8 +83,8 @@ public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); - if (log.isTraceEnabled()) { - log.trace("=======The string cache aop is executed! method : {}", method.getName()); + if (this.log.isTraceEnabled()) { + this.log.trace("=======The string cache aop is executed! method : {}", method.getName()); } // 根据方法的参数 以及当前类对象获得 keyGenerator @@ -92,7 +92,7 @@ public Object around(ProceedingJoinPoint point) throws Throwable { Object[] arguments = point.getArgs(); KeyGenerator keyGenerator = new KeyGenerator(target, method, arguments); - ValueOperations valueOperations = redisTemplate.opsForValue(); + ValueOperations valueOperations = this.redisTemplate.opsForValue(); // 缓存处理 Cached cachedAnnotation = AnnotationUtils.getAnnotation(method, Cached.class); @@ -176,7 +176,7 @@ public Object cached(CachedOps ops) throws Throwable { return null; } else if (cacheData != null) { - return cacheSerializer.deserialize(cacheData, dataClazz); + return this.cacheSerializer.deserialize(cacheData, dataClazz); } // 2.==========如果缓存为空 则需查询数据库并更新=============== @@ -186,7 +186,8 @@ else if (cacheData != null) { // 从数据库查询数据 Object dbValue = ops.joinPoint().proceed(); // 如果数据库中没数据,填充一个String,防止缓存击穿 - cacheValue = dbValue == null ? CachePropertiesHolder.nullValue() : cacheSerializer.serialize(dbValue); + cacheValue = dbValue == null ? CachePropertiesHolder.nullValue() + : this.cacheSerializer.serialize(dbValue); // 设置缓存 ops.cachePut().accept(cacheValue); } @@ -196,7 +197,7 @@ else if (cacheData != null) { if (cacheData == null || ops.nullValue(cacheData)) { return null; } - return cacheSerializer.deserialize(cacheData, dataClazz); + return this.cacheSerializer.deserialize(cacheData, dataClazz); } /** @@ -208,7 +209,7 @@ private Object cachePut(CachePutOps ops) throws Throwable { Object data = ops.joinPoint().proceed(); // 将返回值放置入缓存中 - String cacheData = data == null ? CachePropertiesHolder.nullValue() : cacheSerializer.serialize(data); + String cacheData = data == null ? CachePropertiesHolder.nullValue() : this.cacheSerializer.serialize(data); ops.cachePut().accept(cacheData); return data; @@ -254,7 +255,7 @@ private VoidMethod buildCacheDelExecution(CacheDel cacheDelAnnotation, KeyGenera cacheDel = () -> { Cursor scan = RedisHelper.scan(cacheDelAnnotation.key().concat("*")); while (scan.hasNext()) { - redisTemplate.delete(scan.next()); + this.redisTemplate.delete(scan.next()); } if (!scan.isClosed()) { scan.close(); @@ -264,12 +265,12 @@ private VoidMethod buildCacheDelExecution(CacheDel cacheDelAnnotation, KeyGenera else { if (cacheDelAnnotation.multiDel()) { Collection keys = keyGenerator.getKeys(cacheDelAnnotation.key(), cacheDelAnnotation.keyJoint()); - cacheDel = () -> redisTemplate.delete(keys); + cacheDel = () -> this.redisTemplate.delete(keys); } else { // 缓存key String key = keyGenerator.getKey(cacheDelAnnotation.key(), cacheDelAnnotation.keyJoint()); - cacheDel = () -> redisTemplate.delete(key); + cacheDel = () -> this.redisTemplate.delete(key); } } return cacheDel; diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/KeyGenerator.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/KeyGenerator.java index 9dcbc1cb9..407608b50 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/KeyGenerator.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/core/KeyGenerator.java @@ -55,7 +55,7 @@ public String getKey(String keyPrefix, String keyJoint) { return keyPrefix; } // 获取所有需要拼接的元素, 组装进集合中 - String joint = SpelUtils.parseValueToString(spelContext, keyJoint); + String joint = SpelUtils.parseValueToString(this.spelContext, keyJoint); Assert.notNull(joint, "Key joint cannot be null!"); if (!StringUtils.hasText(keyPrefix)) { @@ -70,7 +70,7 @@ public List getKeys(String keyPrefix, String keyJoint) { Assert.hasText(keyJoint, "[getKeys] keyJoint cannot be null"); // 获取所有需要拼接的元素, 组装进集合中 - List joints = SpelUtils.parseValueToStringList(spelContext, keyJoint); + List joints = SpelUtils.parseValueToStringList(this.spelContext, keyJoint); Assert.notEmpty(joints, "[getKeys] keyJoint must be resolved to a non-empty collection!"); if (!StringUtils.hasText(keyPrefix)) { diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/AbstractKeySpaceEventMessageListener.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/AbstractKeySpaceEventMessageListener.java index e65bbfbfc..f7d20700f 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/AbstractKeySpaceEventMessageListener.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/AbstractKeySpaceEventMessageListener.java @@ -72,7 +72,7 @@ protected void doHandleMessage(@NonNull Message message) { * @param event can be {@literal null}. */ protected void publishEvent(RedisKeyExpiredEvent event) { - if (publisher != null) { + if (this.publisher != null) { this.publisher.publishEvent(event); } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultDeletedKeyEventMessageListener.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultDeletedKeyEventMessageListener.java index b43b24e31..f01920418 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultDeletedKeyEventMessageListener.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultDeletedKeyEventMessageListener.java @@ -53,13 +53,13 @@ public DefaultDeletedKeyEventMessageListener(RedisMessageListenerContainer liste @Override public void onMessage(Message message, byte[] pattern) { - if (CollectionUtils.isEmpty(keyDeletedEventMessageTemplates)) { + if (CollectionUtils.isEmpty(this.keyDeletedEventMessageTemplates)) { return; } super.onMessage(message, pattern); String setKey = message.toString(); // 监听key信息新增/修改事件 - for (KeyDeletedEventMessageTemplate keyDeletedEventMessageTemplate : keyDeletedEventMessageTemplates) { + for (KeyDeletedEventMessageTemplate keyDeletedEventMessageTemplate : this.keyDeletedEventMessageTemplates) { if (keyDeletedEventMessageTemplate.support(setKey)) { if (log.isTraceEnabled()) { log.trace("use template [{}] handle key deleted event,the deleted key is [{}]", diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultExpiredKeyEventMessageListener.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultExpiredKeyEventMessageListener.java index 9c5f0704a..02f212ea3 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultExpiredKeyEventMessageListener.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultExpiredKeyEventMessageListener.java @@ -53,13 +53,13 @@ public DefaultExpiredKeyEventMessageListener(RedisMessageListenerContainer liste @Override public void onMessage(Message message, byte[] pattern) { - if (CollectionUtils.isEmpty(keyExpiredEventMessageTemplates)) { + if (CollectionUtils.isEmpty(this.keyExpiredEventMessageTemplates)) { return; } super.onMessage(message, pattern); String expiredKey = message.toString(); // listening key expired event - for (KeyExpiredEventMessageTemplate keyExpiredEventMessageTemplate : keyExpiredEventMessageTemplates) { + for (KeyExpiredEventMessageTemplate keyExpiredEventMessageTemplate : this.keyExpiredEventMessageTemplates) { if (keyExpiredEventMessageTemplate.support(expiredKey)) { if (log.isTraceEnabled()) { log.trace("use template[{}]handle key expired event,the expired key is [{}]", diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultSetKeyEventMessageListener.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultSetKeyEventMessageListener.java index cc121668b..61b5f6cfe 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultSetKeyEventMessageListener.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/keyevent/listener/DefaultSetKeyEventMessageListener.java @@ -53,13 +53,13 @@ public DefaultSetKeyEventMessageListener(RedisMessageListenerContainer listenerC @Override public void onMessage(Message message, byte[] pattern) { - if (CollectionUtils.isEmpty(keySetEventMessageTemplates)) { + if (CollectionUtils.isEmpty(this.keySetEventMessageTemplates)) { return; } super.onMessage(message, pattern); String setKey = message.toString(); // 监听key信息新增/修改事件 - for (KeySetEventMessageTemplate keySetEventMessageTemplate : keySetEventMessageTemplates) { + for (KeySetEventMessageTemplate keySetEventMessageTemplate : this.keySetEventMessageTemplates) { if (keySetEventMessageTemplate.support(setKey)) { if (log.isTraceEnabled()) { log.trace("use template[{}]handle key set event,the set key is[{}]", diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/listener/AbstractMessageEventListener.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/listener/AbstractMessageEventListener.java index 0bd8985cb..e02ff9ce6 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/listener/AbstractMessageEventListener.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/listener/AbstractMessageEventListener.java @@ -41,19 +41,19 @@ public abstract class AbstractMessageEventListener implements MessageEventLis protected AbstractMessageEventListener() { Type superClass = getClass().getGenericSuperclass(); ParameterizedType type = (ParameterizedType) superClass; - clz = (Class) type.getActualTypeArguments()[0]; + this.clz = (Class) type.getActualTypeArguments()[0]; } @Override public void onMessage(Message message, byte[] pattern) { byte[] channelBytes = message.getChannel(); - RedisSerializer stringSerializer = stringRedisTemplate.getStringSerializer(); + RedisSerializer stringSerializer = this.stringRedisTemplate.getStringSerializer(); String channelTopic = stringSerializer.deserialize(channelBytes); String topic = topic().getTopic(); if (topic.equals(channelTopic)) { byte[] bodyBytes = message.getBody(); String body = stringSerializer.deserialize(bodyBytes); - T decodeMessage = JsonUtils.toObj(body, clz); + T decodeMessage = JsonUtils.toObj(body, this.clz); handleMessage(decodeMessage); } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/lock/DistributedLock.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/lock/DistributedLock.java index f0bdeaa71..ae6045992 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/lock/DistributedLock.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/lock/DistributedLock.java @@ -103,7 +103,7 @@ public T lock() { boolean exResolved = false; T value = null; try { - value = executeAction.execute(); + value = this.executeAction.execute(); this.result = value; } catch (Throwable e) { @@ -117,8 +117,8 @@ public T lock() { this.result = this.successAction.apply(value); } } - else if (lockFailAction != null) { - this.result = lockFailAction.get(); + else if (this.lockFailAction != null) { + this.result = this.lockFailAction.get(); } return this.result; @@ -172,8 +172,8 @@ static class Fibonacci { public long next() { long next = this.current + this.prev; - if (first) { - first = false; + if (this.first) { + this.first = false; } else { this.prev = this.current; diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/AbstractCacheOps.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/AbstractCacheOps.java index 56a086e0b..771590895 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/AbstractCacheOps.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/AbstractCacheOps.java @@ -35,7 +35,7 @@ protected AbstractCacheOps(ProceedingJoinPoint joinPoint) { * @return ProceedingJoinPoint */ public ProceedingJoinPoint joinPoint() { - return joinPoint; + return this.joinPoint; } /** diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelOps.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelOps.java index 1d5d67baf..7a0ab149b 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelOps.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelOps.java @@ -35,7 +35,7 @@ public CacheDelOps(ProceedingJoinPoint joinPoint, VoidMethod cacheDel) { } public VoidMethod cacheDel() { - return cacheDel; + return this.cacheDel; } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelsOps.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelsOps.java index 08062743f..cf542b29a 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelsOps.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CacheDelsOps.java @@ -35,7 +35,7 @@ public CacheDelsOps(ProceedingJoinPoint joinPoint, VoidMethod[] cacheDels) { } public VoidMethod[] cacheDel() { - return cacheDels; + return this.cacheDels; } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachePutOps.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachePutOps.java index 495e062b1..36a50d798 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachePutOps.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachePutOps.java @@ -36,7 +36,7 @@ public CachePutOps(ProceedingJoinPoint joinPoint, Consumer cachePut) { } public Consumer cachePut() { - return cachePut; + return this.cachePut; } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachedOps.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachedOps.java index b2ff9671a..c344e5b5d 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachedOps.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/operation/CachedOps.java @@ -72,23 +72,23 @@ public CachedOps(ProceedingJoinPoint joinPoint, String lockKey, Supplier } public Supplier cacheQuery() { - return cacheQuery; + return this.cacheQuery; } public Consumer cachePut() { - return cachePut; + return this.cachePut; } public Type returnType() { - return returnType; + return this.returnType; } public String lockKey() { - return lockKey; + return this.lockKey; } public int retryCount() { - return retryCount; + return this.retryCount; } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/IRedisPrefixConverter.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/IRedisPrefixConverter.java index 39d340fa1..745be60df 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/IRedisPrefixConverter.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/IRedisPrefixConverter.java @@ -49,8 +49,7 @@ public interface IRedisPrefixConverter { * @return 原始key */ default byte[] unwrap(byte[] bytes) { - int wrapLen; - if (!match() || bytes == null || (wrapLen = bytes.length) == 0) { + if (!match() || bytes == null || bytes.length == 0) { return bytes; } String prefix = getPrefix(); @@ -60,6 +59,7 @@ default byte[] unwrap(byte[] bytes) { } byte[] prefixBytes = prefix.getBytes(StandardCharsets.UTF_8); int prefixLen = prefixBytes.length; + int wrapLen = bytes.length; int originLen = wrapLen - prefixLen; byte[] originBytes = new byte[originLen]; System.arraycopy(bytes, prefixLen, originBytes, 0, originLen); @@ -72,8 +72,7 @@ default byte[] unwrap(byte[] bytes) { * @return 加前缀之后的key */ default byte[] wrap(byte[] bytes) { - int originLen; - if (!match() || bytes == null || (originLen = bytes.length) == 0) { + if (!match() || bytes == null || bytes.length == 0) { return bytes; } String prefix = getPrefix(); @@ -83,6 +82,7 @@ default byte[] wrap(byte[] bytes) { } byte[] prefixBytes = prefix.getBytes(StandardCharsets.UTF_8); int prefixLen = prefixBytes.length; + int originLen = bytes.length; byte[] wrapBytes = new byte[prefixLen + originLen]; System.arraycopy(prefixBytes, 0, wrapBytes, 0, prefixLen); System.arraycopy(bytes, 0, wrapBytes, prefixLen, originLen); diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/impl/DefaultRedisPrefixConverter.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/impl/DefaultRedisPrefixConverter.java index 1df6c78a1..f4f612e39 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/impl/DefaultRedisPrefixConverter.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/prefix/impl/DefaultRedisPrefixConverter.java @@ -33,7 +33,7 @@ public DefaultRedisPrefixConverter(String prefix) { @Override public String getPrefix() { - return prefix; + return this.prefix; } @Override diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/JacksonSerializer.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/JacksonSerializer.java index 9e270b8f0..1ff35f938 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/JacksonSerializer.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/JacksonSerializer.java @@ -39,7 +39,7 @@ public class JacksonSerializer implements CacheSerializer { */ @Override public Object deserialize(String cacheData, Type type) throws IOException { - return objectMapper.readValue(cacheData, CacheSerializer.getJavaType(type)); + return this.objectMapper.readValue(cacheData, CacheSerializer.getJavaType(type)); } /** @@ -50,7 +50,7 @@ public Object deserialize(String cacheData, Type type) throws IOException { */ @Override public String serialize(Object cacheData) throws IOException { - return objectMapper.writeValueAsString(cacheData); + return this.objectMapper.writeValueAsString(cacheData); } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixJdkRedisSerializer.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixJdkRedisSerializer.java index 42e1e079d..4636d056e 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixJdkRedisSerializer.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixJdkRedisSerializer.java @@ -36,14 +36,14 @@ public PrefixJdkRedisSerializer(IRedisPrefixConverter redisPrefixConverter) { @Override public Object deserialize(byte[] bytes) { - byte[] unwrap = redisPrefixConverter.unwrap(bytes); + byte[] unwrap = this.redisPrefixConverter.unwrap(bytes); return super.deserialize(unwrap); } @Override public byte[] serialize(Object object) { byte[] originBytes = super.serialize(object); - return redisPrefixConverter.wrap(originBytes); + return this.redisPrefixConverter.wrap(originBytes); } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixStringRedisSerializer.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixStringRedisSerializer.java index 4b7737b70..8dab9ff0b 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixStringRedisSerializer.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/serialize/PrefixStringRedisSerializer.java @@ -39,14 +39,14 @@ public PrefixStringRedisSerializer(IRedisPrefixConverter iRedisPrefixConverter) @Override public String deserialize(byte[] bytes) { - byte[] unwrap = iRedisPrefixConverter.unwrap(bytes); + byte[] unwrap = this.iRedisPrefixConverter.unwrap(bytes); return super.deserialize(unwrap); } @Override public byte[] serialize(String key) { byte[] originBytes = super.serialize(key); - return iRedisPrefixConverter.wrap(originBytes); + return this.iRedisPrefixConverter.wrap(originBytes); } } diff --git a/redis/ballcat-redis/src/main/java/org/ballcat/redis/thread/AbstractRedisThread.java b/redis/ballcat-redis/src/main/java/org/ballcat/redis/thread/AbstractRedisThread.java index 69de7a741..b62c68f00 100644 --- a/redis/ballcat-redis/src/main/java/org/ballcat/redis/thread/AbstractRedisThread.java +++ b/redis/ballcat-redis/src/main/java/org/ballcat/redis/thread/AbstractRedisThread.java @@ -56,7 +56,7 @@ public abstract class AbstractRedisThread extends AbstractQueueThread { /** * 激活与休眠线程 */ - protected final Condition condition = lock.newCondition(); + protected final Condition condition = this.lock.newCondition(); /** * 获取数据存储的key @@ -99,15 +99,15 @@ public void put(E e) { // 不插入空值 if (e != null) { try { - lock.lockInterruptibly(); + this.lock.lockInterruptibly(); try { // 线程被中断后无法执行Redis命令 RedisHelper.rPush(getKey(), convertToString(e)); // 激活线程 - condition.signal(); + this.condition.signal(); } finally { - lock.unlock(); + this.lock.unlock(); } } catch (InterruptedException ex) { @@ -138,7 +138,7 @@ public E poll(long time) throws InterruptedException { return null; } // 上锁 - lock.lockInterruptibly(); + this.lock.lockInterruptibly(); try { // 设置等待时长 long nanos = TimeUnit.MILLISECONDS.toNanos(time); @@ -151,14 +151,14 @@ public E poll(long time) throws InterruptedException { } // 休眠. 返回剩余的休眠时间 - nanos = condition.awaitNanos(nanos); + nanos = this.condition.awaitNanos(nanos); } while (isRun() && nanos > 0); return convertToObj(pop); } finally { - lock.unlock(); + this.lock.unlock(); } } @@ -166,7 +166,7 @@ public E poll(long time) throws InterruptedException { @Override protected void shutdown(List list) { // 修改运行标志 - run = false; + this.run = false; for (E e : list) { // 所有数据插入redis put(e); @@ -177,7 +177,7 @@ protected void shutdown(List list) { @Override public boolean isRun() { // 运行中 且 未被中断 - return run && !isInterrupted(); + return this.run && !isInterrupted(); } } diff --git a/redis/ballcat-redis/src/test/java/org/ballcat/redis/DistributeLockTest.java b/redis/ballcat-redis/src/test/java/org/ballcat/redis/DistributeLockTest.java index b93aec5e0..5ade583d7 100644 --- a/redis/ballcat-redis/src/test/java/org/ballcat/redis/DistributeLockTest.java +++ b/redis/ballcat-redis/src/test/java/org/ballcat/redis/DistributeLockTest.java @@ -34,7 +34,7 @@ class DistributeLockTest { @Test void testSuccess() { String value = DistributedLock.instance() - .action(lockKey, () -> "value") + .action(this.lockKey, () -> "value") .onSuccess(ret -> ret + "Success") .lock(); Assertions.assertEquals("valueSuccess", value); @@ -43,7 +43,7 @@ void testSuccess() { @Test void testHandleException() { String value = DistributedLock.instance() - .action(lockKey, this::throwIOException) + .action(this.lockKey, this::throwIOException) .onSuccess(ret -> ret + ret) .onException(e -> System.out.println("发生异常了")) .lock(); @@ -53,7 +53,7 @@ void testHandleException() { @Test void testThrowException() { Assertions.assertThrows(IOException.class, - () -> DistributedLock.instance().action(lockKey, this::throwIOException).lock()); + () -> DistributedLock.instance().action(this.lockKey, this::throwIOException).lock()); } String throwIOException() throws IOException { diff --git a/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/AddMessageEventListenerToContainer.java b/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/AddMessageEventListenerToContainer.java index ef2efe91f..2a05237cb 100644 --- a/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/AddMessageEventListenerToContainer.java +++ b/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/AddMessageEventListenerToContainer.java @@ -41,8 +41,8 @@ public class AddMessageEventListenerToContainer { @PostConstruct public void addMessageListener() { // 注册监听器 - for (MessageEventListener messageEventListener : listenerList) { - listenerContainer.addMessageListener(messageEventListener, messageEventListener.topic()); + for (MessageEventListener messageEventListener : this.listenerList) { + this.listenerContainer.addMessageListener(messageEventListener, messageEventListener.topic()); } } diff --git a/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/BallcatRedisAutoConfiguration.java b/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/BallcatRedisAutoConfiguration.java index 1594c57bb..000cf2d49 100644 --- a/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/BallcatRedisAutoConfiguration.java +++ b/redis/ballcat-spring-boot-starter-redis/src/main/java/org/ballcat/autoconfigure/redis/BallcatRedisAutoConfiguration.java @@ -92,7 +92,7 @@ public IRedisPrefixConverter redisPrefixConverter() { @ConditionalOnMissingBean public StringRedisTemplate stringRedisTemplate(IRedisPrefixConverter redisPrefixConverter) { StringRedisTemplate template = new StringRedisTemplate(); - template.setConnectionFactory(redisConnectionFactory); + template.setConnectionFactory(this.redisConnectionFactory); template.setKeySerializer(new PrefixStringRedisSerializer(redisPrefixConverter)); return template; } @@ -102,7 +102,7 @@ public StringRedisTemplate stringRedisTemplate(IRedisPrefixConverter redisPrefix @ConditionalOnMissingBean(name = "redisTemplate") public RedisTemplate redisTemplate(IRedisPrefixConverter redisPrefixConverter) { RedisTemplate template = new RedisTemplate<>(); - template.setConnectionFactory(redisConnectionFactory); + template.setConnectionFactory(this.redisConnectionFactory); template.setKeySerializer(new PrefixJdkRedisSerializer(redisPrefixConverter)); return template; } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProvider.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProvider.java index 0105cd5e5..13ac76f53 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProvider.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProvider.java @@ -80,7 +80,7 @@ protected Authentication getAuthenticatedAuthentication( username, password); log.debug("got usernamePasswordAuthenticationToken={}", usernamePasswordAuthenticationToken); - return daoAuthenticationProvider.authenticate(usernamePasswordAuthenticationToken); + return this.daoAuthenticationProvider.authenticate(usernamePasswordAuthenticationToken); } } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationToken.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationToken.java index fafad978d..8d9a06d57 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationToken.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationToken.java @@ -55,7 +55,7 @@ public OAuth2ResourceOwnerPasswordAuthenticationToken(String username, Authentic @Override public String getName() { - return username; + return this.username; } } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationToken.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationToken.java index 81dc33dfd..dbfedfc00 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationToken.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2TokenRevocationAuthenticationToken.java @@ -118,7 +118,7 @@ public String getTokenTypeHint() { } public OAuth2Authorization getAuthorization() { - return authorization; + return this.authorization; } } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/autoconfigure/OAuth2AuthorizationServerConfigurerExtensionConfiguration.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/autoconfigure/OAuth2AuthorizationServerConfigurerExtensionConfiguration.java index b3aae3436..b66b82416 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/autoconfigure/OAuth2AuthorizationServerConfigurerExtensionConfiguration.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/autoconfigure/OAuth2AuthorizationServerConfigurerExtensionConfiguration.java @@ -90,7 +90,7 @@ public OAuth2TokenRevocationResponseHandler oAuth2TokenRevocationResponseHandler @ConditionalOnBean(OAuth2TokenRevocationResponseHandler.class) public OAuth2TokenRevocationEndpointConfigurerExtension oAuth2TokenRevocationEndpointConfigurerCustomizer( OAuth2TokenRevocationResponseHandler oAuth2TokenRevocationResponseHandler) { - return new OAuth2TokenRevocationEndpointConfigurerExtension(oAuth2AuthorizationService, + return new OAuth2TokenRevocationEndpointConfigurerExtension(this.oAuth2AuthorizationService, oAuth2TokenRevocationResponseHandler); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenResponseEnhanceConfigurerExtension.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenResponseEnhanceConfigurerExtension.java index 6d1f12254..299ef57aa 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenResponseEnhanceConfigurerExtension.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenResponseEnhanceConfigurerExtension.java @@ -97,7 +97,7 @@ private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResp if (refreshToken != null) { builder.refreshToken(refreshToken.getTokenValue()); } - Map additionalParameters = oauth2TokenResponseEnhancer.enhance(accessTokenAuthentication); + Map additionalParameters = this.oauth2TokenResponseEnhancer.enhance(accessTokenAuthentication); if (!CollectionUtils.isEmpty(additionalParameters)) { builder.additionalParameters(additionalParameters); } @@ -105,7 +105,7 @@ private void sendAccessTokenResponse(HttpServletRequest request, HttpServletResp ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); // 添加 cookie, 配合无状态登录使用 - if (setAccessTokenCookie) { + if (this.setAccessTokenCookie) { setCookie(request, response, OAuth2TokenType.ACCESS_TOKEN.getValue(), accessToken.getTokenValue(), 86400); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenRevocationEndpointConfigurerExtension.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenRevocationEndpointConfigurerExtension.java index f0b314411..74bc46b7d 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenRevocationEndpointConfigurerExtension.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/configurer/OAuth2TokenRevocationEndpointConfigurerExtension.java @@ -50,7 +50,7 @@ public void customize(OAuth2AuthorizationServerConfigurer oAuth2AuthorizationSer authenticationProviders .removeIf(x -> x.getClass().isAssignableFrom(OAuth2TokenRevocationAuthenticationProvider.class)); authenticationProviders.add(0, - new BallcatOAuth2TokenRevocationAuthenticationProvider(authorizationService)); + new BallcatOAuth2TokenRevocationAuthenticationProvider(this.authorizationService)); }; final Consumer> convertersConsumer = converters -> { @@ -59,7 +59,7 @@ public void customize(OAuth2AuthorizationServerConfigurer oAuth2AuthorizationSer }; oAuth2AuthorizationServerConfigurer.tokenRevocationEndpoint( - tokenRevocation -> tokenRevocation.revocationResponseHandler(oAuth2TokenRevocationResponseHandler) + tokenRevocation -> tokenRevocation.revocationResponseHandler(this.oAuth2TokenRevocationResponseHandler) .revocationRequestConverters(convertersConsumer) .authenticationProviders(authenticationProvidersConsumer)); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/BasicOAuth2AuthorizationServerConfigurerCustomizer.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/BasicOAuth2AuthorizationServerConfigurerCustomizer.java index 801b8ef9a..d1cb14da4 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/BasicOAuth2AuthorizationServerConfigurerCustomizer.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/BasicOAuth2AuthorizationServerConfigurerCustomizer.java @@ -45,7 +45,7 @@ public class BasicOAuth2AuthorizationServerConfigurerCustomizer implements Sprin public void customize(HttpSecurity http) throws Exception { // 授权服务器配置 OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer(); - for (OAuth2AuthorizationServerConfigurerExtension customizer : oAuth2AuthorizationServerConfigurerExtensionList) { + for (OAuth2AuthorizationServerConfigurerExtension customizer : this.oAuth2AuthorizationServerConfigurerExtensionList) { customizer.customize(authorizationServerConfigurer, http); } @@ -62,8 +62,8 @@ public void customize(HttpSecurity http) throws Exception { http.apply(authorizationServerConfigurer); // 适配处理 - if (!CollectionUtils.isEmpty(OAuth2AuthorizationServerConfigurerAdapters)) { - for (OAuth2AuthorizationServerConfigurerAdapter configurer : OAuth2AuthorizationServerConfigurerAdapters) { + if (!CollectionUtils.isEmpty(this.OAuth2AuthorizationServerConfigurerAdapters)) { + for (OAuth2AuthorizationServerConfigurerAdapter configurer : this.OAuth2AuthorizationServerConfigurerAdapters) { http.apply(configurer); } } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginCaptchaConfigurerAdapter.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginCaptchaConfigurerAdapter.java index d818d88a1..8bbc1e240 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginCaptchaConfigurerAdapter.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginCaptchaConfigurerAdapter.java @@ -56,7 +56,7 @@ public void configure(HttpSecurity httpSecurity) { HttpMethod.POST.name()); // 验证码,必须在 OAuth2ClientAuthenticationFilter 过滤器之后,方便获取当前客户端 - httpSecurity.addFilterAfter(new LoginCaptchaFilter(requestMatcher, captchaValidator), + httpSecurity.addFilterAfter(new LoginCaptchaFilter(requestMatcher, this.captchaValidator), OAuth2ClientAuthenticationFilter.class); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginPasswordDecoderConfigurerAdapter.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginPasswordDecoderConfigurerAdapter.java index e8cb6e655..f04235354 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginPasswordDecoderConfigurerAdapter.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/config/customizer/OAuth2LoginPasswordDecoderConfigurerAdapter.java @@ -55,7 +55,7 @@ public void configure(HttpSecurity httpSecurity) throws Exception { HttpMethod.POST.name()); // 密码解密,必须在 OAuth2ClientAuthenticationFilter 过滤器之后,方便获取当前客户端 - httpSecurity.addFilterAfter(new LoginPasswordDecoderFilter(requestMatcher, passwordSecretKey), + httpSecurity.addFilterAfter(new LoginPasswordDecoderFilter(requestMatcher, this.passwordSecretKey), OAuth2ClientAuthenticationFilter.class); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/authentication/OAuth2TokenRevocationResponseHandler.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/authentication/OAuth2TokenRevocationResponseHandler.java index bc570014d..ef2ceb43b 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/authentication/OAuth2TokenRevocationResponseHandler.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/authentication/OAuth2TokenRevocationResponseHandler.java @@ -44,7 +44,7 @@ public class OAuth2TokenRevocationResponseHandler implements AuthenticationSucce public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { // 发布用户登出事件 - publisher.publishEvent(new LogoutSuccessEvent(authentication)); + this.publisher.publishEvent(new LogoutSuccessEvent(authentication)); // 返回 200 响应 response.setStatus(HttpStatus.OK.value()); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/context/OAuth2SecurityContextRepository.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/context/OAuth2SecurityContextRepository.java index d783fea42..4da184048 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/context/OAuth2SecurityContextRepository.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/context/OAuth2SecurityContextRepository.java @@ -62,7 +62,7 @@ public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHold if (!StringUtils.hasText(bearerToken)) { return SecurityContextHolder.createEmptyContext(); } - OAuth2Authorization oAuth2Authorization = authorizationService.findByToken(bearerToken, + OAuth2Authorization oAuth2Authorization = this.authorizationService.findByToken(bearerToken, OAuth2TokenType.ACCESS_TOKEN); if (oAuth2Authorization == null) { return SecurityContextHolder.createEmptyContext(); diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginCaptchaFilter.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginCaptchaFilter.java index 1079a18df..6742b5e2b 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginCaptchaFilter.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginCaptchaFilter.java @@ -82,7 +82,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse return; } - CaptchaValidateResult captchaValidateResult = captchaValidator.validate(request); + CaptchaValidateResult captchaValidateResult = this.captchaValidator.validate(request); if (captchaValidateResult.isSuccess()) { filterChain.doFilter(request, response); } diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginPasswordDecoderFilter.java b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginPasswordDecoderFilter.java index 3d677e5cb..1101df6af 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginPasswordDecoderFilter.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/main/java/org/ballcat/springsecurity/oauth2/server/authorization/web/filter/LoginPasswordDecoderFilter.java @@ -69,7 +69,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } // 未配置密码密钥时,直接跳过 - if (passwordSecretKey == null) { + if (this.passwordSecretKey == null) { log.warn("passwordSecretKey not configured, skip password decoder"); filterChain.doFilter(request, response); return; @@ -98,12 +98,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String passwordAes = request.getParameter(OAuth2ParameterNames.PASSWORD); try { - String password = PasswordUtils.decodeAES(passwordAes, passwordSecretKey); + String password = PasswordUtils.decodeAES(passwordAes, this.passwordSecretKey); parameterMap.put(OAuth2ParameterNames.PASSWORD, new String[] { password }); } catch (Exception e) { log.error("[doFilterInternal] password decode aes error,passwordAes: {},passwordSecretKey: {}", passwordAes, - passwordSecretKey, e); + this.passwordSecretKey, e); response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); response.setStatus(HttpStatus.BAD_REQUEST.value()); R r = R.failed(SystemResultCode.UNAUTHORIZED, "用户名或密码错误!"); diff --git a/security/ballcat-spring-security-oauth2-authorization-server/src/test/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProviderTests.java b/security/ballcat-spring-security-oauth2-authorization-server/src/test/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProviderTests.java index eee9eac1d..7b399931e 100644 --- a/security/ballcat-spring-security-oauth2-authorization-server/src/test/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProviderTests.java +++ b/security/ballcat-spring-security-oauth2-authorization-server/src/test/java/org/ballcat/springsecurity/oauth2/server/authorization/authentication/OAuth2ResourceOwnerPasswordAuthenticationProviderTests.java @@ -126,7 +126,7 @@ void constructorWhenAuthorizationServiceNullThenThrowIllegalArgumentException() @Test void constructorWhenOAuth2TokenGeneratorNullThenThrowIllegalArgumentException() { assertThatThrownBy(() -> new OAuth2ResourceOwnerPasswordAuthenticationProvider(this.authorizationService, null, - userDetailsService)) + this.userDetailsService)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("tokenGenerator cannot be null"); } diff --git a/security/ballcat-spring-security-oauth2-core/src/main/java/org/ballcat/springsecurity/oauth2/userdetails/ClientPrincipal.java b/security/ballcat-spring-security-oauth2-core/src/main/java/org/ballcat/springsecurity/oauth2/userdetails/ClientPrincipal.java index df3362c50..ded5c6e20 100644 --- a/security/ballcat-spring-security-oauth2-core/src/main/java/org/ballcat/springsecurity/oauth2/userdetails/ClientPrincipal.java +++ b/security/ballcat-spring-security-oauth2-core/src/main/java/org/ballcat/springsecurity/oauth2/userdetails/ClientPrincipal.java @@ -46,7 +46,7 @@ public class ClientPrincipal implements OAuth2AuthenticatedPrincipal, Serializab @NonNull public Set getScope() { - return scope; + return this.scope; } public void setScope(Collection scope) { @@ -55,17 +55,17 @@ public void setScope(Collection scope) { @Override public Map getAttributes() { - return attributes; + return this.attributes; } @Override public Collection getAuthorities() { - return authorities; + return this.authorities; } @Override public String getName() { - return clientId; + return this.clientId; } public ClientPrincipal(String clientId, Map attributes, diff --git a/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/configurer/BasicOauth2ResourceServerConfigurerCustomizer.java b/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/configurer/BasicOauth2ResourceServerConfigurerCustomizer.java index 41b108603..c23cf758a 100644 --- a/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/configurer/BasicOauth2ResourceServerConfigurerCustomizer.java +++ b/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/configurer/BasicOauth2ResourceServerConfigurerCustomizer.java @@ -44,9 +44,9 @@ public BasicOauth2ResourceServerConfigurerCustomizer(AuthenticationEntryPoint au public void customize(HttpSecurity httpSecurity) throws Exception { // 开启 OAuth2 资源服务 httpSecurity.oauth2ResourceServer() - .authenticationEntryPoint(authenticationEntryPoint) + .authenticationEntryPoint(this.authenticationEntryPoint) // bearToken 解析器 - .bearerTokenResolver(bearerTokenResolver) + .bearerTokenResolver(this.bearerTokenResolver) // 不透明令牌, .opaqueToken(); } diff --git a/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/BallcatRemoteOpaqueTokenIntrospector.java b/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/BallcatRemoteOpaqueTokenIntrospector.java index 5426fde30..713e6254e 100644 --- a/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/BallcatRemoteOpaqueTokenIntrospector.java +++ b/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/BallcatRemoteOpaqueTokenIntrospector.java @@ -257,7 +257,7 @@ private OAuth2AuthenticatedPrincipal convertClaimsSet(Map claims if (v instanceof Boolean) { return v; } - logger.warn("自定端点返回的 {} 属性解析异常, 值为: {},", TokenAttributeNameConstants.IS_CLIENT, v); + this.logger.warn("自定端点返回的 {} 属性解析异常, 值为: {},", TokenAttributeNameConstants.IS_CLIENT, v); return false; }); diff --git a/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/SpringAuthorizationServerSharedStoredOpaqueTokenIntrospector.java b/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/SpringAuthorizationServerSharedStoredOpaqueTokenIntrospector.java index 6664443f7..c86fdb537 100644 --- a/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/SpringAuthorizationServerSharedStoredOpaqueTokenIntrospector.java +++ b/security/ballcat-spring-security-oauth2-resource-server/src/main/java/org/ballcat/springsecurity/oauth2/server/resource/introspection/SpringAuthorizationServerSharedStoredOpaqueTokenIntrospector.java @@ -61,7 +61,7 @@ public SpringAuthorizationServerSharedStoredOpaqueTokenIntrospector( */ @Override public OAuth2AuthenticatedPrincipal introspect(String accessTokenValue) { - OAuth2Authorization authorization = authorizationService.findByToken(accessTokenValue, null); + OAuth2Authorization authorization = this.authorizationService.findByToken(accessTokenValue, null); if (authorization == null) { if (log.isTraceEnabled()) { log.trace("Did not authenticate token introspection request since token was not found"); diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/authentication/AnonymousForeverAuthenticationProvider.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/authentication/AnonymousForeverAuthenticationProvider.java index 27bffce65..ea066282b 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/authentication/AnonymousForeverAuthenticationProvider.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/authentication/AnonymousForeverAuthenticationProvider.java @@ -68,10 +68,12 @@ public class AnonymousForeverAuthenticationProvider implements AuthenticationPro public AnonymousForeverAuthenticationProvider(List pathList) { if (CollectionUtils.isEmpty(pathList)) { - pathPatterns = new ArrayList<>(); + this.pathPatterns = new ArrayList<>(); } else { - pathPatterns = pathList.stream().map(PathPatternParser.defaultInstance::parse).collect(Collectors.toList()); + this.pathPatterns = pathList.stream() + .map(PathPatternParser.defaultInstance::parse) + .collect(Collectors.toList()); } this.key = UUID.randomUUID().toString(); @@ -100,7 +102,7 @@ public Authentication authenticate(Authentication authentication) throws Authent String requestUri = request.getRequestURI(); PathContainer pathContainer = PathContainer.parsePath(requestUri); - boolean anyMatch = pathPatterns.stream().anyMatch(x -> x.matches(pathContainer)); + boolean anyMatch = this.pathPatterns.stream().anyMatch(x -> x.matches(pathContainer)); if (anyMatch) { Authentication anonymousAuthentication = createAuthentication(request); log.debug("Set SecurityContextHolder to anonymous SecurityContext"); diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/AuthorizeRequestsSpringSecurityConfigurerCustomizer.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/AuthorizeRequestsSpringSecurityConfigurerCustomizer.java index fea5780ba..8ba16244f 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/AuthorizeRequestsSpringSecurityConfigurerCustomizer.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/AuthorizeRequestsSpringSecurityConfigurerCustomizer.java @@ -42,7 +42,7 @@ public void customize(HttpSecurity httpSecurity) throws Exception { // 拦截 url 配置 httpSecurity.requestMatcher(AnyRequestMatcher.INSTANCE) .authorizeRequests() - .antMatchers(springSecurityProperties.getIgnoreUrls().toArray(new String[0])) + .antMatchers(this.springSecurityProperties.getIgnoreUrls().toArray(new String[0])) .permitAll() .anyRequest() .authenticated(); diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/ExceptionHandleSpringSecurityConfigurerCustomizer.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/ExceptionHandleSpringSecurityConfigurerCustomizer.java index 2a3c142f3..6cf9dd43f 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/ExceptionHandleSpringSecurityConfigurerCustomizer.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/ExceptionHandleSpringSecurityConfigurerCustomizer.java @@ -35,7 +35,7 @@ public ExceptionHandleSpringSecurityConfigurerCustomizer(AuthenticationEntryPoin @Override public void customize(HttpSecurity httpSecurity) throws Exception { - httpSecurity.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint); + httpSecurity.exceptionHandling().authenticationEntryPoint(this.authenticationEntryPoint); } @Override diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/FormLoginSpringSecurityConfigurerCustomizer.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/FormLoginSpringSecurityConfigurerCustomizer.java index 1e40035f0..d25dbf865 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/FormLoginSpringSecurityConfigurerCustomizer.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/FormLoginSpringSecurityConfigurerCustomizer.java @@ -47,18 +47,18 @@ public class FormLoginSpringSecurityConfigurerCustomizer implements SpringSecuri @Override public void customize(HttpSecurity httpSecurity) throws Exception { // 表单登录 - SpringSecurityProperties.FormLogin formLogin = springSecurityProperties.getFormLogin(); + SpringSecurityProperties.FormLogin formLogin = this.springSecurityProperties.getFormLogin(); if (formLogin.isEnabled()) { FormLoginConfigurer formLoginConfigurer = httpSecurity.formLogin(); - if (formLoginSuccessHandler != null) { - formLoginConfigurer.successHandler(formLoginSuccessHandler); + if (this.formLoginSuccessHandler != null) { + formLoginConfigurer.successHandler(this.formLoginSuccessHandler); } - if (authenticationEntryPoint != null) { + if (this.authenticationEntryPoint != null) { AuthenticationEntryPointFailureHandler authenticationFailureHandler = new AuthenticationEntryPointFailureHandler( - authenticationEntryPoint); + this.authenticationEntryPoint); formLoginConfigurer.failureHandler(authenticationFailureHandler); httpSecurity.setSharedObject(AuthenticationFailureHandler.class, authenticationFailureHandler); } @@ -77,8 +77,8 @@ public void customize(HttpSecurity httpSecurity) throws Exception { // 登出 LogoutConfigurer logout = httpSecurity.logout(); - if (logoutSuccessHandler != null) { - logout.logoutSuccessHandler(logoutSuccessHandler); + if (this.logoutSuccessHandler != null) { + logout.logoutSuccessHandler(this.logoutSuccessHandler); } } } diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginCaptchaSpringSecurityConfigurerCustomizer.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginCaptchaSpringSecurityConfigurerCustomizer.java index b472c6f9b..4158ab55d 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginCaptchaSpringSecurityConfigurerCustomizer.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginCaptchaSpringSecurityConfigurerCustomizer.java @@ -52,7 +52,7 @@ public LoginCaptchaSpringSecurityConfigurerCustomizer(SpringSecurityProperties s @Override public void customize(HttpSecurity httpSecurity) throws Exception { - SpringSecurityProperties.FormLogin formLogin = springSecurityProperties.getFormLogin(); + SpringSecurityProperties.FormLogin formLogin = this.springSecurityProperties.getFormLogin(); String loginProcessingUrl = formLogin.getLoginProcessingUrl(); if (loginProcessingUrl == null) { @@ -66,9 +66,9 @@ public void customize(HttpSecurity httpSecurity) throws Exception { AntPathRequestMatcher requestMatcher = new AntPathRequestMatcher(loginProcessingUrl, HttpMethod.POST.name()); // 创建过滤器 - LoginCaptchaFilter filter = new LoginCaptchaFilter(requestMatcher, captchaValidator); - if (messageSource != null) { - filter.setMessageSource(messageSource); + LoginCaptchaFilter filter = new LoginCaptchaFilter(requestMatcher, this.captchaValidator); + if (this.messageSource != null) { + filter.setMessageSource(this.messageSource); } AuthenticationFailureHandler failureHandler = httpSecurity.getSharedObject(AuthenticationFailureHandler.class); if (failureHandler != null) { diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginPasswordDecodeSpringSecurityConfigurerCustomizer.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginPasswordDecodeSpringSecurityConfigurerCustomizer.java index 762b450b8..b993cc210 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginPasswordDecodeSpringSecurityConfigurerCustomizer.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/LoginPasswordDecodeSpringSecurityConfigurerCustomizer.java @@ -51,7 +51,7 @@ public LoginPasswordDecodeSpringSecurityConfigurerCustomizer(SpringSecurityPrope @Override public void customize(HttpSecurity httpSecurity) throws Exception { - SpringSecurityProperties.FormLogin formLogin = springSecurityProperties.getFormLogin(); + SpringSecurityProperties.FormLogin formLogin = this.springSecurityProperties.getFormLogin(); String loginProcessingUrl = formLogin.getLoginProcessingUrl(); if (loginProcessingUrl == null) { @@ -65,9 +65,9 @@ public void customize(HttpSecurity httpSecurity) throws Exception { AntPathRequestMatcher requestMatcher = new AntPathRequestMatcher(loginProcessingUrl, HttpMethod.POST.name()); // 创建过滤器 - LoginPasswordDecoderFilter filter = new LoginPasswordDecoderFilter(requestMatcher, passwordSecretKey); - if (messageSource != null) { - filter.setMessageSource(messageSource); + LoginPasswordDecoderFilter filter = new LoginPasswordDecoderFilter(requestMatcher, this.passwordSecretKey); + if (this.messageSource != null) { + filter.setMessageSource(this.messageSource); } AuthenticationFailureHandler failureHandler = httpSecurity.getSharedObject(AuthenticationFailureHandler.class); if (failureHandler != null) { diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SeparationLoginSpringSecurityConfigurerCustomizer.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SeparationLoginSpringSecurityConfigurerCustomizer.java index b83ef237c..42bad6991 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SeparationLoginSpringSecurityConfigurerCustomizer.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SeparationLoginSpringSecurityConfigurerCustomizer.java @@ -50,12 +50,13 @@ public class SeparationLoginSpringSecurityConfigurerCustomizer implements Spring @Override public void customize(HttpSecurity httpSecurity) throws Exception { // 表单登录 - SpringSecurityProperties.FormLogin formLogin = springSecurityProperties.getFormLogin(); + SpringSecurityProperties.FormLogin formLogin = this.springSecurityProperties.getFormLogin(); if (formLogin.isEnabled()) { - AuthenticationSuccessHandler successHandler = formLoginSuccessHandler == null - ? new DefaultFormLoginSuccessHandler() : formLoginSuccessHandler; + AuthenticationSuccessHandler successHandler = this.formLoginSuccessHandler == null + ? new DefaultFormLoginSuccessHandler() : this.formLoginSuccessHandler; AuthenticationEntryPointFailureHandler failureHandler = new AuthenticationEntryPointFailureHandler( - authenticationEntryPoint == null ? new Http403ForbiddenEntryPoint() : authenticationEntryPoint); + this.authenticationEntryPoint == null ? new Http403ForbiddenEntryPoint() + : this.authenticationEntryPoint); httpSecurity.setSharedObject(AuthenticationFailureHandler.class, failureHandler); SeparationLoginConfigurer separationLoginConfigurer = httpSecurity diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SpringSecurityFilterChainConfiguration.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SpringSecurityFilterChainConfiguration.java index 849973c76..bd2fd8270 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SpringSecurityFilterChainConfiguration.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuer/SpringSecurityFilterChainConfiguration.java @@ -52,16 +52,16 @@ SecurityFilterChain defaultSecurityFilterChain(HttpSecurity httpSecurity) throws httpSecurity.csrf().disable(); // 允许嵌入iframe - if (!springSecurityProperties.isIframeDeny()) { + if (!this.springSecurityProperties.isIframeDeny()) { httpSecurity.headers().frameOptions().disable(); } // 使用无状态登录时,需要配合自定义的 SecurityContextRepository - SessionCreationPolicy sessionCreationPolicy = springSecurityProperties.getSessionCreationPolicy(); + SessionCreationPolicy sessionCreationPolicy = this.springSecurityProperties.getSessionCreationPolicy(); httpSecurity.sessionManagement().sessionCreationPolicy(sessionCreationPolicy); // 自定义处理 - List configurerCustomizers = configurerCustomizersProvider + List configurerCustomizers = this.configurerCustomizersProvider .getIfAvailable(Collections::emptyList); for (SpringSecurityConfigurerCustomizer configurerCustomizer : configurerCustomizers) { configurerCustomizer.customize(httpSecurity); diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuration/SpringSecurityWebSecurityConfiguration.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuration/SpringSecurityWebSecurityConfiguration.java index ff9393ff2..784ea441c 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuration/SpringSecurityWebSecurityConfiguration.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/configuration/SpringSecurityWebSecurityConfiguration.java @@ -57,7 +57,7 @@ public SpringSecurityWebSecurityConfiguration(SpringSecurityProperties springSec @Bean @ConditionalOnMissingBean public AuthorizeRequestsSpringSecurityConfigurerCustomizer springSecurityAnyRequestAuthenticatedCustomizer() { - return new AuthorizeRequestsSpringSecurityConfigurerCustomizer(springSecurityProperties); + return new AuthorizeRequestsSpringSecurityConfigurerCustomizer(this.springSecurityProperties); } @Bean @@ -76,7 +76,7 @@ public SeparationLoginSpringSecurityConfigurerCustomizer springSecurityFormLogin ObjectProvider authenticationEntryPointObjectProvider, ObjectProvider formLoginSuccessHandlerObjectProvider, ObjectProvider logoutSuccessHandlerObjectProvider) { - return new SeparationLoginSpringSecurityConfigurerCustomizer(springSecurityProperties, + return new SeparationLoginSpringSecurityConfigurerCustomizer(this.springSecurityProperties, authenticationEntryPointObjectProvider.getIfAvailable(), formLoginSuccessHandlerObjectProvider.getIfAvailable(), logoutSuccessHandlerObjectProvider.getIfAvailable()); @@ -90,7 +90,7 @@ public FormLoginSpringSecurityConfigurerCustomizer formLoginSpringSecurityConfig ObjectProvider authenticationEntryPointObjectProvider, ObjectProvider formLoginSuccessHandlerObjectProvider, ObjectProvider logoutSuccessHandlerObjectProvider) { - return new FormLoginSpringSecurityConfigurerCustomizer(springSecurityProperties, + return new FormLoginSpringSecurityConfigurerCustomizer(this.springSecurityProperties, authenticationEntryPointObjectProvider.getIfAvailable(), formLoginSuccessHandlerObjectProvider.getIfAvailable(), logoutSuccessHandlerObjectProvider.getIfAvailable()); @@ -101,7 +101,7 @@ public FormLoginSpringSecurityConfigurerCustomizer formLoginSpringSecurityConfig @ConditionalOnProperty(prefix = "ballcat.springsecurity.form-login", name = "login-captcha", havingValue = "true") public LoginCaptchaSpringSecurityConfigurerCustomizer loginCaptchaSpringSecurityConfigurerCustomizer( CaptchaValidator captchaValidator) { - return new LoginCaptchaSpringSecurityConfigurerCustomizer(springSecurityProperties, captchaValidator); + return new LoginCaptchaSpringSecurityConfigurerCustomizer(this.springSecurityProperties, captchaValidator); } @Bean @@ -109,7 +109,8 @@ public LoginCaptchaSpringSecurityConfigurerCustomizer loginCaptchaSpringSecurity @ConditionalOnProperty(prefix = "ballcat.security", name = "password-secret-key") public LoginPasswordDecodeSpringSecurityConfigurerCustomizer loginPasswordDecodeSpringSecurityConfigurerCustomizer( @Value("${ballcat.security.password-secret-key}") String passwordSecretKey) { - return new LoginPasswordDecodeSpringSecurityConfigurerCustomizer(springSecurityProperties, passwordSecretKey); + return new LoginPasswordDecodeSpringSecurityConfigurerCustomizer(this.springSecurityProperties, + passwordSecretKey); } } diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/UsernameAesPasswordAuthenticationFilter.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/UsernameAesPasswordAuthenticationFilter.java index f0c9710ce..9ccc989e9 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/UsernameAesPasswordAuthenticationFilter.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/UsernameAesPasswordAuthenticationFilter.java @@ -53,13 +53,13 @@ public UsernameAesPasswordAuthenticationFilter(AuthenticationManager authenticat @Override protected String obtainPassword(HttpServletRequest request) { String requestPassword = request.getParameter(getPasswordParameter()); - if (passwordSecretKey == null) { + if (this.passwordSecretKey == null) { return requestPassword; } // 先进行 AES 解密 try { - return PasswordUtils.decodeAES(requestPassword, passwordSecretKey); + return PasswordUtils.decodeAES(requestPassword, this.passwordSecretKey); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("error parameter", e); diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginCaptchaFilter.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginCaptchaFilter.java index 93f30a679..8d43cc6a6 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginCaptchaFilter.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginCaptchaFilter.java @@ -61,13 +61,13 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse return; } - CaptchaValidateResult captchaValidateResult = captchaValidator.validate(request); + CaptchaValidateResult captchaValidateResult = this.captchaValidator.validate(request); if (captchaValidateResult.isSuccess()) { filterChain.doFilter(request, response); } else { - logger.error("Captcha verification failed, captchaValidateResult: " + captchaValidateResult); - failureHandler.onAuthenticationFailure(request, response, new InvalidCaptchaException(this.messages + this.logger.error("Captcha verification failed, captchaValidateResult: " + captchaValidateResult); + this.failureHandler.onAuthenticationFailure(request, response, new InvalidCaptchaException(this.messages .getMessage("LoginCaptchaFilter.captchaVerificationFailed", "Captcha verification failed"))); } } diff --git a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginPasswordDecoderFilter.java b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginPasswordDecoderFilter.java index 200c81ff2..c03c7f255 100644 --- a/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginPasswordDecoderFilter.java +++ b/security/ballcat-spring-security/src/main/java/org/ballcat/springsecurity/web/filter/LoginPasswordDecoderFilter.java @@ -74,7 +74,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } // 未配置密码密钥时,直接跳过 - if (passwordSecretKey == null) { + if (this.passwordSecretKey == null) { log.warn("passwordSecretKey not configured, skip password decoder"); filterChain.doFilter(request, response); return; @@ -82,16 +82,16 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // 解密前台加密后的密码 Map parameterMap = new HashMap<>(request.getParameterMap()); - String passwordAes = request.getParameter(passwordParameterName); + String passwordAes = request.getParameter(this.passwordParameterName); try { - String password = PasswordUtils.decodeAES(passwordAes, passwordSecretKey); - parameterMap.put(passwordParameterName, new String[] { password }); + String password = PasswordUtils.decodeAES(passwordAes, this.passwordSecretKey); + parameterMap.put(this.passwordParameterName, new String[] { password }); } catch (Exception e) { log.error("[doFilterInternal] password decode aes error,passwordAes: {},passwordSecretKey: {}", passwordAes, - passwordSecretKey, e); - failureHandler.onAuthenticationFailure(request, response, new BadCredentialsException(this.messages + this.passwordSecretKey, e); + this.failureHandler.onAuthenticationFailure(request, response, new BadCredentialsException(this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"))); return; } @@ -102,7 +102,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } public String getPasswordParameterName() { - return passwordParameterName; + return this.passwordParameterName; } public void setPasswordParameterName(String passwordParameterName) { diff --git a/security/ballcat-spring-security/src/test/java/org/ballcat/springsecyrity/util/PasswordTest.java b/security/ballcat-spring-security/src/test/java/org/ballcat/springsecyrity/util/PasswordTest.java index 8612ac33f..7e3f074f3 100644 --- a/security/ballcat-spring-security/src/test/java/org/ballcat/springsecyrity/util/PasswordTest.java +++ b/security/ballcat-spring-security/src/test/java/org/ballcat/springsecyrity/util/PasswordTest.java @@ -38,19 +38,19 @@ void matchTest() { // 不指定加密算法时,默认使用 bcrypt 加密算法 String defaultEncodedPassword = "$2a$10$IRAHstZa7wgcrrifF6tpNeSlpvCBe3Tl3GEDQEUxtI/Gxc30OUxlW"; - Assertions.assertTrue(PASSWORD_ENCODER.matches(rawPassword, defaultEncodedPassword)); + Assertions.assertTrue(this.PASSWORD_ENCODER.matches(rawPassword, defaultEncodedPassword)); // 指定使用 bcrypt 加密算法的存储的密码 String bcryptPassword = "{bcrypt}$2a$10$IRAHstZa7wgcrrifF6tpNeSlpvCBe3Tl3GEDQEUxtI/Gxc30OUxlW"; - Assertions.assertTrue(PASSWORD_ENCODER.matches(rawPassword, bcryptPassword)); + Assertions.assertTrue(this.PASSWORD_ENCODER.matches(rawPassword, bcryptPassword)); // 指定不用加密算法原样存储的密码 String noopPassword = "{noop}a123456"; - Assertions.assertTrue(PASSWORD_ENCODER.matches(rawPassword, noopPassword)); + Assertions.assertTrue(this.PASSWORD_ENCODER.matches(rawPassword, noopPassword)); // 指定使用 MD5 存储的密码 String md5Password = "{MD5}dc483e80a7a0bd9ef71d8cf973673924"; - Assertions.assertTrue(PASSWORD_ENCODER.matches(rawPassword, md5Password)); + Assertions.assertTrue(this.PASSWORD_ENCODER.matches(rawPassword, md5Password)); } } diff --git a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/SmsAutoConfiguration.java b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/SmsAutoConfiguration.java index 56e0f0977..c12c19e30 100644 --- a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/SmsAutoConfiguration.java +++ b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/SmsAutoConfiguration.java @@ -43,7 +43,7 @@ public class SmsAutoConfiguration { @ConditionalOnMissingBean(AbstractSmsSender.class) @ConditionalOnProperty(name = "ballcat.sms.type", havingValue = "TENCENT") public TencentSender tencentSmsSender() { - return new TencentSender(properties); + return new TencentSender(this.properties); } @Bean @@ -51,7 +51,7 @@ public TencentSender tencentSmsSender() { @ConditionalOnMissingBean(AbstractSmsSender.class) @ConditionalOnProperty(name = "ballcat.sms.type", havingValue = "ALIYUN") public AliyunSender aliyunSmsSender() { - return new AliyunSender(properties); + return new AliyunSender(this.properties); } } diff --git a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/aliyun/AliyunSender.java b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/aliyun/AliyunSender.java index ff21749ab..a3accd84f 100644 --- a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/aliyun/AliyunSender.java +++ b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/aliyun/AliyunSender.java @@ -39,15 +39,15 @@ public class AliyunSender extends AbstractSmsSender { private final Aliyun aliyun; public AliyunSender(SmsProperties properties) throws Exception { - aliyun = properties.getAliyun(); + this.aliyun = properties.getAliyun(); Config config = new Config() // 您的AccessKey ID - .setAccessKeyId(aliyun.getAccessKeyId()) + .setAccessKeyId(this.aliyun.getAccessKeyId()) // 您的AccessKey Secret - .setAccessKeySecret(aliyun.getAccessKeySecret()) + .setAccessKeySecret(this.aliyun.getAccessKeySecret()) // 访问的域名 - .setEndpoint(aliyun.getEndpoint()); - client = new Client(config); + .setEndpoint(this.aliyun.getEndpoint()); + this.client = new Client(config); } @Override @@ -57,12 +57,12 @@ public TypeEnum platform() { @Override protected SmsSenderResult doSend(AliYunSenderParams sp) throws Exception { - String templateId = aliyun.getTemplateId(); + String templateId = this.aliyun.getTemplateId(); if (StringUtils.hasText(sp.getTemplateId())) { templateId = sp.getTemplateId(); } - String signName = aliyun.getSignName(); + String signName = this.aliyun.getSignName(); if (StringUtils.hasText(sp.getSignName())) { signName = sp.getSignName(); } @@ -72,7 +72,7 @@ protected SmsSenderResult doSend(AliYunSenderParams sp) throws Exception { .setTemplateCode(templateId) .setTemplateParam(JsonUtils.toJson(sp.getAliyunTemplateParam())); - SendSmsResponse resp = client.sendSms(req); + SendSmsResponse resp = this.client.sendSms(req); return SmsSenderResult.generateAliyun(JsonUtils.toJson(resp), sp.toString(), sp.getPhoneNumbers()); } diff --git a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/sender/AbstractSmsSender.java b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/sender/AbstractSmsSender.java index e8e9eb915..e3785d2f4 100644 --- a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/sender/AbstractSmsSender.java +++ b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/sender/AbstractSmsSender.java @@ -54,7 +54,7 @@ public SmsSenderResult send(P p) { */ public SmsSenderResult errRet(TypeEnum platform, Set phoneNumbers, String msg, Exception e) { String id = ObjectId.get().toString(); - log.error("sms result error! errorId: {}; {}", id, msg, e); + this.log.error("sms result error! errorId: {}; {}", id, msg, e); return SmsSenderResult.generateException(platform, phoneNumbers, id, e); } diff --git a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/tencent/TencentSender.java b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/tencent/TencentSender.java index 5ae1f4a53..12747094f 100644 --- a/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/tencent/TencentSender.java +++ b/sms/ballcat-spring-boot-starter-sms/src/main/java/org/ballcat/sms/tencent/TencentSender.java @@ -45,8 +45,8 @@ public class TencentSender extends AbstractSmsSender { private final Credential cred; public TencentSender(SmsProperties properties) { - tencent = properties.getTencent(); - cred = new Credential(properties.getId(), properties.getKey()); + this.tencent = properties.getTencent(); + this.cred = new Credential(properties.getId(), properties.getKey()); } @Override @@ -57,16 +57,16 @@ public TypeEnum platform() { @Override protected SmsSenderResult doSend(TencentSenderParams sp) throws Exception { HttpProfile httpProfile = new HttpProfile(); - httpProfile.setEndpoint(tencent.getEndpoint()); + httpProfile.setEndpoint(this.tencent.getEndpoint()); ClientProfile clientProfile = new ClientProfile(); clientProfile.setHttpProfile(httpProfile); - SmsClient client = new SmsClient(cred, tencent.getRegion(), clientProfile); + SmsClient client = new SmsClient(this.cred, this.tencent.getRegion(), clientProfile); Map json = new HashMap<>(5); json.put("PhoneNumberSet", sp.getPhoneNumbers()); - json.put("SmsSdkAppid", tencent.getSdkId()); + json.put("SmsSdkAppid", this.tencent.getSdkId()); fillSign(sp, json); fillTemplate(sp, json); @@ -77,7 +77,7 @@ protected SmsSenderResult doSend(TencentSenderParams sp) throws Exception { } protected void fillSign(TencentSenderParams sp, Map json) { - String sign = StringUtils.hasText(sp.getSign()) ? sp.getSign() : tencent.getSign(); + String sign = StringUtils.hasText(sp.getSign()) ? sp.getSign() : this.tencent.getSign(); if (!StringUtils.hasText(sign)) { return; } @@ -85,7 +85,7 @@ protected void fillSign(TencentSenderParams sp, Map json) { } protected void fillTemplate(TencentSenderParams sp, Map json) { - Integer templateId = sp.getTemplateId() != null ? sp.getTemplateId() : tencent.getTemplateId(); + Integer templateId = sp.getTemplateId() != null ? sp.getTemplateId() : this.tencent.getTemplateId(); if (templateId == null) { return; } diff --git a/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/Tesseract.java b/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/Tesseract.java index b83a3b1e4..50bf74d3e 100644 --- a/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/Tesseract.java +++ b/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/Tesseract.java @@ -50,7 +50,7 @@ public class Tesseract { * @param path 例: C:\Program Files\Tesseract-OCR\tesseract.exe */ public void setTesseractPath(String path) { - tesseractPath = path; + this.tesseractPath = path; } /** @@ -59,7 +59,8 @@ public void setTesseractPath(String path) { * @return a {@link java.util.List} object */ public List run(Consumer builderConsumer) { - final TesseractCommand.TesseractCommandBuilder builder = TesseractCommand.builder().tesseract(tesseractPath); + final TesseractCommand.TesseractCommandBuilder builder = TesseractCommand.builder() + .tesseract(this.tesseractPath); builderConsumer.accept(builder); return builder.build().run(); } diff --git a/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractCommand.java b/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractCommand.java index 6914de464..e3745a9ae 100644 --- a/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractCommand.java +++ b/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractCommand.java @@ -60,24 +60,24 @@ public class TesseractCommand { * @return a {@link java.lang.String} object. */ public String getCommand() { - StringBuilder builder = new StringBuilder("\"").append(tesseract).append("\" \""); + StringBuilder builder = new StringBuilder("\"").append(this.tesseract).append("\" \""); try { - builder.append(image.write()).append("\" stdout"); + builder.append(this.image.write()).append("\" stdout"); } catch (IOException e) { throw new OcrException("图片加载异常!", e); } - if (hasText(lang)) { - builder.append(" -l ").append(lang); + if (hasText(this.lang)) { + builder.append(" -l ").append(this.lang); } - if (psm != null) { - builder.append(" --psm ").append(psm); + if (this.psm != null) { + builder.append(" --psm ").append(this.psm); } - if (boxes) { + if (this.boxes) { builder.append(" makebox"); } diff --git a/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractImage.java b/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractImage.java index 1ef2e90e8..06507e380 100644 --- a/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractImage.java +++ b/tesseract/ballcat-tesseract/src/main/java/org/ballcat/tesseract/TesseractImage.java @@ -92,15 +92,16 @@ private TesseractImage(File rawFile, BufferedImage buffer, String type) { * @return 灰度图 */ public TesseractImage rgb() { - final BufferedImage grayBuffer = new BufferedImage(buffer.getWidth(), buffer.getHeight(), buffer.getType()); + final BufferedImage grayBuffer = new BufferedImage(this.buffer.getWidth(), this.buffer.getHeight(), + this.buffer.getType()); - for (int x = 0; x < buffer.getWidth(); x++) { - for (int y = 0; y < buffer.getHeight(); y++) { - grayBuffer.setRGB(x, y, toGrayRgb(buffer.getRGB(x, y))); + for (int x = 0; x < this.buffer.getWidth(); x++) { + for (int y = 0; y < this.buffer.getHeight(); y++) { + grayBuffer.setRGB(x, y, toGrayRgb(this.buffer.getRGB(x, y))); } } - return new TesseractImage(rawFile, grayBuffer, type); + return new TesseractImage(this.rawFile, grayBuffer, this.type); } /** @@ -129,17 +130,17 @@ protected int toGrayRgb(int oldRgb) { * @param rectangle a {@link java.awt.Rectangle} object. */ public TesseractImage crop(Rectangle rectangle) { - final BufferedImage cropBuffer = new BufferedImage(rectangle.width, rectangle.height, buffer.getType()); + final BufferedImage cropBuffer = new BufferedImage(rectangle.width, rectangle.height, this.buffer.getType()); - for (int x = 0; x < buffer.getWidth(); x++) { - for (int y = 0; y < buffer.getHeight(); y++) { + for (int x = 0; x < this.buffer.getWidth(); x++) { + for (int y = 0; y < this.buffer.getHeight(); y++) { if (rectangle.contains(x, y)) { - cropBuffer.setRGB(x - rectangle.x, y - rectangle.y, buffer.getRGB(x, y)); + cropBuffer.setRGB(x - rectangle.x, y - rectangle.y, this.buffer.getRGB(x, y)); } } } - return new TesseractImage(rawFile, cropBuffer, type); + return new TesseractImage(this.rawFile, cropBuffer, this.type); } /** @@ -148,19 +149,19 @@ public TesseractImage crop(Rectangle rectangle) { * @throws java.io.IOException if any. */ public String write() throws IOException { - if (tmpFile == null) { + if (this.tmpFile == null) { if (!DIR.exists()) { DIR.mkdirs(); } - tmpFile = new File(DIR, System.currentTimeMillis() + "." + type); - if (tmpFile.createNewFile()) { - ImageIO.write(buffer, type, tmpFile); + this.tmpFile = new File(DIR, System.currentTimeMillis() + "." + this.type); + if (this.tmpFile.createNewFile()) { + ImageIO.write(this.buffer, this.type, this.tmpFile); } else { return write(); } } - return tmpFile.getPath(); + return this.tmpFile.getPath(); } } diff --git a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogAutoConfiguration.java b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogAutoConfiguration.java index e1f06c0fd..306538889 100644 --- a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogAutoConfiguration.java +++ b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogAutoConfiguration.java @@ -55,15 +55,16 @@ public class AccessLogAutoConfiguration { @ConditionalOnMissingBean(AccessLogFilter.class) public AccessLogFilter defaultAccessLogFilter() { // 合并 annotationRules 和 propertiesRules, 注解高于配置 - List annotationRules = AccessLogRuleFinder.findRulesFormAnnotation(requestMappingHandlerMapping); - List propertiesRules = accessLogProperties.getAccessLogRules(); + List annotationRules = AccessLogRuleFinder + .findRulesFormAnnotation(this.requestMappingHandlerMapping); + List propertiesRules = this.accessLogProperties.getAccessLogRules(); List accessLogRules = AccessLogRuleFinder.mergeRules(annotationRules, propertiesRules); - AccessLogRecordOptions defaultRecordOptions = accessLogProperties.getDefaultAccessLogRecordOptions(); + AccessLogRecordOptions defaultRecordOptions = this.accessLogProperties.getDefaultAccessLogRecordOptions(); AbstractAccessLogFilter accessLogFilter = new DefaultAccessLogFilter(defaultRecordOptions, accessLogRules); - accessLogFilter.setMaxBodyLength(accessLogProperties.getMaxBodyLength()); - accessLogFilter.setOrder(accessLogProperties.getFilterOrder()); + accessLogFilter.setMaxBodyLength(this.accessLogProperties.getMaxBodyLength()); + accessLogFilter.setOrder(this.accessLogProperties.getFilterOrder()); return accessLogFilter; } diff --git a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogProperties.java b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogProperties.java index 12f4f37ba..67ee1b096 100644 --- a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogProperties.java +++ b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/accesslog/AccessLogProperties.java @@ -74,11 +74,11 @@ public class AccessLogProperties { private List rules = Collections.emptyList(); public AccessLogRecordOptions getDefaultAccessLogRecordOptions() { - return convertToAccessLogRecordOptions(defaultRecordOptions); + return convertToAccessLogRecordOptions(this.defaultRecordOptions); } public List getAccessLogRules() { - return rules.stream().map(AccessLogProperties::convertToAccessLogRule).collect(Collectors.toList()); + return this.rules.stream().map(AccessLogProperties::convertToAccessLogRule).collect(Collectors.toList()); } private static AccessLogRecordOptions convertToAccessLogRecordOptions(RecordOptions recordOptions) { diff --git a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/actuate/ActuatorSecurityAutoConfiguration.java b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/actuate/ActuatorSecurityAutoConfiguration.java index a860a5069..d29c5a3ba 100644 --- a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/actuate/ActuatorSecurityAutoConfiguration.java +++ b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/actuate/ActuatorSecurityAutoConfiguration.java @@ -55,7 +55,7 @@ public FilterRegistrationBean actuatorFilterRegistration ActuatorSecurityFilter filter = new ActuatorSecurityFilter(actuatorSecurityProperties.getSecretId(), actuatorSecurityProperties.getSecretKey()); registrationBean.setFilter(filter); - String basePath = webEndpointProperties.getBasePath(); + String basePath = this.webEndpointProperties.getBasePath(); if (!StringUtils.hasText(basePath)) { basePath = "/actuator"; } diff --git a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/event/EnvironmentPost.java b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/event/EnvironmentPost.java index 51ec416ca..57a6817d3 100644 --- a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/event/EnvironmentPost.java +++ b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/event/EnvironmentPost.java @@ -33,7 +33,7 @@ public class EnvironmentPost implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - EnvironmentUtils.setEnvironment(environment); + EnvironmentUtils.setENVIRONMENT(environment); } } diff --git a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/servlet/WebMvcAutoConfiguration.java b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/servlet/WebMvcAutoConfiguration.java index 88fa3155b..59b95f013 100644 --- a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/servlet/WebMvcAutoConfiguration.java +++ b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/servlet/WebMvcAutoConfiguration.java @@ -63,7 +63,7 @@ static class CustomWebMvcConfigurer implements WebMvcConfigurer { */ @Override public void addArgumentResolvers(List argumentResolvers) { - argumentResolvers.add(pageParamArgumentResolver); + argumentResolvers.add(this.pageParamArgumentResolver); } } diff --git a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/undertow/BallcatUndertowTimer.java b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/undertow/BallcatUndertowTimer.java index 50b7ad2ea..3c6e9431f 100644 --- a/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/undertow/BallcatUndertowTimer.java +++ b/web/ballcat-spring-boot-starter-web/src/main/java/org/ballcat/autoconfigure/web/undertow/BallcatUndertowTimer.java @@ -29,10 +29,10 @@ public class BallcatUndertowTimer extends AbstractTimer { @Override protected void process() { try { - if (dir == null || dir.exists()) { + if (this.dir == null || this.dir.exists()) { return; } - dir.mkdirs(); + this.dir.mkdirs(); } catch (Exception e) { // diff --git a/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTest.java b/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTest.java index 79f711d9e..e6e28df88 100644 --- a/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTest.java +++ b/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTest.java @@ -44,18 +44,18 @@ class AccessLogTest { @BeforeEach public void setup() { - mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(accessLogFilter).build(); + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.accessLogFilter).build(); } @Test void testDefault() throws Exception { - TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) accessLogFilter; + TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) this.accessLogFilter; testAccessLogFilter.clearHttpInfo(); // ’/test‘ 走默认选项。只记录 queryString, 不记录请求体和响应体 HttpInfo httpInfo = testAccessLogFilter.getHttpInfo(); assertNull(httpInfo); - mockMvc.perform(MockMvcRequestBuilders.get("/test?a=1")) + this.mockMvc.perform(MockMvcRequestBuilders.get("/test?a=1")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Hello, World!")); httpInfo = testAccessLogFilter.getHttpInfo(); @@ -67,13 +67,13 @@ void testDefault() throws Exception { @Test void testIgnored() throws Exception { - TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) accessLogFilter; + TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) this.accessLogFilter; testAccessLogFilter.clearHttpInfo(); // ’/test/ignored‘ 根据配置会进行忽略 HttpInfo httpInfo = testAccessLogFilter.getHttpInfo(); assertNull(httpInfo); - mockMvc.perform(MockMvcRequestBuilders.get("/test/ignored?a=2")) + this.mockMvc.perform(MockMvcRequestBuilders.get("/test/ignored?a=2")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Hello, World!")); assertNull(testAccessLogFilter.getHttpInfo()); @@ -81,7 +81,7 @@ void testIgnored() throws Exception { @Test void testAnnotation() throws Exception { - TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) accessLogFilter; + TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) this.accessLogFilter; testAccessLogFilter.clearHttpInfo(); // ’/test/annotation‘ 根据注解会进行记录 queryString 和响应体 @@ -89,7 +89,7 @@ void testAnnotation() throws Exception { assertNull(httpInfo); String prefix = "haha"; - mockMvc.perform(MockMvcRequestBuilders.post("/test/annotation?a=3").content(prefix)) + this.mockMvc.perform(MockMvcRequestBuilders.post("/test/annotation?a=3").content(prefix)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(prefix + " Hello, World!")); httpInfo = testAccessLogFilter.getHttpInfo(); @@ -101,7 +101,7 @@ void testAnnotation() throws Exception { @Test void testRecordAll() throws Exception { - TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) accessLogFilter; + TestAccessLogFilter testAccessLogFilter = (TestAccessLogFilter) this.accessLogFilter; testAccessLogFilter.clearHttpInfo(); // ’/test/record-all‘ 根据配置会进行记录 queryString 请求体和响应体 @@ -109,7 +109,7 @@ void testRecordAll() throws Exception { assertNull(httpInfo); String prefix = "haha"; - mockMvc.perform(MockMvcRequestBuilders.post("/test/record-all?a=4").content(prefix)) + this.mockMvc.perform(MockMvcRequestBuilders.post("/test/record-all?a=4").content(prefix)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string(prefix + " Hello, World!")); httpInfo = testAccessLogFilter.getHttpInfo(); diff --git a/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTestConfiguration.java b/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTestConfiguration.java index a48a4b878..6728893b9 100644 --- a/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTestConfiguration.java +++ b/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/AccessLogTestConfiguration.java @@ -49,15 +49,16 @@ public class AccessLogTestConfiguration { @Bean public AccessLogFilter accessLogFilter() { // 合并 annotationRules 和 propertiesRules, 注解高于配置 - List annotationRules = AccessLogRuleFinder.findRulesFormAnnotation(requestMappingHandlerMapping); - List propertiesRules = accessLogProperties.getAccessLogRules(); + List annotationRules = AccessLogRuleFinder + .findRulesFormAnnotation(this.requestMappingHandlerMapping); + List propertiesRules = this.accessLogProperties.getAccessLogRules(); List accessLogRules = AccessLogRuleFinder.mergeRules(annotationRules, propertiesRules); - AccessLogRecordOptions defaultRecordOptions = accessLogProperties.getDefaultAccessLogRecordOptions(); + AccessLogRecordOptions defaultRecordOptions = this.accessLogProperties.getDefaultAccessLogRecordOptions(); TestAccessLogFilter accessLogFilter = new TestAccessLogFilter(defaultRecordOptions, accessLogRules); - accessLogFilter.setMaxBodyLength(accessLogProperties.getMaxBodyLength()); - accessLogFilter.setOrder(accessLogProperties.getFilterOrder()); + accessLogFilter.setMaxBodyLength(this.accessLogProperties.getMaxBodyLength()); + accessLogFilter.setOrder(this.accessLogProperties.getFilterOrder()); return accessLogFilter; } diff --git a/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/TestAccessLogFilter.java b/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/TestAccessLogFilter.java index 8747b442d..0cc2e9957 100644 --- a/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/TestAccessLogFilter.java +++ b/web/ballcat-spring-boot-starter-web/src/test/java/org/ballcat/autoconfigure/web/accesslog/TestAccessLogFilter.java @@ -39,7 +39,7 @@ public TestAccessLogFilter(AccessLogRecordOptions defaultRecordOptions, List 0) { + if (this.messages.size() > 0) { // 如果需要发送的消息不为空 - for (ExceptionMessage exceptionMessage : messages.values()) { + for (ExceptionMessage exceptionMessage : this.messages.values()) { notifyExceptionMessage(exceptionMessage); } - messages.clear(); + this.messages.clear(); } watch.reset(); watch.start(); @@ -181,12 +181,12 @@ public ExceptionMessage toMessage(Throwable t) { t.printStackTrace(new PrintStream(stream)); final String e = stream.toString(); return new ExceptionMessage().setNumber(1) - .setMac(mac) - .setApplicationName(applicationName) - .setHostname(hostname) - .setIp(ip) - .setRequestUri(requestUri) - .setStack((e.length() > noticeConfig.getLength() ? e.substring(0, noticeConfig.getLength()) : e) + .setMac(this.mac) + .setApplicationName(this.applicationName) + .setHostname(this.hostname) + .setIp(this.ip) + .setRequestUri(this.requestUri) + .setStack((e.length() > this.noticeConfig.getLength() ? e.substring(0, this.noticeConfig.getLength()) : e) .replace("\\r", "")) .setTime(LocalDateTime.now().format(LocalDateTimeUtils.FORMATTER_YMD_HMS)); } @@ -199,13 +199,13 @@ public void handle(Throwable throwable) { boolean ignore = false; // 只有不是忽略的异常类才会插入异常消息队列 - if (Boolean.FALSE.equals(noticeConfig.getIgnoreChild())) { + if (Boolean.FALSE.equals(this.noticeConfig.getIgnoreChild())) { // 不忽略子类 - ignore = noticeConfig.getIgnoreExceptions().contains(throwable.getClass()); + ignore = this.noticeConfig.getIgnoreExceptions().contains(throwable.getClass()); } else { // 忽略子类 - for (Class ignoreException : noticeConfig.getIgnoreExceptions()) { + for (Class ignoreException : this.noticeConfig.getIgnoreExceptions()) { // 属于子类 if (ignoreException.isAssignableFrom(throwable.getClass())) { ignore = true; @@ -216,7 +216,7 @@ public void handle(Throwable throwable) { // 不忽略则插入队列 if (!ignore) { - queue.put(throwable); + this.queue.put(throwable); } } catch (InterruptedException e) { diff --git a/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/DingTalkExceptionNotifier.java b/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/DingTalkExceptionNotifier.java index 2ee99bd0f..a8b53e9a7 100644 --- a/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/DingTalkExceptionNotifier.java +++ b/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/DingTalkExceptionNotifier.java @@ -48,7 +48,7 @@ public ExceptionNoticeResponse notify(ExceptionMessage sendMessage) { message.atAll(); } - DingTalkResponse response = sender.sendMessage(message); + DingTalkResponse response = this.sender.sendMessage(message); return new ExceptionNoticeResponse().setErrMsg(response.getResponse()).setSuccess(response.isSuccess()); } diff --git a/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/MailExceptionNotifier.java b/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/MailExceptionNotifier.java index e5f5bb79c..2650544ba 100644 --- a/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/MailExceptionNotifier.java +++ b/web/ballcat-web/src/main/java/org/ballcat/web/exception/notice/MailExceptionNotifier.java @@ -46,7 +46,7 @@ public MailExceptionNotifier(MailSender sender, List recipientEmails) { @Override public ExceptionNoticeResponse notify(ExceptionMessage sendMessage) { - MailSendInfo mailSendInfo = sender.sendTextMail("异常警告", sendMessage.toString(), this.recipientEmails); + MailSendInfo mailSendInfo = this.sender.sendTextMail("异常警告", sendMessage.toString(), this.recipientEmails); // 邮箱发送失败会抛出异常,否则视作发送成功 return new ExceptionNoticeResponse().setSuccess(mailSendInfo.getSuccess()) .setErrMsg(mailSendInfo.getErrorMsg()); diff --git a/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/GlobalHandlerExceptionResolver.java b/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/GlobalHandlerExceptionResolver.java index 2b9468374..6d8cd18a2 100644 --- a/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/GlobalHandlerExceptionResolver.java +++ b/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/GlobalHandlerExceptionResolver.java @@ -67,9 +67,9 @@ public class GlobalHandlerExceptionResolver { @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public R handleGlobalException(Exception e, HttpServletRequest request) { log.error("请求地址: {}, 全局异常信息 ex={}", request.getRequestURI(), e.getMessage(), e); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息. - String errorMessage = GlobalConstants.ENV_PROD.equals(profile) ? PROD_ERR_MSG : e.getLocalizedMessage(); + String errorMessage = GlobalConstants.ENV_PROD.equals(this.profile) ? PROD_ERR_MSG : e.getLocalizedMessage(); return R.failed(SystemResultCode.SERVER_ERROR, errorMessage); } @@ -82,9 +82,9 @@ public R handleGlobalException(Exception e, HttpServletRequest request) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public R handleNullPointerException(NullPointerException e, HttpServletRequest request) { log.error("请求地址: {}, 空指针异常 ex={}", request.getRequestURI(), e.getMessage(), e); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息. - String errorMessage = GlobalConstants.ENV_PROD.equals(profile) ? PROD_ERR_MSG : NLP_MSG; + String errorMessage = GlobalConstants.ENV_PROD.equals(this.profile) ? PROD_ERR_MSG : NLP_MSG; return R.failed(SystemResultCode.SERVER_ERROR, errorMessage); } @@ -97,8 +97,8 @@ public R handleNullPointerException(NullPointerException e, HttpServletR @ExceptionHandler(MethodArgumentTypeMismatchException.class) public R handleMethodArgumentTypeMismatchException(Exception e, HttpServletRequest request) { log.error("请求地址: {}, 请求入参异常 ex={}", request.getRequestURI(), e.getMessage(), e); - globalExceptionHandler.handle(e); - String errorMessage = GlobalConstants.ENV_PROD.equals(profile) ? PROD_ERR_MSG : e.getMessage(); + this.globalExceptionHandler.handle(e); + String errorMessage = GlobalConstants.ENV_PROD.equals(this.profile) ? PROD_ERR_MSG : e.getMessage(); return R.failed(SystemResultCode.BAD_REQUEST, errorMessage); } @@ -109,7 +109,7 @@ public R handleMethodArgumentTypeMismatchException(Exception e, HttpServ @ExceptionHandler({ HttpMediaTypeNotSupportedException.class, HttpRequestMethodNotSupportedException.class }) public R requestNotSupportedException(Exception e, HttpServletRequest request) { log.error("请求地址: {}, 请求方式异常 ex={}", request.getRequestURI(), e.getMessage(), e); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); return R.failed(SystemResultCode.BAD_REQUEST, e.getLocalizedMessage()); } @@ -122,7 +122,7 @@ public R requestNotSupportedException(Exception e, HttpServletRequest re @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) { log.error("请求地址: {}, 非法数据输入 ex={}", request.getRequestURI(), e.getMessage(), e); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); return R.failed(SystemResultCode.BAD_REQUEST, e.getMessage()); } @@ -139,7 +139,7 @@ public R handleBodyValidException(BindException e, HttpServletRequest re : "未获取到错误信息!"; log.error("请求地址: {}, 参数绑定异常 ex={}", request.getRequestURI(), errorMsg); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); return R.failed(SystemResultCode.BAD_REQUEST, errorMsg); } @@ -152,7 +152,7 @@ public R handleBodyValidException(BindException e, HttpServletRequest re @ResponseStatus(HttpStatus.BAD_REQUEST) public R handleValidationException(ValidationException e, HttpServletRequest request) { log.error("请求地址: {}, 参数校验异常 ex={}", request.getRequestURI(), e.getMessage()); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); return R.failed(SystemResultCode.BAD_REQUEST, e.getLocalizedMessage()); } @@ -165,7 +165,7 @@ public R handleValidationException(ValidationException e, HttpServletReq @ResponseStatus(HttpStatus.OK) public R handleBallCatException(BusinessException e, HttpServletRequest request) { log.error("请求地址: {}, 业务异常信息 ex={}", request.getRequestURI(), e.getMessage()); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); return R.failed(e.getCode(), e.getMessage()); } diff --git a/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/SecurityHandlerExceptionResolver.java b/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/SecurityHandlerExceptionResolver.java index 66c5cee33..36afca317 100644 --- a/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/SecurityHandlerExceptionResolver.java +++ b/web/ballcat-web/src/main/java/org/ballcat/web/exception/resolver/SecurityHandlerExceptionResolver.java @@ -51,7 +51,7 @@ public R handleAccessDeniedException(AccessDeniedException e) { String msg = SpringSecurityMessageSource.getAccessor() .getMessage("AbstractAccessDecisionManager.accessDenied", e.getMessage()); log.error("拒绝授权异常信息 ex={}", msg); - globalExceptionHandler.handle(e); + this.globalExceptionHandler.handle(e); return R.failed(SystemResultCode.FORBIDDEN, e.getLocalizedMessage()); } diff --git a/web/ballcat-web/src/main/java/org/ballcat/web/pageable/PageParamArgumentResolverSupport.java b/web/ballcat-web/src/main/java/org/ballcat/web/pageable/PageParamArgumentResolverSupport.java index cb798dd57..4d022fefd 100644 --- a/web/ballcat-web/src/main/java/org/ballcat/web/pageable/PageParamArgumentResolverSupport.java +++ b/web/ballcat-web/src/main/java/org/ballcat/web/pageable/PageParamArgumentResolverSupport.java @@ -65,8 +65,8 @@ public abstract class PageParamArgumentResolverSupport { private int maxPageSize = PageableConstants.DEFAULT_MAX_PAGE_SIZE; protected PageParam getPageParam(MethodParameter parameter, HttpServletRequest request) { - String pageParameterValue = request.getParameter(pageParameterName); - String sizeParameterValue = request.getParameter(sizeParameterName); + String pageParameterValue = request.getParameter(this.pageParameterName); + String sizeParameterValue = request.getParameter(this.sizeParameterName); PageParam pageParam; try { @@ -86,9 +86,9 @@ protected PageParam getPageParam(MethodParameter parameter, HttpServletRequest r // ========== 排序处理 =========== Map parameterMap = request.getParameterMap(); // sort 可以传多个,所以同时支持 sort 和 sort[] - String[] sort = parameterMap.get(sortParameterName); + String[] sort = parameterMap.get(this.sortParameterName); if (ObjectUtils.isEmpty(sort)) { - sort = parameterMap.get(sortParameterName + "[]"); + sort = parameterMap.get(this.sortParameterName + "[]"); } List sorts; @@ -220,8 +220,8 @@ protected void paramValidate(MethodParameter parameter, ModelAndViewContainer ma BindingResult bindingResult = binder.getBindingResult(); long size = pageParam.getSize(); - if (size > maxPageSize) { - bindingResult.addError(new ObjectError("size", "分页条数不能大于" + maxPageSize)); + if (size > this.maxPageSize) { + bindingResult.addError(new ObjectError("size", "分页条数不能大于" + this.maxPageSize)); } if (bindingResult.hasErrors() && isBindExceptionRequired(binder, parameter)) { diff --git a/web/ballcat-web/src/main/java/org/ballcat/web/trace/TraceIdFilter.java b/web/ballcat-web/src/main/java/org/ballcat/web/trace/TraceIdFilter.java index f8ec39ebf..57cc27b69 100644 --- a/web/ballcat-web/src/main/java/org/ballcat/web/trace/TraceIdFilter.java +++ b/web/ballcat-web/src/main/java/org/ballcat/web/trace/TraceIdFilter.java @@ -46,15 +46,15 @@ public class TraceIdFilter extends OncePerRequestFilter { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 先获取请求头中的 traceId,如果没有,则生成一个 - String traceId = request.getHeader(traceIdHeaderName); + String traceId = request.getHeader(this.traceIdHeaderName); if (traceId == null || traceId.isEmpty()) { - traceId = traceIdGenerator.generate(); + traceId = this.traceIdGenerator.generate(); } MDC.put(MDCConstants.TRACE_ID_KEY, traceId); try { // 响应头中添加 traceId 参数,方便排查问题 - response.setHeader(traceIdHeaderName, traceId); + response.setHeader(this.traceIdHeaderName, traceId); filterChain.doFilter(request, response); } finally { diff --git a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/WebSocketAutoConfiguration.java b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/WebSocketAutoConfiguration.java index 81a57530e..7b4affa82 100644 --- a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/WebSocketAutoConfiguration.java +++ b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/WebSocketAutoConfiguration.java @@ -63,20 +63,20 @@ public WebSocketConfigurer webSocketConfigurer(List handsh @Autowired(required = false) SockJsServiceConfigurer sockJsServiceConfigurer) { return registry -> { WebSocketHandlerRegistration registration = registry - .addHandler(webSocketHandler, webSocketProperties.getPath()) + .addHandler(webSocketHandler, this.webSocketProperties.getPath()) .addInterceptors(handshakeInterceptor.toArray(new HandshakeInterceptor[0])); - String[] allowedOrigins = webSocketProperties.getAllowedOrigins(); + String[] allowedOrigins = this.webSocketProperties.getAllowedOrigins(); if (allowedOrigins != null && allowedOrigins.length > 0) { registration.setAllowedOrigins(allowedOrigins); } - String[] allowedOriginPatterns = webSocketProperties.getAllowedOriginPatterns(); + String[] allowedOriginPatterns = this.webSocketProperties.getAllowedOriginPatterns(); if (allowedOriginPatterns != null && allowedOriginPatterns.length > 0) { registration.setAllowedOriginPatterns(allowedOriginPatterns); } - if (webSocketProperties.isWithSockjs()) { + if (this.webSocketProperties.isWithSockjs()) { SockJsServiceRegistration sockJsServiceRegistration = registration.withSockJS(); if (sockJsServiceConfigurer != null) { sockJsServiceConfigurer.config(sockJsServiceRegistration); diff --git a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/LocalMessageDistributorConfig.java b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/LocalMessageDistributorConfig.java index cd2919dcc..d3f3d094a 100644 --- a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/LocalMessageDistributorConfig.java +++ b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/LocalMessageDistributorConfig.java @@ -47,7 +47,7 @@ public class LocalMessageDistributorConfig { @Bean @ConditionalOnMissingBean(MessageDistributor.class) public LocalMessageDistributor messageDistributor() { - return new LocalMessageDistributor(webSocketSessionStore); + return new LocalMessageDistributor(this.webSocketSessionStore); } } diff --git a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RedisMessageDistributorConfig.java b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RedisMessageDistributorConfig.java index 82d946d59..a74e90d60 100644 --- a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RedisMessageDistributorConfig.java +++ b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RedisMessageDistributorConfig.java @@ -50,7 +50,7 @@ public class RedisMessageDistributorConfig { @Bean @ConditionalOnMissingBean(MessageDistributor.class) public RedisMessageDistributor messageDistributor(StringRedisTemplate stringRedisTemplate) { - return new RedisMessageDistributor(webSocketSessionStore, stringRedisTemplate); + return new RedisMessageDistributor(this.webSocketSessionStore, stringRedisTemplate); } @Bean diff --git a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RocketMqMessageDistributorConfig.java b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RocketMqMessageDistributorConfig.java index 7fd68221d..cf2cb0c8f 100644 --- a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RocketMqMessageDistributorConfig.java +++ b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/RocketMqMessageDistributorConfig.java @@ -45,7 +45,7 @@ public class RocketMqMessageDistributorConfig { @Bean @ConditionalOnMissingBean(MessageDistributor.class) public RocketmqMessageDistributor messageDistributor(RocketMQTemplate template) { - return new RocketmqMessageDistributor(webSocketSessionStore, template); + return new RocketmqMessageDistributor(this.webSocketSessionStore, template); } } diff --git a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/WebSocketHandlerConfig.java b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/WebSocketHandlerConfig.java index fa3a014ec..3717ce266 100644 --- a/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/WebSocketHandlerConfig.java +++ b/websocket/ballcat-spring-boot-starter-websocket/src/main/java/org/ballcat/autoconfigure/websocket/config/WebSocketHandlerConfig.java @@ -54,9 +54,9 @@ public WebSocketSessionStore webSocketSessionStore( public WebSocketHandler webSocketHandler(WebSocketSessionStore webSocketSessionStore, @Autowired(required = false) PlanTextMessageHandler planTextMessageHandler) { CustomWebSocketHandler customWebSocketHandler = new CustomWebSocketHandler(planTextMessageHandler); - if (webSocketProperties.isMapSession()) { + if (this.webSocketProperties.isMapSession()) { return new MapSessionWebSocketHandlerDecorator(customWebSocketHandler, webSocketSessionStore, - webSocketProperties.getConcurrent()); + this.webSocketProperties.getConcurrent()); } return customWebSocketHandler; } diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/AbstractMessageDistributor.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/AbstractMessageDistributor.java index e86c7b2e1..071d18bd8 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/AbstractMessageDistributor.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/AbstractMessageDistributor.java @@ -48,7 +48,7 @@ protected void doSend(MessageDO messageDO) { // 获取待发送的 sessionKeys Collection sessionKeys; if (needBroadcast != null && needBroadcast) { - sessionKeys = webSocketSessionStore.getSessionKeys(); + sessionKeys = this.webSocketSessionStore.getSessionKeys(); } else { sessionKeys = messageDO.getSessionKeys(); @@ -62,7 +62,7 @@ protected void doSend(MessageDO messageDO) { Boolean onlyOneClientInSameKey = messageDO.getOnlyOneClientInSameKey(); for (Object sessionKey : sessionKeys) { - Collection sessions = webSocketSessionStore.getSessions(sessionKey); + Collection sessions = this.webSocketSessionStore.getSessions(sessionKey); if (!CollectionUtils.isEmpty(sessions)) { // 相同 sessionKey 的客户端只推送一次操作 if (onlyOneClientInSameKey != null && onlyOneClientInSameKey) { diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageDistributor.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageDistributor.java index ab8bf8a0f..2dc853b54 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageDistributor.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageDistributor.java @@ -50,14 +50,14 @@ public RedisMessageDistributor(WebSocketSessionStore webSocketSessionStore, @Override public void distribute(MessageDO messageDO) { String str = JsonUtils.toJson(messageDO); - stringRedisTemplate.convertAndSend(CHANNEL, str); + this.stringRedisTemplate.convertAndSend(CHANNEL, str); } @Override public void onMessage(Message message, byte[] bytes) { log.info("redis channel Listener message send {}", message); byte[] channelBytes = message.getChannel(); - RedisSerializer stringSerializer = stringRedisTemplate.getStringSerializer(); + RedisSerializer stringSerializer = this.stringRedisTemplate.getStringSerializer(); String channel = stringSerializer.deserialize(channelBytes); // 这里没有使用通配符,所以一定是true diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageListenerInitializer.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageListenerInitializer.java index b84381ec7..f4bf9731f 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageListenerInitializer.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/distribute/RedisMessageListenerInitializer.java @@ -36,7 +36,7 @@ public class RedisMessageListenerInitializer { @PostConstruct public void addMessageListener() { - redisMessageListenerContainer.addMessageListener(redisWebsocketMessageListener, + this.redisMessageListenerContainer.addMessageListener(this.redisWebsocketMessageListener, new PatternTopic(RedisMessageDistributor.CHANNEL)); } diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/handler/CustomWebSocketHandler.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/handler/CustomWebSocketHandler.java index c722decbb..5b67f3f17 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/handler/CustomWebSocketHandler.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/handler/CustomWebSocketHandler.java @@ -67,8 +67,8 @@ public void handleTextMessage(WebSocketSession session, TextMessage message) { catch (ErrorJsonMessageException ex) { log.debug("消息载荷 [{}] 回退使用 PlanTextMessageHandler,原因:{}", payload, ex.getMessage()); // fallback 使用普通文本处理 - if (planTextMessageHandler != null) { - planTextMessageHandler.handle(session, payload); + if (this.planTextMessageHandler != null) { + this.planTextMessageHandler.handle(session, payload); } else { log.error("[handleTextMessage] 普通文本消息({})没有对应的消息处理器", payload); diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/holder/JsonMessageHandlerInitializer.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/holder/JsonMessageHandlerInitializer.java index a2265609b..2770e89b8 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/holder/JsonMessageHandlerInitializer.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/holder/JsonMessageHandlerInitializer.java @@ -40,7 +40,7 @@ public class JsonMessageHandlerInitializer { @SuppressWarnings("unchecked") @PostConstruct public void initJsonMessageHandlerHolder() { - for (JsonMessageHandler jsonMessageHandler : jsonMessageHandlerList) { + for (JsonMessageHandler jsonMessageHandler : this.jsonMessageHandlerList) { JsonMessageHandlerHolder.addHandler((JsonMessageHandler) jsonMessageHandler); } } diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/message/JsonWebSocketMessage.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/message/JsonWebSocketMessage.java index 6154b0d60..10bfbaf60 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/message/JsonWebSocketMessage.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/message/JsonWebSocketMessage.java @@ -41,7 +41,7 @@ protected JsonWebSocketMessage(String type) { } public String getType() { - return type; + return this.type; } } diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/DefaultWebSocketSessionStore.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/DefaultWebSocketSessionStore.java index 2b179f388..bb6f582af 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/DefaultWebSocketSessionStore.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/DefaultWebSocketSessionStore.java @@ -48,7 +48,7 @@ public DefaultWebSocketSessionStore(SessionKeyGenerator sessionKeyGenerator) { */ @Override public void addSession(WebSocketSession wsSession) { - Object sessionKey = sessionKeyGenerator.sessionKey(wsSession); + Object sessionKey = this.sessionKeyGenerator.sessionKey(wsSession); Map sessions = this.sessionKeyToWsSessions.get(sessionKey); if (sessions == null) { sessions = new ConcurrentHashMap<>(); @@ -64,7 +64,7 @@ public void addSession(WebSocketSession wsSession) { */ @Override public void removeSession(WebSocketSession session) throws IOException { - Object sessionKey = sessionKeyGenerator.sessionKey(session); + Object sessionKey = this.sessionKeyGenerator.sessionKey(session); String wsSessionId = session.getId(); Map sessions = this.sessionKeyToWsSessions.get(sessionKey); @@ -92,7 +92,10 @@ public void removeSession(WebSocketSession session) throws IOException { */ @Override public Collection getSessions() { - return sessionKeyToWsSessions.values().stream().flatMap(x -> x.values().stream()).collect(Collectors.toList()); + return this.sessionKeyToWsSessions.values() + .stream() + .flatMap(x -> x.values().stream()) + .collect(Collectors.toList()); } /** @@ -116,7 +119,7 @@ public Collection getSessions(Object sessionKey) { */ @Override public Collection getSessionKeys() { - return sessionKeyToWsSessions.keySet(); + return this.sessionKeyToWsSessions.keySet(); } } diff --git a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/MapSessionWebSocketHandlerDecorator.java b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/MapSessionWebSocketHandlerDecorator.java index 5902cea89..20931cbe0 100644 --- a/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/MapSessionWebSocketHandlerDecorator.java +++ b/websocket/ballcat-websocket/src/main/java/org/ballcat/websocket/session/MapSessionWebSocketHandlerDecorator.java @@ -49,13 +49,13 @@ public MapSessionWebSocketHandlerDecorator(WebSocketHandler delegate, WebSocketS @Override public void afterConnectionEstablished(WebSocketSession wsSession) { // 包装一层,防止并发发送出现问题 - if (Boolean.TRUE.equals(concurrentWebSocketSessionOptions.isEnable())) { + if (Boolean.TRUE.equals(this.concurrentWebSocketSessionOptions.isEnable())) { wsSession = new ConcurrentWebSocketSessionDecorator(wsSession, - concurrentWebSocketSessionOptions.getSendTimeLimit(), - concurrentWebSocketSessionOptions.getBufferSizeLimit(), - concurrentWebSocketSessionOptions.getOverflowStrategy()); + this.concurrentWebSocketSessionOptions.getSendTimeLimit(), + this.concurrentWebSocketSessionOptions.getBufferSizeLimit(), + this.concurrentWebSocketSessionOptions.getOverflowStrategy()); } - webSocketSessionStore.addSession(wsSession); + this.webSocketSessionStore.addSession(wsSession); } /** @@ -65,7 +65,7 @@ public void afterConnectionEstablished(WebSocketSession wsSession) { */ @Override public void afterConnectionClosed(WebSocketSession wsSession, CloseStatus closeStatus) throws Exception { - webSocketSessionStore.removeSession(wsSession); + this.webSocketSessionStore.removeSession(wsSession); } } diff --git a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/cleaner/JsoupXssCleaner.java b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/cleaner/JsoupXssCleaner.java index 85aa890e4..55f9d9df5 100644 --- a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/cleaner/JsoupXssCleaner.java +++ b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/cleaner/JsoupXssCleaner.java @@ -93,7 +93,7 @@ protected Safelist buildSafelist() { @Override public String clean(String html) { - return Jsoup.clean(html, baseUri, safelist, new Document.OutputSettings().prettyPrint(false)); + return Jsoup.clean(html, this.baseUri, this.safelist, new Document.OutputSettings().prettyPrint(false)); } } diff --git a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssFilter.java b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssFilter.java index 4ee18191c..23e3ce277 100644 --- a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssFilter.java +++ b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssFilter.java @@ -64,7 +64,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // 开启 Xss 过滤状态 XssStateHolder.open(); try { - filterChain.doFilter(new XssRequestWrapper(request, xssCleaner), response); + filterChain.doFilter(new XssRequestWrapper(request, this.xssCleaner), response); } finally { // 必须删除 ThreadLocal 存储的状态 @@ -75,26 +75,26 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse @Override protected boolean shouldNotFilter(HttpServletRequest request) { // 关闭直接跳过 - if (!xssProperties.isEnabled()) { + if (!this.xssProperties.isEnabled()) { return true; } // 请求方法检查 - if (xssProperties.getIncludeHttpMethods().stream().noneMatch(request.getMethod()::equalsIgnoreCase)) { + if (this.xssProperties.getIncludeHttpMethods().stream().noneMatch(request.getMethod()::equalsIgnoreCase)) { return true; } // 请求路径检查 String requestUri = request.getRequestURI(); // 此路径是否不需要处理 - for (String exclude : xssProperties.getExcludePaths()) { + for (String exclude : this.xssProperties.getExcludePaths()) { if (ANT_PATH_MATCHER.match(exclude, requestUri)) { return true; } } // 路径是否包含 - for (String include : xssProperties.getIncludePaths()) { + for (String include : this.xssProperties.getIncludePaths()) { if (ANT_PATH_MATCHER.match(include, requestUri)) { return false; } diff --git a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssRequestWrapper.java b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssRequestWrapper.java index a138d4847..cab26c455 100644 --- a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssRequestWrapper.java +++ b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssRequestWrapper.java @@ -47,7 +47,7 @@ public Map getParameterMap() { for (Map.Entry entry : parameters.entrySet()) { String[] values = entry.getValue(); for (int i = 0; i < values.length; i++) { - values[i] = xssCleaner.clean(values[i]); + values[i] = this.xssCleaner.clean(values[i]); } map.put(entry.getKey(), values); } @@ -63,7 +63,7 @@ public String[] getParameterValues(String name) { int count = values.length; String[] encodedValues = new String[count]; for (int i = 0; i < count; i++) { - encodedValues[i] = xssCleaner.clean(values[i]); + encodedValues[i] = this.xssCleaner.clean(values[i]); } return encodedValues; } @@ -74,14 +74,14 @@ public String getParameter(String name) { if (value == null) { return null; } - return xssCleaner.clean(value); + return this.xssCleaner.clean(value); } @Override public Object getAttribute(String name) { Object value = super.getAttribute(name); if (value instanceof String) { - xssCleaner.clean((String) value); + this.xssCleaner.clean((String) value); } return value; } @@ -92,7 +92,7 @@ public String getHeader(String name) { if (value == null) { return null; } - return xssCleaner.clean(value); + return this.xssCleaner.clean(value); } @Override @@ -101,7 +101,7 @@ public String getQueryString() { if (value == null) { return null; } - return xssCleaner.clean(value); + return this.xssCleaner.clean(value); } } diff --git a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonDeserializer.java b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonDeserializer.java index 052074f19..a97c5f1f1 100644 --- a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonDeserializer.java +++ b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonDeserializer.java @@ -63,7 +63,7 @@ public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOEx } // 29-Jun-2020, tatu: New! "Scalar from Object" (mostly for XML) if (t == JsonToken.START_OBJECT) { - return ctxt.extractScalarFromObject(p, this, _valueClass); + return ctxt.extractScalarFromObject(p, this, this._valueClass); } // allow coercions for other scalar types // 17-Jan-2018, tatu: Related to [databind#1853] avoid FIELD_NAME by ensuring it's @@ -72,14 +72,14 @@ public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOEx String text = p.getValueAsString(); return getCleanText(text); } - return (String) ctxt.handleUnexpectedToken(_valueClass, p); + return (String) ctxt.handleUnexpectedToken(this._valueClass, p); } private String getCleanText(String text) { if (text == null) { return null; } - return XssStateHolder.enabled() ? xssCleaner.clean(text) : text; + return XssStateHolder.enabled() ? this.xssCleaner.clean(text) : text; } } diff --git a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonSerializer.java b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonSerializer.java index ae222677c..e6df150a0 100644 --- a/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonSerializer.java +++ b/xss/ballcat-spring-boot-starter-xss/src/main/java/org/ballcat/xss/core/XssStringJsonSerializer.java @@ -47,7 +47,7 @@ public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvi if (value != null) { // 开启 Xss 才进行处理 if (XssStateHolder.enabled()) { - value = xssCleaner.clean(value); + value = this.xssCleaner.clean(value); } jsonGenerator.writeString(value); }