From ecf22c0630dba0c7b7ed2828d23135c140e604be Mon Sep 17 00:00:00 2001 From: yizhenqiang Date: Fri, 6 Dec 2024 18:04:55 +0800 Subject: [PATCH 1/5] Fix some minor issues discovered by PMD (Programming Mistake Detector) plugins --- .../org/apache/dubbo/common/io/Bytes.java | 50 ++---- .../dubbo/common/utils/AnnotationUtils.java | 17 +- .../common/utils/CompatibleTypeUtils.java | 24 +-- .../apache/dubbo/common/utils/IOUtils.java | 12 +- .../dubbo/config/ReferenceConfigBase.java | 31 ++-- .../dubbo/container/page/ResourceFilter.java | 17 +- .../support/AbstractMetadataReport.java | 169 +++++++----------- .../apache/dubbo/rpc/support/RpcUtils.java | 35 ++-- .../UnpackZookeeperInitializer.java | 38 ++-- 9 files changed, 160 insertions(+), 233 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java index 98007dffc7f..5f0a08eedf5 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java @@ -19,10 +19,10 @@ import org.apache.dubbo.common.utils.IOUtils; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Files; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Map; @@ -34,12 +34,10 @@ * CodecUtils. */ public class Bytes { - private static final String C64 = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. - private static final char[] - BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, - BASE64 = C64.toCharArray(); + private static final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. + + private static final char[] BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, BASE64 = C64.toCharArray(); private static final int MASK4 = 0x0f, MASK6 = 0x3f, MASK8 = 0xff; private static final Map DECODE_TABLE_MAP = new ConcurrentHashMap<>(); @@ -287,10 +285,8 @@ public static int bytes2int(byte[] b) { * @return int. */ public static int bytes2int(byte[] b, int off) { - return ((b[off + 3] & 0xFF) << 0) - + ((b[off + 2] & 0xFF) << 8) - + ((b[off + 1] & 0xFF) << 16) - + ((b[off + 0]) << 24); + return ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off + 0]) + << 24); } /** @@ -311,10 +307,8 @@ public static float bytes2float(byte[] b) { * @return int. */ public static float bytes2float(byte[] b, int off) { - int i = ((b[off + 3] & 0xFF) << 0) - + ((b[off + 2] & 0xFF) << 8) - + ((b[off + 1] & 0xFF) << 16) - + ((b[off + 0]) << 24); + int i = ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off + 0]) + << 24); return Float.intBitsToFloat(i); } @@ -336,14 +330,9 @@ public static long bytes2long(byte[] b) { * @return long. */ public static long bytes2long(byte[] b, int off) { - return ((b[off + 7] & 0xFFL) << 0) - + ((b[off + 6] & 0xFFL) << 8) - + ((b[off + 5] & 0xFFL) << 16) - + ((b[off + 4] & 0xFFL) << 24) - + ((b[off + 3] & 0xFFL) << 32) - + ((b[off + 2] & 0xFFL) << 40) - + ((b[off + 1] & 0xFFL) << 48) - + (((long) b[off + 0]) << 56); + return ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ( + (b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ( + (b[off + 1] & 0xFFL) << 48) + (((long) b[off + 0]) << 56); } /** @@ -364,14 +353,9 @@ public static double bytes2double(byte[] b) { * @return double. */ public static double bytes2double(byte[] b, int off) { - long j = ((b[off + 7] & 0xFFL) << 0) - + ((b[off + 6] & 0xFFL) << 8) - + ((b[off + 5] & 0xFFL) << 16) - + ((b[off + 4] & 0xFFL) << 24) - + ((b[off + 3] & 0xFFL) << 32) - + ((b[off + 2] & 0xFFL) << 40) - + ((b[off + 1] & 0xFFL) << 48) - + (((long) b[off + 0]) << 56); + long j = ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ( + (b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ( + (b[off + 1] & 0xFFL) << 48) + (((long) b[off + 0]) << 56); return Double.longBitsToDouble(j); } @@ -766,9 +750,7 @@ public static byte[] base642bytes(final String str, final int off, final int len b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); } else if (rem == 3) { - int c1 = indexOf(code, str.charAt(r++)), - c2 = indexOf(code, str.charAt(r++)), - c3 = indexOf(code, str.charAt(r++)); + int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)), c3 = indexOf(code, str.charAt(r++)); b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); @@ -844,7 +826,7 @@ public static byte[] getMD5(byte[] source) { * @return MD5 byte array. */ public static byte[] getMD5(File file) throws IOException { - InputStream is = new FileInputStream(file); + InputStream is = Files.newInputStream(file.toPath()); try { return getMD5(is); } finally { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java index e3e53216b98..c92ef508395 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java @@ -154,7 +154,7 @@ static T getAttribute(Annotation annotation, String... attributeNames) throw } // exclude string attribute default is empty - if ((attribute instanceof String) && ((String) attribute).length() == 0) { + if ((attribute instanceof String) && ((String) attribute).isEmpty()) { continue; } @@ -174,8 +174,9 @@ static T getAttribute(Annotation annotation, String... attributeNames) throw * @return the {@link Annotation} if found * @throws ClassCastException If the {@link Annotation annotation} type that client requires can't match actual type */ - static A getAnnotation(AnnotatedElement annotatedElement, String annotationClassName) - throws ClassCastException { + static A getAnnotation( + AnnotatedElement annotatedElement, + String annotationClassName) throws ClassCastException { Class annotationType = resolveAnnotationType(annotatedElement, annotationClassName); if (annotationType == null) { return null; @@ -259,13 +260,10 @@ static List getAllDeclaredAnnotations(Class type, Predicate getMetaAnnotations( Class annotationType, Predicate... metaAnnotationsToFilter) { - return getDeclaredAnnotations( - annotationType, + return getDeclaredAnnotations(annotationType, // Excludes the Java native annotation types or it causes the stack overflow, e.g, // @Target annotates itself - excludedType(Target.class), - excludedType(Retention.class), - excludedType(Documented.class), + excludedType(Target.class), excludedType(Retention.class), excludedType(Documented.class), // Add other predicates and(metaAnnotationsToFilter)); } @@ -522,6 +520,7 @@ static T getDefaultValue(Class annotationType, String /** * Filter default value of Annotation type + * * @param annotationType annotation type from {@link Annotation#annotationType()} * @param attributes * @return @@ -544,6 +543,7 @@ static Map filterDefaultValues( /** * Filter default value of Annotation type + * * @param annotation * @param attributes * @return @@ -554,6 +554,7 @@ static Map filterDefaultValues(Annotation annotation, Map type) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { - throw new IllegalArgumentException(String.format( - "CAN NOT convert String(%s) to char!" - + " when convert String to char, the String MUST only 1 char.", - string)); + throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } @@ -80,13 +78,13 @@ public static Object compatibleTypeConvert(Object value, Class type) { return new BigDecimal(string); } if (type == Short.class || type == short.class) { - return new Short(string); + return Short.valueOf(string); } if (type == Integer.class || type == int.class) { - return new Integer(string); + return Integer.valueOf(string); } if (type == Long.class || type == long.class) { - return new Long(string); + return Long.valueOf(string); } if (type == Double.class || type == double.class) { return new Double(string); @@ -95,14 +93,12 @@ public static Object compatibleTypeConvert(Object value, Class type) { return new Float(string); } if (type == Byte.class || type == byte.class) { - return new Byte(string); + return Byte.valueOf(string); } if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } - if (type == Date.class - || type == java.sql.Date.class - || type == java.sql.Timestamp.class + if (type == Date.class || type == java.sql.Date.class || type == java.sql.Timestamp.class || type == java.sql.Time.class) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); @@ -119,8 +115,7 @@ public static Object compatibleTypeConvert(Object value, Class type) { } catch (ParseException e) { throw new IllegalStateException( "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " - + e.getMessage(), - e); + + e.getMessage(), e); } } if (type == java.time.LocalDateTime.class) { @@ -209,8 +204,7 @@ public static Object compatibleTypeConvert(Object value, Class type) { } if (!type.isInterface()) { try { - Collection result = - (Collection) type.getDeclaredConstructor().newInstance(); + Collection result = (Collection) type.getDeclaredConstructor().newInstance(); result.addAll(collection); return result; } catch (Throwable ignored) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java index c2ee5587b3b..e7fca493062 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java @@ -36,6 +36,7 @@ import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; +import java.nio.file.Files; import java.util.ArrayList; import java.util.List; @@ -46,6 +47,7 @@ * @since 2.0.7 */ public class IOUtils { + private static final int BUFFER_SIZE = 1024 * 8; public static final int EOF = -1; @@ -86,8 +88,10 @@ public static long write(InputStream is, OutputStream os, int bufferSize) throws * @return count. * @throws IOException If an I/O error occurs */ - public static long write(final InputStream input, final OutputStream output, final byte[] buffer) - throws IOException { + public static long write( + final InputStream input, + final OutputStream output, + final byte[] buffer) throws IOException { long count = 0; int n; while (EOF != (n = input.read(buffer))) { @@ -168,7 +172,7 @@ public static String[] readLines(File file) throws IOException { return new String[0]; } - return readLines(new FileInputStream(file)); + return readLines(Files.newInputStream(file.toPath())); } /** @@ -228,7 +232,7 @@ public static void writeLines(File file, String[] lines) throws IOException { if (file == null) { throw new IOException("File is null."); } - writeLines(new FileOutputStream(file), lines); + writeLines(Files.newOutputStream(file.toPath()), lines); } /** diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java index da1b9bc831e..2e4f0892255 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java @@ -135,8 +135,7 @@ public boolean shouldInit() { protected void preProcessRefresh() { super.preProcessRefresh(); if (consumer == null) { - consumer = getModuleConfigManager() - .getDefaultConsumer() + consumer = getModuleConfigManager().getDefaultConsumer() .orElseThrow(() -> new IllegalStateException("Default consumer is not initialized")); } // try set properties from `dubbo.reference` if not set in current config @@ -230,9 +229,8 @@ public static Class determineInterfaceClass(String generic, String interfaceN public static Class determineInterfaceClass(String generic, String interfaceName, ClassLoader classLoader) { if (ProtocolUtils.isGeneric(generic)) { - return Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded() - ? Dubbo2CompactUtils.getGenericServiceClass() - : GenericService.class; + return Dubbo2CompactUtils.isEnabled() + && Dubbo2CompactUtils.isGenericServiceClassLoaded() ? Dubbo2CompactUtils.getGenericServiceClass() : GenericService.class; } try { if (StringUtils.isNotEmpty(interfaceName)) { @@ -263,8 +261,7 @@ public void setInterface(Class interfaceClass) { } else { if (interfaceClass != null) { try { - if (!interfaceClass.equals( - Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) { + if (!interfaceClass.equals(Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) { // interfaceClass is not visible from origin classloader, override the classloader from // interfaceClass into referenceConfig setInterfaceClassLoader(interfaceClass.getClassLoader()); @@ -315,13 +312,12 @@ protected void resolveFile() { if (StringUtils.isEmpty(resolve)) { resolveFile = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_RESOLVE_FILE); if (StringUtils.isEmpty(resolveFile)) { - File userResolveFile = new File( - new File(SystemPropertyConfigUtils.getSystemProperty(USER_HOME)), "dubbo-resolve.properties"); + File userResolveFile = new File(new File(SystemPropertyConfigUtils.getSystemProperty(USER_HOME)), "dubbo-resolve.properties"); if (userResolveFile.exists()) { resolveFile = userResolveFile.getAbsolutePath(); } } - if (resolveFile != null && resolveFile.length() > 0) { + if (resolveFile != null && !resolveFile.isEmpty()) { Properties properties = new RegexProperties(); try (FileInputStream fis = new FileInputStream(resolveFile)) { properties.load(fis); @@ -336,17 +332,11 @@ protected void resolveFile() { url = resolve; if (logger.isWarnEnabled()) { if (resolveFile != null) { - logger.warn( - COMMON_UNEXPECTED_EXCEPTION, - "", - "", + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); } else { - logger.warn( - COMMON_UNEXPECTED_EXCEPTION, - "", - "", + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", "Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); } } @@ -369,9 +359,8 @@ public String getUniqueServiceName() { @Override public String getVersion() { - return StringUtils.isEmpty(this.version) - ? (consumer != null ? consumer.getVersion() : this.version) - : this.version; + return StringUtils.isEmpty(this.version) ? ( + consumer != null ? consumer.getVersion() : this.version) : this.version; } @Override diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java index 981508e4aeb..ed6b5b67e07 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java @@ -27,11 +27,12 @@ import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @@ -50,10 +51,10 @@ public class ResourceFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { String config = filterConfig.getInitParameter("resources"); - if (config != null && config.length() > 0) { + if (config != null && !config.isEmpty()) { String[] configs = Constants.COMMA_SPLIT_PATTERN.split(config); for (String c : configs) { - if (c != null && c.length() > 0) { + if (c != null && !c.isEmpty()) { c = c.replace('\\', '/'); if (c.endsWith("/")) { c = c.substring(0, c.length() - 1); @@ -66,8 +67,10 @@ public void init(FilterConfig filterConfig) throws ServletException { public void destroy() {} - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) - throws IOException, ServletException { + public void doFilter( + ServletRequest req, + ServletResponse res, + FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (response.isCommitted()) { @@ -118,7 +121,7 @@ private boolean isFile(String path) { private long getLastModified(String uri) { for (String resource : resources) { - if (resource != null && resource.length() > 0) { + if (resource != null && !resource.isEmpty()) { String path = resource + uri; if (isFile(path)) { File file = new File(path); @@ -136,7 +139,7 @@ private InputStream getInputStream(String uri) { String path = resource + uri; try { if (isFile(path)) { - return new FileInputStream(path); + return Files.newInputStream(Paths.get(path)); } else if (path.startsWith(CLASSPATH_PREFIX)) { return Thread.currentThread() .getContextClassLoader() diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index f21e99b3dfd..6e580655583 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -36,13 +36,13 @@ import org.apache.dubbo.rpc.model.ApplicationModel; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; @@ -93,8 +93,7 @@ public abstract class AbstractMetadataReport implements MetadataReport { // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are // the list of notified service providers final Properties properties = new Properties(); - private final ExecutorService reportCacheExecutor = - Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); + private final ExecutorService reportCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); final Map allMetadataReports = new ConcurrentHashMap<>(4); private final AtomicLong lastCacheChanged = new AtomicLong(); @@ -118,19 +117,16 @@ public AbstractMetadataReport(URL reportServerURL) { boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true); // Start file save timer String defaultFilename = SystemPropertyConfigUtils.getSystemProperty(USER_HOME) + DUBBO_METADATA - + reportServerURL.getApplication() - + "-" + replace(reportServerURL.getAddress(), ":", "-") - + CACHE; + + reportServerURL.getApplication() + "-" + replace(reportServerURL.getAddress(), ":", "-") + CACHE; String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename); File file = null; if (localCacheEnabled && ConfigUtils.isNotEmpty(filename)) { file = new File(filename); - if (!file.exists() - && file.getParentFile() != null - && !file.getParentFile().exists()) { + if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { - throw new IllegalArgumentException("Invalid service store file " + file - + ", cause: Failed to create directory " + file.getParentFile() + "!"); + throw new IllegalArgumentException( + "Invalid service store file " + file + ", cause: Failed to create directory " + + file.getParentFile() + "!"); } } // if this file exists, firstly delete it. @@ -141,15 +137,11 @@ public AbstractMetadataReport(URL reportServerURL) { this.file = file; loadProperties(); syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false); - metadataReportRetry = new MetadataReportRetry( - reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), - reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); + metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); // cycle report the data switch if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) { - reportTimerScheduler = Executors.newSingleThreadScheduledExecutor( - new NamedThreadFactory("DubboMetadataReportTimer", true)); - reportTimerScheduler.scheduleAtFixedRate( - this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); + reportTimerScheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true)); + reportTimerScheduler.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); } this.reportMetadata = reportServerURL.getParameter(REPORT_METADATA_KEY, false); @@ -180,13 +172,11 @@ private void doSaveProperties(long version) { if (!lockfile.exists()) { lockfile.createNewFile(); } - try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); - FileChannel channel = raf.getChannel()) { + try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { - throw new IOException( - "Can not lock the metadataReport cache file " + file.getAbsolutePath() - + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); + throw new IOException("Can not lock the metadataReport cache file " + file.getAbsolutePath() + + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); } // Save try { @@ -222,18 +212,14 @@ private void doSaveProperties(long version) { } else { reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } - logger.warn( - COMMON_UNEXPECTED_EXCEPTION, - "", - "", - "Failed to save service store file, cause: " + e.getMessage(), - e); + logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", + "Failed to save service store file, cause: " + e.getMessage(), e); } } void loadProperties() { if (file != null && file.exists()) { - try (InputStream in = new FileInputStream(file)) { + try (InputStream in = Files.newInputStream(file.toPath())) { properties.load(in); if (logger.isInfoEnabled()) { logger.info("Load service store file " + file + ", data: " + properties); @@ -273,6 +259,7 @@ public String toString() { } private class SaveProperties implements Runnable { + private long version; private SaveProperties(long version) { @@ -298,38 +285,30 @@ public void storeProviderMetadata( private void storeProviderMetadataTask( MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent( - applicationModel, providerMetadataIdentifier.getUniqueServiceName()); - MetricsEventBus.post( - metadataEvent, - () -> { - boolean result = true; - try { - if (logger.isInfoEnabled()) { - logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier - + "; definition: " + serviceDefinition); - } - allMetadataReports.put(providerMetadataIdentifier, serviceDefinition); - failedReports.remove(providerMetadataIdentifier); - String data = JsonUtils.toJson(serviceDefinition); - doStoreProviderMetadata(providerMetadataIdentifier, data); - saveProperties(providerMetadataIdentifier, data, true, !syncReport); - } catch (Exception e) { - // retry again. If failed again, throw exception. - failedReports.put(providerMetadataIdentifier, serviceDefinition); - metadataReportRetry.startRetryTask(); - logger.error( - PROXY_FAILED_EXPORT_SERVICE, - "", - "", - "Failed to put provider metadata " + providerMetadataIdentifier + " in " - + serviceDefinition + ", cause: " + e.getMessage(), - e); - result = false; - } - return result; - }, - aBoolean -> aBoolean); + MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); + MetricsEventBus.post(metadataEvent, () -> { + boolean result = true; + try { + if (logger.isInfoEnabled()) { + logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + "; definition: " + + serviceDefinition); + } + allMetadataReports.put(providerMetadataIdentifier, serviceDefinition); + failedReports.remove(providerMetadataIdentifier); + String data = JsonUtils.toJson(serviceDefinition); + doStoreProviderMetadata(providerMetadataIdentifier, data); + saveProperties(providerMetadataIdentifier, data, true, !syncReport); + } catch (Exception e) { + // retry again. If failed again, throw exception. + failedReports.put(providerMetadataIdentifier, serviceDefinition); + metadataReportRetry.startRetryTask(); + logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", + "Failed to put provider metadata " + providerMetadataIdentifier + " in " + serviceDefinition + + ", cause: " + e.getMessage(), e); + result = false; + } + return result; + }, aBoolean -> aBoolean); } @Override @@ -338,8 +317,7 @@ public void storeConsumerMetadata( if (syncReport) { storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap); } else { - reportCacheExecutor.execute( - () -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); + reportCacheExecutor.execute(() -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); } } @@ -360,13 +338,9 @@ protected void storeConsumerMetadataTask( // retry again. If failed again, throw exception. failedReports.put(consumerMetadataIdentifier, serviceParameterMap); metadataReportRetry.startRetryTask(); - logger.error( - PROXY_FAILED_EXPORT_SERVICE, - "", - "", + logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", "Failed to put consumer metadata " + consumerMetadataIdentifier + "; " + serviceParameterMap - + ", cause: " + e.getMessage(), - e); + + ", cause: " + e.getMessage(), e); } } @@ -413,8 +387,7 @@ public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataId if (syncReport) { doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls)); } else { - reportCacheExecutor.execute( - () -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls))); + reportCacheExecutor.execute(() -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls))); } } @@ -451,8 +424,7 @@ private boolean doHandleMetadataCollection(Map metad if (metadataMap.isEmpty()) { return true; } - Iterator> iterable = - metadataMap.entrySet().iterator(); + Iterator> iterable = metadataMap.entrySet().iterator(); while (iterable.hasNext()) { Map.Entry item = iterable.next(); if (PROVIDER_SIDE.equals(item.getKey().getSide())) { @@ -485,16 +457,15 @@ long calculateStartTime() { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long subtract = calendar.getTimeInMillis() + ONE_DAY_IN_MILLISECONDS - nowMill; - return subtract - + (FOUR_HOURS_IN_MILLISECONDS / 2) - + ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS); + return subtract + (FOUR_HOURS_IN_MILLISECONDS / 2) + ThreadLocalRandom.current() + .nextInt(FOUR_HOURS_IN_MILLISECONDS); } class MetadataReportRetry { + protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - final ScheduledExecutorService retryExecutor = - Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true)); + final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true)); volatile ScheduledFuture retryScheduledFuture; final AtomicInteger retryCounter = new AtomicInteger(0); // retry task schedule period @@ -513,30 +484,22 @@ void startRetryTask() { if (retryScheduledFuture == null) { synchronized (retryCounter) { if (retryScheduledFuture == null) { - retryScheduledFuture = retryExecutor.scheduleWithFixedDelay( - () -> { - // Check and connect to the metadata - try { - int times = retryCounter.incrementAndGet(); - logger.info("start to retry task for metadata report. retry times:" + times); - if (retry() && times > retryTimesIfNonFail) { - cancelRetryTask(); - } - if (times > retryLimit) { - cancelRetryTask(); - } - } catch (Throwable t) { // Defensive fault tolerance - logger.error( - COMMON_UNEXPECTED_EXCEPTION, - "", - "", - "Unexpected error occur at failed retry, cause: " + t.getMessage(), - t); - } - }, - 500, - retryPeriod, - TimeUnit.MILLISECONDS); + retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(() -> { + // Check and connect to the metadata + try { + int times = retryCounter.incrementAndGet(); + logger.info("start to retry task for metadata report. retry times:" + times); + if (retry() && times > retryTimesIfNonFail) { + cancelRetryTask(); + } + if (times > retryLimit) { + cancelRetryTask(); + } + } catch (Throwable t) { // Defensive fault tolerance + logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", + "Unexpected error occur at failed retry, cause: " + t.getMessage(), t); + } + }, 500, retryPeriod, TimeUnit.MILLISECONDS); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 228392fe021..631c221c507 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -60,11 +60,9 @@ public class RpcUtils { public static Class getReturnType(Invocation invocation) { try { - if (invocation != null - && invocation.getInvoker() != null - && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class - && !invocation.getMethodName().startsWith("$")) { + if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName() + .startsWith("$")) { String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); @@ -79,11 +77,9 @@ public static Class getReturnType(Invocation invocation) { public static Type[] getReturnTypes(Invocation invocation) { try { - if (invocation != null - && invocation.getInvoker() != null - && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class - && !invocation.getMethodName().startsWith("$")) { + if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName() + .startsWith("$")) { Type[] returnTypes = null; if (invocation instanceof RpcInvocation) { returnTypes = ((RpcInvocation) invocation).getReturnTypes(); @@ -110,7 +106,7 @@ public static Type[] getReturnTypes(Invocation invocation) { public static Long getInvocationId(Invocation inv) { String id = inv.getAttachment(ID_KEY); - return id == null ? null : new Long(id); + return id == null ? null : Long.valueOf(id); } /** @@ -136,8 +132,7 @@ private static boolean isAttachInvocationId(URL url, Invocation invocation) { public static String getMethodName(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation.getArguments() != null - && invocation.getArguments().length > 0 + && invocation.getArguments() != null && invocation.getArguments().length > 0 && invocation.getArguments()[0] instanceof String) { return (String) invocation.getArguments()[0]; } @@ -146,8 +141,7 @@ public static String getMethodName(Invocation invocation) { public static Object[] getArguments(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation.getArguments() != null - && invocation.getArguments().length > 2 + && invocation.getArguments() != null && invocation.getArguments().length > 2 && invocation.getArguments()[2] instanceof Object[]) { return (Object[]) invocation.getArguments()[2]; } @@ -156,8 +150,7 @@ public static Object[] getArguments(Invocation invocation) { public static Class[] getParameterTypes(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation.getArguments() != null - && invocation.getArguments().length > 1 + && invocation.getArguments() != null && invocation.getArguments().length > 1 && invocation.getArguments()[1] instanceof String[]) { String[] types = (String[]) invocation.getArguments()[1]; if (types == null) { @@ -244,9 +237,8 @@ public static boolean isOneway(URL url, Invocation inv) { private static Method getMethodByService(Invocation invocation, String service) throws NoSuchMethodException { Class invokerInterface = invocation.getInvoker().getInterface(); - Class cls = invokerInterface != null - ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) - : ReflectUtils.forName(service); + Class cls = invokerInterface + != null ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) : ReflectUtils.forName(service); Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); if (method.getReturnType() == void.class) { return null; @@ -287,8 +279,7 @@ public static int calculateTimeout(URL url, Invocation invocation, String method int timeout = (int) defaultTimeout; if (countdown == null) { if (url != null) { - timeout = (int) RpcUtils.getTimeout( - url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); + timeout = (int) RpcUtils.getTimeout(url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); if (url.getMethodParameter(methodName, ENABLE_TIMEOUT_COUNTDOWN_KEY, false)) { // pass timeout to remote server invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout); diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java index 209d0593bd3..316c8a3dd15 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java @@ -32,7 +32,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; -import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.io.IOUtils; /** * Unpack the downloaded zookeeper binary archive. @@ -52,14 +52,11 @@ private void unpack(ZookeeperContext context, int clientPort) throws DubboTestEx File sourceFile = context.getSourceFile().toFile(); Path targetPath = Paths.get(context.getSourceFile().getParent().toString(), String.valueOf(clientPort)); // check if it's unpacked. - if (targetPath.toFile() != null && targetPath.toFile().isDirectory()) { + if (targetPath.toFile().isDirectory()) { logger.info(String.format("The file has been unpacked, target path:%s", targetPath.toString())); return; } - try (FileInputStream fileInputStream = new FileInputStream(sourceFile); - GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); - TarArchiveInputStream tarArchiveInputStream = - new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) { + try (FileInputStream fileInputStream = new FileInputStream(sourceFile); GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) { File targetFile = targetPath.toFile(); TarArchiveEntry entry; while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) { @@ -87,28 +84,31 @@ protected void doInitialize(ZookeeperContext context) throws DubboTestException // get the file name, just like apache-zookeeper-{version}-bin // the version we maybe unknown if the zookeeper archive binary file is copied by user self. Path parentPath = Paths.get(context.getSourceFile().getParent().toString(), String.valueOf(clientPort)); - if (!Files.exists(parentPath) - || !parentPath.toFile().isDirectory() - || parentPath.toFile().listFiles().length != 1) { + if (!Files.exists(parentPath) || !parentPath.toFile().isDirectory()) { + throw new IllegalStateException("There is something wrong in unpacked file!"); + } + + File[] files = parentPath.toFile().listFiles(); + if (files == null || files.length != 1) { throw new IllegalStateException("There is something wrong in unpacked file!"); } // rename directory - File sourceFile = parentPath.toFile().listFiles()[0]; - File targetFile = Paths.get(parentPath.toString(), context.getUnpackedDirectory()) - .toFile(); + File sourceFile = files[0]; + File targetFile = Paths.get(parentPath.toString(), context.getUnpackedDirectory()).toFile(); sourceFile.renameTo(targetFile); if (!Files.exists(targetFile.toPath()) || !targetFile.isDirectory()) { - throw new IllegalStateException(String.format( - "Failed to rename the directory. source directory: %s, target directory: %s", - sourceFile.toPath().toString(), targetFile.toPath().toString())); + throw new IllegalStateException(String.format("Failed to rename the directory. source directory: %s, target directory: %s", sourceFile.toPath(), targetFile.toPath())); } // get the bin path Path zookeeperBin = Paths.get(targetFile.toString(), "bin"); // update file permission - for (File file : zookeeperBin.toFile().listFiles()) { - file.setExecutable(true, false); - file.setReadable(true, false); - file.setWritable(false, false); + File[] zookeeperBinFiles = zookeeperBin.toFile().listFiles(); + if (zookeeperBinFiles != null) { + for (File file : zookeeperBinFiles) { + file.setExecutable(true, false); + file.setReadable(true, false); + file.setWritable(false, false); + } } } } From f79be435c667892112ac2bd35514d833d693cccb Mon Sep 17 00:00:00 2001 From: yizhenqiang Date: Fri, 20 Dec 2024 13:05:28 +0800 Subject: [PATCH 2/5] Fix some minor issues discovered by PMD (Programming Mistake Detector) plugins --- .../org/apache/dubbo/common/io/Bytes.java | 46 +++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java index 5f0a08eedf5..9304b6c1c1f 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java @@ -34,10 +34,12 @@ * CodecUtils. */ public class Bytes { + private static final String C64 = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. - private static final String C64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // default base64. - - private static final char[] BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, BASE64 = C64.toCharArray(); + private static final char[] + BASE16 = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}, + BASE64 = C64.toCharArray(); private static final int MASK4 = 0x0f, MASK6 = 0x3f, MASK8 = 0xff; private static final Map DECODE_TABLE_MAP = new ConcurrentHashMap<>(); @@ -285,8 +287,10 @@ public static int bytes2int(byte[] b) { * @return int. */ public static int bytes2int(byte[] b, int off) { - return ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off + 0]) - << 24); + return ((b[off + 3] & 0xFF) << 0) + + ((b[off + 2] & 0xFF) << 8) + + ((b[off + 1] & 0xFF) << 16) + + ((b[off + 0]) << 24); } /** @@ -307,8 +311,10 @@ public static float bytes2float(byte[] b) { * @return int. */ public static float bytes2float(byte[] b, int off) { - int i = ((b[off + 3] & 0xFF) << 0) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off + 0]) - << 24); + int i = ((b[off + 3] & 0xFF) << 0) + + ((b[off + 2] & 0xFF) << 8) + + ((b[off + 1] & 0xFF) << 16) + + ((b[off + 0]) << 24); return Float.intBitsToFloat(i); } @@ -330,9 +336,14 @@ public static long bytes2long(byte[] b) { * @return long. */ public static long bytes2long(byte[] b, int off) { - return ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ( - (b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ( - (b[off + 1] & 0xFFL) << 48) + (((long) b[off + 0]) << 56); + return ((b[off + 7] & 0xFFL) << 0) + + ((b[off + 6] & 0xFFL) << 8) + + ((b[off + 5] & 0xFFL) << 16) + + ((b[off + 4] & 0xFFL) << 24) + + ((b[off + 3] & 0xFFL) << 32) + + ((b[off + 2] & 0xFFL) << 40) + + ((b[off + 1] & 0xFFL) << 48) + + (((long) b[off + 0]) << 56); } /** @@ -353,9 +364,14 @@ public static double bytes2double(byte[] b) { * @return double. */ public static double bytes2double(byte[] b, int off) { - long j = ((b[off + 7] & 0xFFL) << 0) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ( - (b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ( - (b[off + 1] & 0xFFL) << 48) + (((long) b[off + 0]) << 56); + long j = ((b[off + 7] & 0xFFL) << 0) + + ((b[off + 6] & 0xFFL) << 8) + + ((b[off + 5] & 0xFFL) << 16) + + ((b[off + 4] & 0xFFL) << 24) + + ((b[off + 3] & 0xFFL) << 32) + + ((b[off + 2] & 0xFFL) << 40) + + ((b[off + 1] & 0xFFL) << 48) + + (((long) b[off + 0]) << 56); return Double.longBitsToDouble(j); } @@ -750,7 +766,9 @@ public static byte[] base642bytes(final String str, final int off, final int len b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); } else if (rem == 3) { - int c1 = indexOf(code, str.charAt(r++)), c2 = indexOf(code, str.charAt(r++)), c3 = indexOf(code, str.charAt(r++)); + int c1 = indexOf(code, str.charAt(r++)), + c2 = indexOf(code, str.charAt(r++)), + c3 = indexOf(code, str.charAt(r++)); b[w++] = (byte) ((c1 << 2) | (c2 >> 4)); b[w++] = (byte) ((c2 << 4) | (c3 >> 2)); From ff492e246ee52882e864fe1c4c6117c5e3f37c1d Mon Sep 17 00:00:00 2001 From: yizhenqiang Date: Fri, 20 Dec 2024 13:15:07 +0800 Subject: [PATCH 3/5] Fix some minor issues discovered by PMD (Programming Mistake Detector) plugins --- .../dubbo/common/utils/AnnotationUtils.java | 15 +- .../common/utils/CompatibleTypeUtils.java | 13 +- .../apache/dubbo/common/utils/IOUtils.java | 7 +- .../dubbo/config/ReferenceConfigBase.java | 29 ++- .../dubbo/container/page/ResourceFilter.java | 6 +- .../support/AbstractMetadataReport.java | 165 +++++++++++------- .../apache/dubbo/rpc/support/RpcUtils.java | 33 ++-- .../UnpackZookeeperInitializer.java | 5 +- 8 files changed, 166 insertions(+), 107 deletions(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java index c92ef508395..0c59d7232bf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/AnnotationUtils.java @@ -174,9 +174,8 @@ static T getAttribute(Annotation annotation, String... attributeNames) throw * @return the {@link Annotation} if found * @throws ClassCastException If the {@link Annotation annotation} type that client requires can't match actual type */ - static A getAnnotation( - AnnotatedElement annotatedElement, - String annotationClassName) throws ClassCastException { + static A getAnnotation(AnnotatedElement annotatedElement, String annotationClassName) + throws ClassCastException { Class annotationType = resolveAnnotationType(annotatedElement, annotationClassName); if (annotationType == null) { return null; @@ -260,10 +259,13 @@ static List getAllDeclaredAnnotations(Class type, Predicate getMetaAnnotations( Class annotationType, Predicate... metaAnnotationsToFilter) { - return getDeclaredAnnotations(annotationType, + return getDeclaredAnnotations( + annotationType, // Excludes the Java native annotation types or it causes the stack overflow, e.g, // @Target annotates itself - excludedType(Target.class), excludedType(Retention.class), excludedType(Documented.class), + excludedType(Target.class), + excludedType(Retention.class), + excludedType(Documented.class), // Add other predicates and(metaAnnotationsToFilter)); } @@ -520,7 +522,6 @@ static T getDefaultValue(Class annotationType, String /** * Filter default value of Annotation type - * * @param annotationType annotation type from {@link Annotation#annotationType()} * @param attributes * @return @@ -543,7 +544,6 @@ static Map filterDefaultValues( /** * Filter default value of Annotation type - * * @param annotation * @param attributes * @return @@ -554,7 +554,6 @@ static Map filterDefaultValues(Annotation annotation, Map type) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { - throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" - + " when convert String to char, the String MUST only 1 char.", string)); + throw new IllegalArgumentException(String.format( + "CAN NOT convert String(%s) to char!" + + " when convert String to char, the String MUST only 1 char.", + string)); } return string.charAt(0); } @@ -98,7 +100,9 @@ public static Object compatibleTypeConvert(Object value, Class type) { if (type == Boolean.class || type == boolean.class) { return Boolean.valueOf(string); } - if (type == Date.class || type == java.sql.Date.class || type == java.sql.Timestamp.class + if (type == Date.class + || type == java.sql.Date.class + || type == java.sql.Timestamp.class || type == java.sql.Time.class) { try { Date date = new SimpleDateFormat(DATE_FORMAT).parse(string); @@ -204,7 +208,8 @@ public static Object compatibleTypeConvert(Object value, Class type) { } if (!type.isInterface()) { try { - Collection result = (Collection) type.getDeclaredConstructor().newInstance(); + Collection result = + (Collection) type.getDeclaredConstructor().newInstance(); result.addAll(collection); return result; } catch (Throwable ignored) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java index e7fca493062..d7f93cc7764 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java @@ -47,7 +47,6 @@ * @since 2.0.7 */ public class IOUtils { - private static final int BUFFER_SIZE = 1024 * 8; public static final int EOF = -1; @@ -88,10 +87,8 @@ public static long write(InputStream is, OutputStream os, int bufferSize) throws * @return count. * @throws IOException If an I/O error occurs */ - public static long write( - final InputStream input, - final OutputStream output, - final byte[] buffer) throws IOException { + public static long write(final InputStream input, final OutputStream output, final byte[] buffer) + throws IOException { long count = 0; int n; while (EOF != (n = input.read(buffer))) { diff --git a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java index 2e4f0892255..e1346b627c6 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/config/ReferenceConfigBase.java @@ -135,7 +135,8 @@ public boolean shouldInit() { protected void preProcessRefresh() { super.preProcessRefresh(); if (consumer == null) { - consumer = getModuleConfigManager().getDefaultConsumer() + consumer = getModuleConfigManager() + .getDefaultConsumer() .orElseThrow(() -> new IllegalStateException("Default consumer is not initialized")); } // try set properties from `dubbo.reference` if not set in current config @@ -229,8 +230,9 @@ public static Class determineInterfaceClass(String generic, String interfaceN public static Class determineInterfaceClass(String generic, String interfaceName, ClassLoader classLoader) { if (ProtocolUtils.isGeneric(generic)) { - return Dubbo2CompactUtils.isEnabled() - && Dubbo2CompactUtils.isGenericServiceClassLoaded() ? Dubbo2CompactUtils.getGenericServiceClass() : GenericService.class; + return Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isGenericServiceClassLoaded() + ? Dubbo2CompactUtils.getGenericServiceClass() + : GenericService.class; } try { if (StringUtils.isNotEmpty(interfaceName)) { @@ -261,7 +263,8 @@ public void setInterface(Class interfaceClass) { } else { if (interfaceClass != null) { try { - if (!interfaceClass.equals(Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) { + if (!interfaceClass.equals( + Class.forName(interfaceClass.getName(), false, getInterfaceClassLoader()))) { // interfaceClass is not visible from origin classloader, override the classloader from // interfaceClass into referenceConfig setInterfaceClassLoader(interfaceClass.getClassLoader()); @@ -312,7 +315,8 @@ protected void resolveFile() { if (StringUtils.isEmpty(resolve)) { resolveFile = SystemPropertyConfigUtils.getSystemProperty(CommonConstants.DubboProperty.DUBBO_RESOLVE_FILE); if (StringUtils.isEmpty(resolveFile)) { - File userResolveFile = new File(new File(SystemPropertyConfigUtils.getSystemProperty(USER_HOME)), "dubbo-resolve.properties"); + File userResolveFile = new File( + new File(SystemPropertyConfigUtils.getSystemProperty(USER_HOME)), "dubbo-resolve.properties"); if (userResolveFile.exists()) { resolveFile = userResolveFile.getAbsolutePath(); } @@ -332,11 +336,17 @@ protected void resolveFile() { url = resolve; if (logger.isWarnEnabled()) { if (resolveFile != null) { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", "Using default dubbo resolve file " + resolveFile + " replace " + interfaceName + "" + resolve + " to p2p invoke remote service."); } else { - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", "Using -D" + interfaceName + "=" + resolve + " to p2p invoke remote service."); } } @@ -359,8 +369,9 @@ public String getUniqueServiceName() { @Override public String getVersion() { - return StringUtils.isEmpty(this.version) ? ( - consumer != null ? consumer.getVersion() : this.version) : this.version; + return StringUtils.isEmpty(this.version) + ? (consumer != null ? consumer.getVersion() : this.version) + : this.version; } @Override diff --git a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java index ed6b5b67e07..abf79685952 100644 --- a/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java +++ b/dubbo-compatible/src/main/java/com/alibaba/dubbo/container/page/ResourceFilter.java @@ -67,10 +67,8 @@ public void init(FilterConfig filterConfig) throws ServletException { public void destroy() {} - public void doFilter( - ServletRequest req, - ServletResponse res, - FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (response.isCommitted()) { diff --git a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java index 6e580655583..76abbb1925a 100644 --- a/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java +++ b/dubbo-metadata/dubbo-metadata-api/src/main/java/org/apache/dubbo/metadata/report/support/AbstractMetadataReport.java @@ -93,7 +93,8 @@ public abstract class AbstractMetadataReport implements MetadataReport { // Local disk cache, where the special key value.registries records the list of metadata centers, and the others are // the list of notified service providers final Properties properties = new Properties(); - private final ExecutorService reportCacheExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); + private final ExecutorService reportCacheExecutor = + Executors.newFixedThreadPool(1, new NamedThreadFactory("DubboSaveMetadataReport", true)); final Map allMetadataReports = new ConcurrentHashMap<>(4); private final AtomicLong lastCacheChanged = new AtomicLong(); @@ -117,16 +118,19 @@ public AbstractMetadataReport(URL reportServerURL) { boolean localCacheEnabled = reportServerURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true); // Start file save timer String defaultFilename = SystemPropertyConfigUtils.getSystemProperty(USER_HOME) + DUBBO_METADATA - + reportServerURL.getApplication() + "-" + replace(reportServerURL.getAddress(), ":", "-") + CACHE; + + reportServerURL.getApplication() + + "-" + replace(reportServerURL.getAddress(), ":", "-") + + CACHE; String filename = reportServerURL.getParameter(FILE_KEY, defaultFilename); File file = null; if (localCacheEnabled && ConfigUtils.isNotEmpty(filename)) { file = new File(filename); - if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) { + if (!file.exists() + && file.getParentFile() != null + && !file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { - throw new IllegalArgumentException( - "Invalid service store file " + file + ", cause: Failed to create directory " - + file.getParentFile() + "!"); + throw new IllegalArgumentException("Invalid service store file " + file + + ", cause: Failed to create directory " + file.getParentFile() + "!"); } } // if this file exists, firstly delete it. @@ -137,11 +141,15 @@ public AbstractMetadataReport(URL reportServerURL) { this.file = file; loadProperties(); syncReport = reportServerURL.getParameter(SYNC_REPORT_KEY, false); - metadataReportRetry = new MetadataReportRetry(reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); + metadataReportRetry = new MetadataReportRetry( + reportServerURL.getParameter(RETRY_TIMES_KEY, DEFAULT_METADATA_REPORT_RETRY_TIMES), + reportServerURL.getParameter(RETRY_PERIOD_KEY, DEFAULT_METADATA_REPORT_RETRY_PERIOD)); // cycle report the data switch if (reportServerURL.getParameter(CYCLE_REPORT_KEY, DEFAULT_METADATA_REPORT_CYCLE_REPORT)) { - reportTimerScheduler = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboMetadataReportTimer", true)); - reportTimerScheduler.scheduleAtFixedRate(this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); + reportTimerScheduler = Executors.newSingleThreadScheduledExecutor( + new NamedThreadFactory("DubboMetadataReportTimer", true)); + reportTimerScheduler.scheduleAtFixedRate( + this::publishAll, calculateStartTime(), ONE_DAY_IN_MILLISECONDS, TimeUnit.MILLISECONDS); } this.reportMetadata = reportServerURL.getParameter(REPORT_METADATA_KEY, false); @@ -172,11 +180,13 @@ private void doSaveProperties(long version) { if (!lockfile.exists()) { lockfile.createNewFile(); } - try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); FileChannel channel = raf.getChannel()) { + try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); + FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { - throw new IOException("Can not lock the metadataReport cache file " + file.getAbsolutePath() - + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); + throw new IOException( + "Can not lock the metadataReport cache file " + file.getAbsolutePath() + + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.metadata.file=xxx.properties"); } // Save try { @@ -212,8 +222,12 @@ private void doSaveProperties(long version) { } else { reportCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } - logger.warn(COMMON_UNEXPECTED_EXCEPTION, "", "", - "Failed to save service store file, cause: " + e.getMessage(), e); + logger.warn( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Failed to save service store file, cause: " + e.getMessage(), + e); } } @@ -259,7 +273,6 @@ public String toString() { } private class SaveProperties implements Runnable { - private long version; private SaveProperties(long version) { @@ -285,30 +298,38 @@ public void storeProviderMetadata( private void storeProviderMetadataTask( MetadataIdentifier providerMetadataIdentifier, ServiceDefinition serviceDefinition) { - MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent(applicationModel, providerMetadataIdentifier.getUniqueServiceName()); - MetricsEventBus.post(metadataEvent, () -> { - boolean result = true; - try { - if (logger.isInfoEnabled()) { - logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + "; definition: " - + serviceDefinition); - } - allMetadataReports.put(providerMetadataIdentifier, serviceDefinition); - failedReports.remove(providerMetadataIdentifier); - String data = JsonUtils.toJson(serviceDefinition); - doStoreProviderMetadata(providerMetadataIdentifier, data); - saveProperties(providerMetadataIdentifier, data, true, !syncReport); - } catch (Exception e) { - // retry again. If failed again, throw exception. - failedReports.put(providerMetadataIdentifier, serviceDefinition); - metadataReportRetry.startRetryTask(); - logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", - "Failed to put provider metadata " + providerMetadataIdentifier + " in " + serviceDefinition - + ", cause: " + e.getMessage(), e); - result = false; - } - return result; - }, aBoolean -> aBoolean); + MetadataEvent metadataEvent = MetadataEvent.toServiceSubscribeEvent( + applicationModel, providerMetadataIdentifier.getUniqueServiceName()); + MetricsEventBus.post( + metadataEvent, + () -> { + boolean result = true; + try { + if (logger.isInfoEnabled()) { + logger.info("store provider metadata. Identifier : " + providerMetadataIdentifier + + "; definition: " + serviceDefinition); + } + allMetadataReports.put(providerMetadataIdentifier, serviceDefinition); + failedReports.remove(providerMetadataIdentifier); + String data = JsonUtils.toJson(serviceDefinition); + doStoreProviderMetadata(providerMetadataIdentifier, data); + saveProperties(providerMetadataIdentifier, data, true, !syncReport); + } catch (Exception e) { + // retry again. If failed again, throw exception. + failedReports.put(providerMetadataIdentifier, serviceDefinition); + metadataReportRetry.startRetryTask(); + logger.error( + PROXY_FAILED_EXPORT_SERVICE, + "", + "", + "Failed to put provider metadata " + providerMetadataIdentifier + " in " + + serviceDefinition + ", cause: " + e.getMessage(), + e); + result = false; + } + return result; + }, + aBoolean -> aBoolean); } @Override @@ -317,7 +338,8 @@ public void storeConsumerMetadata( if (syncReport) { storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap); } else { - reportCacheExecutor.execute(() -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); + reportCacheExecutor.execute( + () -> storeConsumerMetadataTask(consumerMetadataIdentifier, serviceParameterMap)); } } @@ -338,9 +360,13 @@ protected void storeConsumerMetadataTask( // retry again. If failed again, throw exception. failedReports.put(consumerMetadataIdentifier, serviceParameterMap); metadataReportRetry.startRetryTask(); - logger.error(PROXY_FAILED_EXPORT_SERVICE, "", "", + logger.error( + PROXY_FAILED_EXPORT_SERVICE, + "", + "", "Failed to put consumer metadata " + consumerMetadataIdentifier + "; " + serviceParameterMap - + ", cause: " + e.getMessage(), e); + + ", cause: " + e.getMessage(), + e); } } @@ -387,7 +413,8 @@ public void saveSubscribedData(SubscriberMetadataIdentifier subscriberMetadataId if (syncReport) { doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls)); } else { - reportCacheExecutor.execute(() -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls))); + reportCacheExecutor.execute( + () -> doSaveSubscriberData(subscriberMetadataIdentifier, JsonUtils.toJson(urls))); } } @@ -424,7 +451,8 @@ private boolean doHandleMetadataCollection(Map metad if (metadataMap.isEmpty()) { return true; } - Iterator> iterable = metadataMap.entrySet().iterator(); + Iterator> iterable = + metadataMap.entrySet().iterator(); while (iterable.hasNext()) { Map.Entry item = iterable.next(); if (PROVIDER_SIDE.equals(item.getKey().getSide())) { @@ -457,15 +485,16 @@ long calculateStartTime() { calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long subtract = calendar.getTimeInMillis() + ONE_DAY_IN_MILLISECONDS - nowMill; - return subtract + (FOUR_HOURS_IN_MILLISECONDS / 2) + ThreadLocalRandom.current() - .nextInt(FOUR_HOURS_IN_MILLISECONDS); + return subtract + + (FOUR_HOURS_IN_MILLISECONDS / 2) + + ThreadLocalRandom.current().nextInt(FOUR_HOURS_IN_MILLISECONDS); } class MetadataReportRetry { - protected final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); - final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true)); + final ScheduledExecutorService retryExecutor = + Executors.newScheduledThreadPool(0, new NamedThreadFactory("DubboMetadataReportRetryTimer", true)); volatile ScheduledFuture retryScheduledFuture; final AtomicInteger retryCounter = new AtomicInteger(0); // retry task schedule period @@ -484,22 +513,30 @@ void startRetryTask() { if (retryScheduledFuture == null) { synchronized (retryCounter) { if (retryScheduledFuture == null) { - retryScheduledFuture = retryExecutor.scheduleWithFixedDelay(() -> { - // Check and connect to the metadata - try { - int times = retryCounter.incrementAndGet(); - logger.info("start to retry task for metadata report. retry times:" + times); - if (retry() && times > retryTimesIfNonFail) { - cancelRetryTask(); - } - if (times > retryLimit) { - cancelRetryTask(); - } - } catch (Throwable t) { // Defensive fault tolerance - logger.error(COMMON_UNEXPECTED_EXCEPTION, "", "", - "Unexpected error occur at failed retry, cause: " + t.getMessage(), t); - } - }, 500, retryPeriod, TimeUnit.MILLISECONDS); + retryScheduledFuture = retryExecutor.scheduleWithFixedDelay( + () -> { + // Check and connect to the metadata + try { + int times = retryCounter.incrementAndGet(); + logger.info("start to retry task for metadata report. retry times:" + times); + if (retry() && times > retryTimesIfNonFail) { + cancelRetryTask(); + } + if (times > retryLimit) { + cancelRetryTask(); + } + } catch (Throwable t) { // Defensive fault tolerance + logger.error( + COMMON_UNEXPECTED_EXCEPTION, + "", + "", + "Unexpected error occur at failed retry, cause: " + t.getMessage(), + t); + } + }, + 500, + retryPeriod, + TimeUnit.MILLISECONDS); } } } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java index 631c221c507..5b3c2d1ab15 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/RpcUtils.java @@ -60,9 +60,11 @@ public class RpcUtils { public static Class getReturnType(Invocation invocation) { try { - if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName() - .startsWith("$")) { + if (invocation != null + && invocation.getInvoker() != null + && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class + && !invocation.getMethodName().startsWith("$")) { String service = invocation.getInvoker().getUrl().getServiceInterface(); if (StringUtils.isNotEmpty(service)) { Method method = getMethodByService(invocation, service); @@ -77,9 +79,11 @@ public static Class getReturnType(Invocation invocation) { public static Type[] getReturnTypes(Invocation invocation) { try { - if (invocation != null && invocation.getInvoker() != null && invocation.getInvoker().getUrl() != null - && invocation.getInvoker().getInterface() != GenericService.class && !invocation.getMethodName() - .startsWith("$")) { + if (invocation != null + && invocation.getInvoker() != null + && invocation.getInvoker().getUrl() != null + && invocation.getInvoker().getInterface() != GenericService.class + && !invocation.getMethodName().startsWith("$")) { Type[] returnTypes = null; if (invocation instanceof RpcInvocation) { returnTypes = ((RpcInvocation) invocation).getReturnTypes(); @@ -132,7 +136,8 @@ private static boolean isAttachInvocationId(URL url, Invocation invocation) { public static String getMethodName(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation.getArguments() != null && invocation.getArguments().length > 0 + && invocation.getArguments() != null + && invocation.getArguments().length > 0 && invocation.getArguments()[0] instanceof String) { return (String) invocation.getArguments()[0]; } @@ -141,7 +146,8 @@ public static String getMethodName(Invocation invocation) { public static Object[] getArguments(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation.getArguments() != null && invocation.getArguments().length > 2 + && invocation.getArguments() != null + && invocation.getArguments().length > 2 && invocation.getArguments()[2] instanceof Object[]) { return (Object[]) invocation.getArguments()[2]; } @@ -150,7 +156,8 @@ public static Object[] getArguments(Invocation invocation) { public static Class[] getParameterTypes(Invocation invocation) { if (($INVOKE.equals(invocation.getMethodName()) || $INVOKE_ASYNC.equals(invocation.getMethodName())) - && invocation.getArguments() != null && invocation.getArguments().length > 1 + && invocation.getArguments() != null + && invocation.getArguments().length > 1 && invocation.getArguments()[1] instanceof String[]) { String[] types = (String[]) invocation.getArguments()[1]; if (types == null) { @@ -237,8 +244,9 @@ public static boolean isOneway(URL url, Invocation inv) { private static Method getMethodByService(Invocation invocation, String service) throws NoSuchMethodException { Class invokerInterface = invocation.getInvoker().getInterface(); - Class cls = invokerInterface - != null ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) : ReflectUtils.forName(service); + Class cls = invokerInterface != null + ? ReflectUtils.forName(invokerInterface.getClassLoader(), service) + : ReflectUtils.forName(service); Method method = cls.getMethod(invocation.getMethodName(), invocation.getParameterTypes()); if (method.getReturnType() == void.class) { return null; @@ -279,7 +287,8 @@ public static int calculateTimeout(URL url, Invocation invocation, String method int timeout = (int) defaultTimeout; if (countdown == null) { if (url != null) { - timeout = (int) RpcUtils.getTimeout(url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); + timeout = (int) RpcUtils.getTimeout( + url, methodName, RpcContext.getClientAttachment(), invocation, defaultTimeout); if (url.getMethodParameter(methodName, ENABLE_TIMEOUT_COUNTDOWN_KEY, false)) { // pass timeout to remote server invocation.setObjectAttachment(TIMEOUT_ATTACHMENT_KEY, timeout); diff --git a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java index 316c8a3dd15..2b58e6f9e8c 100644 --- a/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java +++ b/dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/registrycenter/initializer/UnpackZookeeperInitializer.java @@ -56,7 +56,10 @@ private void unpack(ZookeeperContext context, int clientPort) throws DubboTestEx logger.info(String.format("The file has been unpacked, target path:%s", targetPath.toString())); return; } - try (FileInputStream fileInputStream = new FileInputStream(sourceFile); GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) { + try (FileInputStream fileInputStream = new FileInputStream(sourceFile); + GzipCompressorInputStream gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream); + TarArchiveInputStream tarArchiveInputStream = + new TarArchiveInputStream(gzipCompressorInputStream, "UTF-8")) { File targetFile = targetPath.toFile(); TarArchiveEntry entry; while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) { From 5f166e6610ecaadcd9dfd983ebeee1910c80c3cf Mon Sep 17 00:00:00 2001 From: yizhenqiang Date: Thu, 9 Jan 2025 17:18:12 +0800 Subject: [PATCH 4/5] Fix some minor issues discovered by PMD (Programming Mistake Detector) plugins --- .../org/apache/dubbo/common/utils/CompatibleTypeUtils.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java index 66cbc3f93d9..e145da6c2d4 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/CompatibleTypeUtils.java @@ -119,7 +119,8 @@ public static Object compatibleTypeConvert(Object value, Class type) { } catch (ParseException e) { throw new IllegalStateException( "Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " - + e.getMessage(), e); + + e.getMessage(), + e); } } if (type == java.time.LocalDateTime.class) { From 9cf65101146083718ed7c9595f1fed4ec90f906b Mon Sep 17 00:00:00 2001 From: yizhenqiang Date: Tue, 14 Jan 2025 20:21:34 +0800 Subject: [PATCH 5/5] Fix some minor issues discovered by PMD (Programming Mistake Detector) plugins --- .../src/main/java/org/apache/dubbo/common/utils/IOUtils.java | 1 - 1 file changed, 1 deletion(-) diff --git a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java index d7f93cc7764..0a8feea7ecf 100644 --- a/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java +++ b/dubbo-common/src/main/java/org/apache/dubbo/common/utils/IOUtils.java @@ -21,7 +21,6 @@ import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException;