Skip to content

Commit

Permalink
[ISSUE #9047] optimize code format and reduce some methods cognitive …
Browse files Browse the repository at this point in the history
…complexity
  • Loading branch information
i36lib committed Dec 13, 2024
1 parent 9aa081b commit c20d145
Show file tree
Hide file tree
Showing 18 changed files with 240 additions and 214 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public SessionCredentials() {
try {
keyContent = MixAll.file2String(KEY_FILE);
} catch (IOException ignore) {
// NO Sonar
}
if (keyContent != null) {
Properties prop = MixAll.string2Properties(keyContent);
Expand Down
222 changes: 117 additions & 105 deletions common/src/main/java/org/apache/rocketmq/common/MixAll.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public abstract class ServiceThread implements Runnable {

protected Thread thread;
protected final CountDownLatch2 waitPoint = new CountDownLatch2(1);
protected volatile AtomicBoolean hasNotified = new AtomicBoolean(false);
protected AtomicBoolean hasNotified = new AtomicBoolean(false);
protected volatile boolean stopped = false;
protected boolean isDaemon = false;

Expand Down
76 changes: 38 additions & 38 deletions common/src/main/java/org/apache/rocketmq/common/UtilAll.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,34 +31,38 @@
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.List;
import java.util.Objects;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.zip.CRC32;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import java.util.Collections;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;

public class UtilAll {
private UtilAll() {
// Prevent class from being instantiated from outside
}
private static final Logger log = LoggerFactory.getLogger(LoggerName.COMMON_LOGGER_NAME);
private static final Logger STORE_LOG = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);

public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_SSS = "yyyy-MM-dd#HH:mm:ss:SSS";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
private final static char[] HEX_ARRAY;
private final static int PID;
private static final char[] HEX_ARRAY;
private static final int PID;

static {
HEX_ARRAY = "0123456789ABCDEF".toCharArray();
Expand Down Expand Up @@ -88,8 +92,8 @@ public static void sleep(long timeOut, TimeUnit timeUnit) {
}
try {
timeUnit.sleep(timeOut);
} catch (Throwable ignored) {

} catch (Exception ignored) {
// NO Sonar
}
}

Expand Down Expand Up @@ -131,6 +135,7 @@ public static boolean isItTimeToDo(final String when) {
return false;
}

@SuppressWarnings("unused")
public static String timeMillisToHumanString() {
return timeMillisToHumanString(System.currentTimeMillis());
}
Expand Down Expand Up @@ -179,6 +184,7 @@ public static long computeNextHourTimeMillis() {
return cal.getTimeInMillis();
}

@SuppressWarnings("unused")
public static long computeNextHalfHourTimeMillis() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
Expand Down Expand Up @@ -216,6 +222,7 @@ public static String timeMillisToHumanString3(final long t) {
cal.get(Calendar.SECOND));
}

@SuppressWarnings("unused")
public static long getTotalSpace(final String path) {
if (null == path || path.isEmpty())
return -1;
Expand Down Expand Up @@ -377,8 +384,6 @@ public static byte[] uncompress(final byte[] src) throws IOException {
}
byteArrayOutputStream.flush();
result = byteArrayOutputStream.toByteArray();
} catch (IOException e) {
throw e;
} finally {
try {
byteArrayInputStream.close();
Expand Down Expand Up @@ -421,6 +426,7 @@ public static byte[] compress(final byte[] src, final int level) throws IOExcept
try {
byteArrayOutputStream.close();
} catch (IOException ignored) {
// NO Sonar
}

defeater.end();
Expand All @@ -429,6 +435,7 @@ public static byte[] compress(final byte[] src, final int level) throws IOExcept
return result;
}

@SuppressWarnings("unused")
public static int asInt(String str, int defaultValue) {
try {
return Integer.parseInt(str);
Expand All @@ -437,6 +444,7 @@ public static int asInt(String str, int defaultValue) {
}
}

@SuppressWarnings("unused")
public static long asLong(String str, long defaultValue) {
try {
return Long.parseLong(str);
Expand Down Expand Up @@ -464,10 +472,8 @@ public static String responseCode2String(final int code) {
}

public static String frontStringAtLeast(final String str, final int size) {
if (str != null) {
if (str.length() > size) {
return str.substring(0, size);
}
if (str != null && str.length() > size) {
return str.substring(0, size);
}

return str;
Expand All @@ -484,9 +490,7 @@ public static String jstack() {
public static String jstack(Map<Thread, StackTraceElement[]> map) {
StringBuilder result = new StringBuilder();
try {
Iterator<Map.Entry<Thread, StackTraceElement[]>> ite = map.entrySet().iterator();
while (ite.hasNext()) {
Map.Entry<Thread, StackTraceElement[]> entry = ite.next();
for (Map.Entry<Thread, StackTraceElement[]> entry : map.entrySet()) {
StackTraceElement[] elements = entry.getValue();
Thread thread = entry.getKey();
if (elements != null && elements.length > 0) {
Expand All @@ -498,7 +502,7 @@ public static String jstack(Map<Thread, StackTraceElement[]> map) {
result.append("\n");
}
}
} catch (Throwable e) {
} catch (Exception e) {
result.append(exceptionSimpleDesc(e));
}

Expand Down Expand Up @@ -570,9 +574,9 @@ public static String ipToIPv4Str(byte[] ip) {
if (ip.length != 4) {
return null;
}
return new StringBuilder().append(ip[0] & 0xFF).append(".").append(
ip[1] & 0xFF).append(".").append(ip[2] & 0xFF)
.append(".").append(ip[3] & 0xFF).toString();
return (ip[0] & 0xFF) + "." +
(ip[1] & 0xFF) + "." + (ip[2] & 0xFF) +
"." + (ip[3] & 0xFF);
}

public static String ipToIPv6Str(byte[] ip) {
Expand Down Expand Up @@ -606,23 +610,17 @@ public static byte[] getIP() {
ip = addresses.nextElement();
if (ip instanceof Inet4Address) {
byte[] ipByte = ip.getAddress();
if (ipByte.length == 4) {
if (ipCheck(ipByte)) {
if (!isInternalIP(ipByte)) {
return ipByte;
} else if (internalIP == null || internalIP[0] == (byte) 127) {
internalIP = ipByte;
}
if (ipByte.length == 4 && ipCheck(ipByte)) {
if (!isInternalIP(ipByte)) {
return ipByte;
} else if (internalIP == null || internalIP[0] == (byte) 127) {
internalIP = ipByte;
}
}
} else if (ip instanceof Inet6Address) {
byte[] ipByte = ip.getAddress();
if (ipByte.length == 16) {
if (ipV6Check(ipByte)) {
if (!isInternalV6IP(ip)) {
return ipByte;
}
}
if (ipByte.length == 16 && ipV6Check(ipByte) && !isInternalV6IP(ip)) {
return ipByte;
}
}
}
Expand All @@ -645,8 +643,10 @@ public static void deleteFile(File file) {
file.delete();
} else if (file.isDirectory()) {
File[] files = file.listFiles();
for (File file1 : files) {
deleteFile(file1);
if (Objects.nonNull(files)) {
for (File file1 : files) {
deleteFile(file1);
}
}
file.delete();
}
Expand Down Expand Up @@ -674,7 +674,7 @@ public static List<String> split(String str, String splitter) {
}

if (StringUtils.isBlank(str)) {
return Collections.EMPTY_LIST;
return Collections.emptyList();
}

String[] addrArray = str.split(splitter);
Expand All @@ -689,7 +689,7 @@ public static void deleteEmptyDirectory(File file) {
return;
}
File[] files = file.listFiles();
if (files == null || files.length <= 0) {
if (files == null || files.length == 0) {
file.delete();
STORE_LOG.info("delete empty direct, {}", file.getPath());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public void preShutdown() throws Exception {
}
}

@SuppressWarnings("unused")
public void appendStart(Start start) {
this.appendStartAndShutdown(new StartAndShutdown() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,18 @@

package org.apache.rocketmq.common.utils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;

public class BinaryUtil {
private BinaryUtil() {
// Prevent class from being instantiated from outside
}

public static byte[] calculateMd5(byte[] binaryData) {
MessageDigest messageDigest = null;
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
Expand All @@ -34,8 +38,9 @@ public static byte[] calculateMd5(byte[] binaryData) {
return messageDigest.digest();
}

@SuppressWarnings("unused")
public static String generateMd5(String bodyStr) {
byte[] bytes = calculateMd5(bodyStr.getBytes(Charset.forName("UTF-8")));
byte[] bytes = calculateMd5(bodyStr.getBytes(StandardCharsets.UTF_8));
return Hex.encodeHexString(bytes, false);
}

Expand All @@ -46,8 +51,8 @@ public static String generateMd5(byte[] content) {

/**
* Returns true if subject contains only bytes that are spec-compliant ASCII characters.
* @param subject
* @return
* @param subject -
* @return is ascii or not
*/
public static boolean isAscii(byte[] subject) {
if (subject == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
import java.net.InetSocketAddress;

public class ChannelUtil {
private ChannelUtil() {
// Prevent class from being instantiated from outside
}

@SuppressWarnings("unused")
public static String getRemoteIp(Channel channel) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
if (inetSocketAddress == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
import java.util.Optional;

public class CleanupPolicyUtils {
private CleanupPolicyUtils() {
// Prevent class from being instantiated from outside
}

@SuppressWarnings("unused")
public static boolean isCompaction(Optional<TopicConfig> topicConfig) {
return Objects.equals(CleanupPolicy.COMPACTION, getDeletePolicy(topicConfig));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public abstract class ConcurrentHashMapUtils {
/**
* A temporary workaround for Java 8 specific performance issue JDK-8161372 .<br> Use implementation of
* ConcurrentMap.computeIfAbsent instead.
*
* <p>
* Requirement: <strong>The mapping function should not modify this map during computation.</strong>
*
* @see <a href="https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
import java.util.UUID;

public class CorrelationIdUtil {
private CorrelationIdUtil() {
// Prevent class from being instantiated from outside
}

public static String createCorrelationId() {
return UUID.randomUUID().toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@
*/
package org.apache.rocketmq.common.utils;

import java.util.Objects;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;

public class ExceptionUtils {
private ExceptionUtils() {
// Prevent class from being instantiated from outside
}

public static Throwable getRealException(Throwable throwable) {
if (throwable instanceof CompletionException || throwable instanceof ExecutionException) {
if (throwable.getCause() != null) {
throwable = throwable.getCause();
}
if ((throwable instanceof CompletionException || throwable instanceof ExecutionException)
&& Objects.nonNull(throwable.getCause())) {
throwable = throwable.getCause();
}

return throwable;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
import java.util.concurrent.ExecutorService;

public class FutureUtils {
private FutureUtils() {
// Prevent class from being instantiated from outside
}

public static <T> CompletableFuture<T> appendNextFuture(CompletableFuture<T> future,
CompletableFuture<T> nextFuture, ExecutorService executor) {
Expand Down
Loading

0 comments on commit c20d145

Please sign in to comment.