refact: clean code & typo & update the name of getTimeZone (#105)

* refact:  clean code & typo & update the name of getTimeZone

Typo: getTimeZome() -> getTimeZone()

And we need check/update the class used it later

* Update RestClient.java
This commit is contained in:
imbajin 2022-09-15 16:36:13 +08:00 committed by GitHub
parent 3b1bcb1a99
commit e85ab38c6b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 146 additions and 177 deletions

View File

@ -28,7 +28,7 @@ body:
options:
- exception / error (异常报错)
- logic (逻辑设计问题)
- performence (性能下降)
- performance (性能下降)
- others (please edit later)
- type: checkboxes

View File

@ -25,7 +25,7 @@ body:
label: Problem Type (问题类型)
options:
- struct / logic (架构 / 逻辑设计问题)
- performence (性能优化)
- performance (性能优化)
- exception / error (异常报错)
- others (please edit later)

View File

@ -88,7 +88,7 @@ public class KeyLock {
Lock lock = this.locks.get(key);
locks.add(lock);
}
Collections.sort(locks, (a, b) -> {
locks.sort((a, b) -> {
int diff = a.hashCode() - b.hashCode();
if (diff == 0 && a != b) {
diff = this.indexOf(a) - this.indexOf(b);
@ -96,8 +96,8 @@ public class KeyLock {
}
return diff;
});
for (int i = 0; i < locks.size(); i++) {
locks.get(i).lock();
for (Lock lock : locks) {
lock.lock();
}
return Collections.unmodifiableList(locks);
}
@ -125,8 +125,8 @@ public class KeyLock {
ImmutableList.of(lock2, lock1) :
ImmutableList.of(lock1, lock2);
for (int i = 0; i < locks.size(); i++) {
locks.get(i).lock();
for (Lock lock : locks) {
lock.lock();
}
return locks;

View File

@ -28,8 +28,7 @@ import org.slf4j.Logger;
public class PausableScheduledThreadPool extends ScheduledThreadPoolExecutor {
private static final Logger LOG = Log.logger(
PausableScheduledThreadPool.class);
private static final Logger LOG = Log.logger(PausableScheduledThreadPool.class);
private volatile boolean paused = false;

View File

@ -21,6 +21,7 @@ package org.apache.hugegraph.config;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import javax.annotation.Nullable;
@ -32,88 +33,55 @@ import com.google.common.base.Predicate;
public final class OptionChecker {
public static <O> Predicate<O> disallowEmpty() {
return new Predicate<O>() {
@Override
public boolean apply(@Nullable O o) {
if (o == null) {
return false;
}
if (o instanceof String) {
return StringUtils.isNotBlank((String) o);
}
if (o.getClass().isArray() && (Array.getLength(o) == 0)) {
return false;
}
if (o instanceof Iterable &&
!((Iterable<?>) o).iterator().hasNext()) {
return false;
}
return true;
return o -> {
if (o == null) {
return false;
}
if (o instanceof String) {
return StringUtils.isNotBlank((String) o);
}
if (o.getClass().isArray() && (Array.getLength(o) == 0)) {
return false;
}
return !(o instanceof Iterable) || ((Iterable<?>) o).iterator().hasNext();
};
}
@SuppressWarnings("unchecked")
public static <O> Predicate<O> allowValues(O... values) {
return new Predicate<O>() {
@Override
public boolean apply(@Nullable O o) {
return o != null && Arrays.asList(values).contains(o);
}
};
return o -> o != null && Arrays.asList(values).contains(o);
}
@SuppressWarnings("unchecked")
public static <O> Predicate<List<O>> inValues(O... values) {
return new Predicate<List<O>>() {
@Override
public boolean apply(@Nullable List<O> o) {
return o != null && Arrays.asList(values).containsAll(o);
}
};
return o -> o != null && new HashSet<>(Arrays.asList(values)).containsAll(o);
}
public static <N extends Number> Predicate<N> positiveInt() {
return new Predicate<N>() {
@Override
public boolean apply(@Nullable N number) {
return number != null && number.longValue() > 0;
}
};
return number -> number != null && number.longValue() > 0;
}
public static <N extends Number> Predicate<N> nonNegativeInt() {
return new Predicate<N>() {
@Override
public boolean apply(@Nullable N number) {
return number != null && number.longValue() >= 0;
}
};
return number -> number != null && number.longValue() >= 0;
}
public static <N extends Number> Predicate<N> rangeInt(N min, N max) {
return new Predicate<N>() {
@Override
public boolean apply(@Nullable N number) {
if (number == null) {
return false;
}
long value = number.longValue();
return value >= min.longValue() && value <= max.longValue();
return number -> {
if (number == null) {
return false;
}
long value = number.longValue();
return value >= min.longValue() && value <= max.longValue();
};
}
public static <N extends Number> Predicate<N> rangeDouble(N min, N max) {
return new Predicate<N>() {
@Override
public boolean apply(@Nullable N number) {
if (number == null) {
return false;
}
double value = number.doubleValue();
return value >= min.doubleValue() && value <= max.doubleValue();
return number -> {
if (number == null) {
return false;
}
double value = number.doubleValue();
return value >= min.doubleValue() && value <= max.doubleValue();
};
}
}

View File

@ -48,7 +48,7 @@ public class SafeDateFormat {
this.formatter = this.formatter.withZone(zone);
}
public TimeZone getTimeZome() {
public TimeZone getTimeZone() {
return this.formatter.getZone().toTimeZone();
}

View File

@ -159,8 +159,8 @@ public class EventHub {
try {
all.next().event(ev);
count++;
} catch (Throwable ignored) {
LOG.warn("Failed to handle event: {}", ev, ignored);
} catch (Throwable e) {
LOG.warn("Failed to handle event: {}", ev, e);
}
}
return count;

View File

@ -25,5 +25,5 @@ public interface EventListener extends java.util.EventListener {
* @param event object
* @return event result
*/
public Object event(Event event);
Object event(Event event);
}

View File

@ -20,5 +20,6 @@
package org.apache.hugegraph.func;
public interface TriFunction <T1, T2, T3, R> {
public R apply(T1 v1, T2 v2, T3 v3);
R apply(T1 v1, T2 v2, T3 v3);
}

View File

@ -82,7 +82,7 @@ public class ExtendableIterator<T> extends WrappedIterator<T> {
return true;
}
Iterator<T> first = null;
Iterator<T> first;
while ((first = this.itors.peekFirst()) != null && !first.hasNext()) {
if (first == this.itors.peekLast() && this.itors.size() == 1) {
this.currentIterator = first;

View File

@ -21,5 +21,5 @@ package org.apache.hugegraph.iterator;
public interface Metadatable {
public Object metadata(String meta, Object... args);
Object metadata(String meta, Object... args);
}

View File

@ -21,14 +21,14 @@ package org.apache.hugegraph.license;
public interface LicenseManager {
public LicenseParams installLicense() throws Exception;
LicenseParams installLicense() throws Exception;
public void uninstallLicense() throws Exception;
void uninstallLicense() throws Exception;
public LicenseParams verifyLicense() throws Exception;
LicenseParams verifyLicense() throws Exception;
public interface VerifyCallback {
interface VerifyCallback {
public void onVerifyLicense(LicenseParams params) throws Exception;
void onVerifyLicense(LicenseParams params) throws Exception;
}
}

View File

@ -135,8 +135,7 @@ public final class LightStopwatch implements Stopwatch {
@Override
public void fillChildrenTotal(List<Stopwatch> children) {
// Fill total times of children
this.totalChildrenTimes = children.stream().mapToLong(
c -> c.totalTimes()).sum();
this.totalChildrenTimes = children.stream().mapToLong(Stopwatch::totalTimes).sum();
}
@Override

View File

@ -184,11 +184,9 @@ public final class NormalStopwatch implements Stopwatch {
@Override
public void fillChildrenTotal(List<Stopwatch> children) {
// Fill total wasted cost of children
this.totalChildrenWasted = children.stream().mapToLong(
c -> c.totalWasted()).sum();
this.totalChildrenWasted = children.stream().mapToLong(Stopwatch::totalWasted).sum();
// Fill total times of children
this.totalChildrenTimes = children.stream().mapToLong(
c -> c.totalTimes()).sum();
this.totalChildrenTimes = children.stream().mapToLong(Stopwatch::totalTimes).sum();
}
@Override

View File

@ -681,8 +681,8 @@ public final class PerfUtil {
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR })
public static @interface Watched {
public String value() default "";
public String prefix() default "";
public @interface Watched {
String value() default "";
String prefix() default "";
}
}

View File

@ -23,40 +23,40 @@ import java.util.List;
public interface Stopwatch extends Cloneable {
public Path id();
public String name();
public Path parent();
Path id();
String name();
Path parent();
public void startTime(long startTime);
public void endTime(long startTime);
void startTime(long startTime);
void endTime(long startTime);
public void lastStartTime(long startTime);
void lastStartTime(long startTime);
public long times();
public long totalTimes();
public long totalChildrenTimes();
long times();
long totalTimes();
long totalChildrenTimes();
public long totalCost();
public void totalCost(long otherCost);
long totalCost();
void totalCost(long otherCost);
public long minCost();
public long maxCost();
long minCost();
long maxCost();
public long totalWasted();
public long totalSelfWasted();
public long totalChildrenWasted();
long totalWasted();
long totalSelfWasted();
long totalChildrenWasted();
public void fillChildrenTotal(List<Stopwatch> children);
void fillChildrenTotal(List<Stopwatch> children);
public Stopwatch copy();
Stopwatch copy();
public Stopwatch child(String name);
public Stopwatch child(String name, Stopwatch watch);
Stopwatch child(String name);
Stopwatch child(String name, Stopwatch watch);
public boolean empty();
public void clear();
boolean empty();
void clear();
public default String toJson() {
default String toJson() {
int len = 200 + this.name().length() + this.parent().length();
StringBuilder sb = new StringBuilder(len);
sb.append("{");
@ -75,14 +75,14 @@ public interface Stopwatch extends Cloneable {
return sb.toString();
}
public static Path id(Path parent, String name) {
static Path id(Path parent, String name) {
if (parent == Path.EMPTY && name == Path.ROOT_NAME) {
return Path.EMPTY;
}
return new Path(parent, name);
}
public static final class Path implements Comparable<Path> {
final class Path implements Comparable<Path> {
public static final String ROOT_NAME = "root";
public static final Path EMPTY = new Path("");

View File

@ -435,11 +435,11 @@ public abstract class AbstractRestClient implements RestClient {
String url,
ClientConfig conf) {
String protocol = (String) conf.getProperty("protocol");
if (protocol == null || protocol.equals("http")) {
if (protocol == null || "http".equals(protocol)) {
return new PoolingHttpClientConnectionManager(TTL, TimeUnit.HOURS);
}
assert protocol.equals("https");
assert "https".equals(protocol);
String trustStoreFile = (String) conf.getProperty("trustStoreFile");
E.checkArgument(trustStoreFile != null && !trustStoreFile.isEmpty(),
"The trust store file must be set when use https");

View File

@ -24,31 +24,45 @@ import java.util.Map;
import jakarta.ws.rs.core.MultivaluedMap;
public interface RestClient {
/**
* Post method
*/
RestResult post(String path, Object object);
public RestResult post(String path, Object object);
public RestResult post(String path, Object object,
MultivaluedMap<String, Object> headers);
public RestResult post(String path, Object object,
Map<String, Object> params);
public RestResult post(String path, Object object,
MultivaluedMap<String, Object> headers,
Map<String, Object> params);
RestResult post(String path, Object object, MultivaluedMap<String, Object> headers);
public RestResult put(String path, String id, Object object);
public RestResult put(String path, String id, Object object,
MultivaluedMap<String, Object> headers);
public RestResult put(String path, String id, Object object,
Map<String, Object> params);
public RestResult put(String path, String id, Object object,
MultivaluedMap<String, Object> headers,
Map<String, Object> params);
RestResult post(String path, Object object, Map<String, Object> params);
public RestResult get(String path);
public RestResult get(String path, Map<String, Object> params);
public RestResult get(String path, String id);
RestResult post(String path, Object object, MultivaluedMap<String, Object> headers,
Map<String, Object> params);
public RestResult delete(String path, Map<String, Object> params);
public RestResult delete(String path, String id);
/**
* Put method
*/
RestResult put(String path, String id, Object object);
public void close();
RestResult put(String path, String id, Object object, MultivaluedMap<String, Object> headers);
RestResult put(String path, String id, Object object, Map<String, Object> params);
RestResult put(String path, String id, Object object, MultivaluedMap<String, Object> headers,
Map<String, Object> params);
/**
* Get method
*/
RestResult get(String path);
RestResult get(String path, Map<String, Object> params);
RestResult get(String path, String id);
/**
* Delete method
*/
RestResult delete(String path, Map<String, Object> params);
RestResult delete(String path, String id);
void close();
}

View File

@ -42,9 +42,7 @@ public class Assert extends org.junit.Assert {
public static void assertThrows(Class<? extends Throwable> throwable,
ThrowableRunnable runnable) {
CompletableFuture<?> future = assertThrowsFuture(throwable, runnable);
future.thenAccept(e -> {
System.err.println(e);
});
future.thenAccept(System.err::println);
}
public static void assertThrows(Class<? extends Throwable> throwable,

View File

@ -47,8 +47,8 @@ public final class CheckSocket {
Integer.parseInt(args[1]));
s.close();
System.exit(0);
} catch (IOException ignored) {
System.err.println(ignored.toString());
} catch (IOException e) {
System.err.println(e);
System.exit(E_FAILED);
}
}

View File

@ -150,7 +150,7 @@ public final class CollectionUtil {
E.checkNotNull(first, "first");
E.checkNotNull(second, "second");
HashSet<T> results = null;
HashSet<T> results;
if (first instanceof HashSet) {
@SuppressWarnings("unchecked")
HashSet<T> clone = (HashSet<T>) ((HashSet<T>) first).clone();
@ -303,7 +303,7 @@ public final class CollectionUtil {
* @param n m of C(n, m)
* @param m n of C(n, m)
* @return true if matched any kind of items combination else false, the
* callback can always return false if want to traverse all combinations
* callback can always return false if you want to traverse all combinations
*/
public static <T> boolean cnm(List<T> all, int n, int m,
Function<List<T>, Boolean> callback) {
@ -317,9 +317,9 @@ public final class CollectionUtil {
* @param n n of C(n, m)
* @param m m of C(n, m)
* @param current current position in list
* @param selected list to contains selected items
* @param selected list to contain selected items
* @return true if matched any kind of items combination else false, the
* callback can always return false if want to traverse all combinations
* callback can always return false if you want to traverse all combinations
*/
private static <T> boolean cnm(List<T> all, int n, int m,
int current, List<T> selected,
@ -360,11 +360,7 @@ public final class CollectionUtil {
// Not select current item, pop it and continue to select C(m-1, n)
selected.remove(index);
assert selected.size() == index : selected;
if (cnm(all, n - 1, m, current, selected, callback)) {
return true;
}
return false;
return cnm(all, n - 1, m, current, selected, callback);
}
/**
@ -399,7 +395,7 @@ public final class CollectionUtil {
* @param n m of A(n, m)
* @param m n of A(n, m)
* @return true if matched any kind of items combination else false, the
* callback can always return false if want to traverse all combinations
* callback can always return false if you want to traverse all combinations
*/
public static <T> boolean anm(List<T> all, int n, int m,
Function<List<T>, Boolean> callback) {
@ -412,9 +408,9 @@ public final class CollectionUtil {
* @param all list to contain all items for combination
* @param n m of A(n, m)
* @param m n of A(n, m)
* @param selected list to contains selected items
* @param selected list to contain selected items
* @return true if matched any kind of items combination else false, the
* callback can always return false if want to traverse all combinations
* callback can always return false if you want to traverse all combinations
*/
private static <T> boolean anm(List<T> all, int n, int m,
List<Integer> selected,

View File

@ -40,7 +40,7 @@ public final class NumericUtil {
* <code>long</code>. The value is converted by getting their IEEE 754
* floating-point &quot;double format&quot; bit layout and then some bits
* are swapped, to be able to compare the result as long. By this the
* precision is not reduced, but the value can easily used as a long. The
* precision is not reduced, but the value can be easily used as a long. The
* sort order (including {@link Double#NaN}) is defined by
* {@link Double#compareTo}; {@code NaN} is greater than positive infinity.
* @param value input double value
@ -66,7 +66,7 @@ public final class NumericUtil {
* <code>int</code>. The value is converted by getting their IEEE 754
* floating-point &quot;float format&quot; bit layout and then some bits are
* swapped, to be able to compare the result as int. By this the precision
* is not reduced, but the value can easily used as an int. The sort order
* is not reduced, but the value can be easily used as an int. The sort order
* (including {@link Float#NaN}) is defined by {@link Float#compareTo};
* {@code NaN} is greater than positive infinity.
* @param value input float value
@ -100,7 +100,7 @@ public final class NumericUtil {
/**
* Converts IEEE 754 representation of a float to sortable order (or back to
* the original)
* @param bits The int format of an float value
* @param bits The int format of a float value
* @return The sortable int value
*/
public static int sortableFloatBits(int bits) {

View File

@ -156,7 +156,7 @@ public final class UnitUtil {
} else {
// Not exists days
int msPos = formatDuration.indexOf("MS");
// If contains ms, rmove the ms part
// If contains ms, remove the ms part
if (msPos >= 0) {
int sPos = formatDuration.indexOf("S");
if (0 <= sPos && sPos < msPos) {

View File

@ -94,7 +94,7 @@ public final class VersionUtil {
public static String getImplementationVersion(String manifestPath) {
manifestPath += "/META-INF/MANIFEST.MF";
Manifest manifest = null;
Manifest manifest;
try {
manifest = new Manifest(new URL(manifestPath).openStream());
} catch (IOException ignored) {

View File

@ -109,7 +109,7 @@ public class SafeDateFormatTest {
SafeDateFormat sdf = new SafeDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone("GMT+10");
Assert.assertEquals(df.getTimeZone(), sdf.getTimeZome());
Assert.assertEquals(df.getTimeZone(), sdf.getTimeZone());
Assert.assertEquals(df.parse("2019-08-10 00:00:00"),
sdf.parse("2019-08-10 00:00:00"));
Assert.assertEquals("2019-08-10 00:00:00",
@ -118,7 +118,7 @@ public class SafeDateFormatTest {
sdf.format(sdf.parse("2019-08-10 00:00:00")));
sdf.setTimeZone("GMT+11");
Assert.assertNotEquals(df.getTimeZone(), sdf.getTimeZome());
Assert.assertNotEquals(df.getTimeZone(), sdf.getTimeZone());
Assert.assertNotEquals(df.parse("2019-08-10 00:00:00"),
sdf.parse("2019-08-10 00:00:00"));
Assert.assertEquals("2019-08-10 00:00:00",

View File

@ -21,17 +21,17 @@ package org.apache.hugegraph.rpc;
public interface RpcServiceConfig4Client {
public <T> T serviceProxy(String interfaceId);
<T> T serviceProxy(String interfaceId);
public <T> T serviceProxy(String graph, String interfaceId);
<T> T serviceProxy(String graph, String interfaceId);
public default <T> T serviceProxy(Class<T> clazz) {
default <T> T serviceProxy(Class<T> clazz) {
return this.serviceProxy(clazz.getName());
}
public default <T> T serviceProxy(String graph, Class<T> clazz) {
default <T> T serviceProxy(String graph, Class<T> clazz) {
return this.serviceProxy(graph, clazz.getName());
}
public void removeAllServiceProxy();
void removeAllServiceProxy();
}

View File

@ -21,12 +21,12 @@ package org.apache.hugegraph.rpc;
public interface RpcServiceConfig4Server {
public <T, S extends T> String addService(Class<T> clazz, S serviceImpl);
<T, S extends T> String addService(Class<T> clazz, S serviceImpl);
public <T, S extends T> String addService(String graph,
<T, S extends T> String addService(String graph,
Class<T> clazz, S serviceImpl);
public void removeService(String serviceId);
void removeService(String serviceId);
public void removeAllService();
void removeAllService();
}

View File

@ -30,7 +30,7 @@ public class ExceptionTest {
public void testExceptionWithMessage() {
RpcException e = new RpcException("test");
Assert.assertEquals("test", e.getMessage());
Assert.assertEquals(null, e.getCause());
Assert.assertNull(e.getCause());
}
@Test
@ -45,7 +45,7 @@ public class ExceptionTest {
public void testExceptionWithMessageAndArgs() {
RpcException e = new RpcException("test %s", 168);
Assert.assertEquals("test 168", e.getMessage());
Assert.assertEquals(null, e.getCause());
Assert.assertNull(e.getCause());
}
@Test

View File

@ -682,9 +682,7 @@ public class ServerClientTest extends BaseUnitTest {
RpcServer rpcServerDisabled = new RpcServer(clientConf);
Assert.assertFalse(rpcServerDisabled.enabled());
Assert.assertThrows(IllegalArgumentException.class, () -> {
rpcServerDisabled.config();
}, e -> {
Assert.assertThrows(IllegalArgumentException.class, rpcServerDisabled::config, e -> {
Assert.assertContains("RpcServer is not enabled", e.getMessage());
});
@ -697,9 +695,7 @@ public class ServerClientTest extends BaseUnitTest {
RpcClientProvider rpcClientDisabled = new RpcClientProvider(serverConf);
Assert.assertFalse(rpcClientDisabled.enabled());
Assert.assertThrows(IllegalArgumentException.class, () -> {
rpcClientDisabled.config();
}, e -> {
Assert.assertThrows(IllegalArgumentException.class, rpcClientDisabled::config, e -> {
Assert.assertContains("RpcClient is not enabled", e.getMessage());
});