Skip to content

Commit

Permalink
optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
ponfee committed Dec 11, 2023
1 parent bb6532f commit 1248ffb
Show file tree
Hide file tree
Showing 67 changed files with 238 additions and 215 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ public String job(ModelMap mmap) {
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(SchedJobPageRequest request) {
if (CollectionUtils.isEmpty(request.getGroups())) {
request.setGroups(SchedGroupService.mapUser(getLoginName()));
}
request.constrainAndTruncateUserGroup(getLoginName());
if (CollectionUtils.isEmpty(request.getGroups())) {
return PageUtils.empty();
}
Expand Down Expand Up @@ -106,9 +104,7 @@ public String detail(@PathVariable("jobId") long jobId, ModelMap mmap) {
@PostMapping("/export")
@ResponseBody
public AjaxResult export(SchedJobPageRequest request) {
if (CollectionUtils.isEmpty(request.getGroups())) {
request.setGroups(SchedGroupService.mapUser(getLoginName()));
}
request.constrainAndTruncateUserGroup(getLoginName());

List<SchedJobExport> list;
if (CollectionUtils.isEmpty(request.getGroups())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public String mggroup() {
public TableDataInfo list(SchedGroupPageRequest request) {
request.setPageNumber(super.getPageNumber());
request.setPageSize(super.getPageSize());
request.truncateUserGroup();
return PageUtils.toTableDataInfo(schedGroupService.queryForPage(request));
}

Expand Down Expand Up @@ -169,7 +170,7 @@ public AjaxResult updateOwnUser(@RequestParam("group") String group,

@RequiresPermissions(PERMISSION_OPERATE)
@GetMapping("/worker")
public String worker(@RequestParam("group") String group, ModelMap mmap) throws Exception {
public String worker(@RequestParam("group") String group, ModelMap mmap) {
mmap.put("list", serverMetricsService.workers(group));
return PREFIX + "/worker";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,7 @@ public String mygroup(ModelMap mmap) {
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(SchedGroupPageRequest request) {
if (CollectionUtils.isEmpty(request.getGroups())) {
request.setGroups(SchedGroupService.mapUser(getLoginName()));
}
request.constrainAndTruncateUserGroup(getLoginName());
if (CollectionUtils.isEmpty(request.getGroups())) {
return PageUtils.empty();
}
Expand Down Expand Up @@ -108,7 +106,7 @@ public AjaxResult doEdit(UpdateSchedGroupRequest req) {

@RequiresPermissions(PERMISSION_OPERATE)
@GetMapping("/worker")
public String worker(@RequestParam("group") String group, ModelMap mmap) throws Exception {
public String worker(@RequestParam("group") String group, ModelMap mmap) {
mmap.put("list", serverMetricsService.workers(group));
return PREFIX + "/worker";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public static synchronized void constrain(Object instance) {

public static synchronized void constrain(Class<?> clazz) {
if (MUTEX.add(clazz)) {
LOG.info("Class '" + clazz + "' instance are created.");
LOG.info("Class '{}' instance are created.", clazz);
} else {
throw new Error("Class '" + clazz + "' instance already created.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ public abstract class TimingWheel<T extends TimingWheel.Timing<T>> implements ja
*/
private final TimingQueue<T>[] wheel;

public TimingWheel(long tickMs, int ringSize) {
protected TimingWheel(long tickMs, int ringSize) {
Assert.isTrue(tickMs > 0, "Tick milliseconds must be greater than 0");
Assert.isTrue(ringSize > 0, "Ring size must be greater than 0");
this.tickMs = tickMs;
Expand Down Expand Up @@ -167,7 +167,7 @@ public final boolean offer(T timing, long leastTimeMillis) {
if (res) {
LOG.info("Timing wheel task success {}", timing);
} else {
LOG.error("Timing wheel task failed " + timing);
LOG.error("Timing wheel task failed {}", timing);
}
return res;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@
*
* @author Ponfee
*/
public final class ArrayHashKey implements java.io.Serializable, Comparable<ArrayHashKey> {

private static final long serialVersionUID = -8749483734287105153L;
public final class ArrayHashKey implements Comparable<ArrayHashKey> {

private final Object[] key;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static <E> LinkedList<E> newLinkedList(E element) {
}

public static <T> Set<T> truncate(Set<T> set, int length) {
if (length < 2 || CollectionUtils.isEmpty(set) || set.size() <= length) {
if (CollectionUtils.isEmpty(set) || length <= 0 || set.size() <= length) {
return set;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public abstract class AbstractHeartbeatThread extends Thread implements Closeabl
*/
protected final long heartbeatPeriodMs;

public AbstractHeartbeatThread(long heartbeatPeriodMs) {
protected AbstractHeartbeatThread(long heartbeatPeriodMs) {
log.info("Heartbeat thread init {}", getClass());
this.heartbeatPeriodMs = Math.floorDiv(2 * heartbeatPeriodMs, 3);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class CustomLocalDateTimeDeserializer extends JSR310DateTimeDeserializerB

public static final CustomLocalDateTimeDeserializer INSTANCE = new CustomLocalDateTimeDeserializer();

private final LocalDateTimeFormat wrappedFormatter;
private final transient LocalDateTimeFormat wrappedFormatter;

protected CustomLocalDateTimeDeserializer() {
this(Dates.DATETIME_PATTERN);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,8 @@ public interface ThrowingConsumer<E, T extends Throwable> {
void accept(E e) throws T;

default <R> ThrowingFunction<E, R, Throwable> toFunction(R result) {
return (arg) -> {
accept(arg);
return x -> {
accept(x);
return result;
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,10 @@ public boolean isFailure() {
*
* @param <T> the data type
*/
public static abstract class ImmutableResult<T> extends Result<T> {
public abstract static class ImmutableResult<T> extends Result<T> {
private static final long serialVersionUID = -8356385235924100622L;

public ImmutableResult(int code, String msg, T data) {
protected ImmutableResult(int code, String msg, T data) {
super(code, msg, data);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,15 @@ public abstract class BaseNode<T extends Serializable & Comparable<T>, A> implem
protected int childrenCount; // 子节点个数
protected int siblingOrdinal; // 兄弟节点按顺序排行(从1开始)

public BaseNode(T nid, T pid, A attach) {
protected BaseNode(T nid, T pid, A attach) {
this(nid, pid, true, attach);
}

public BaseNode(T nid, T pid, boolean enabled, A attach) {
protected BaseNode(T nid, T pid, boolean enabled, A attach) {
this(nid, pid, enabled, enabled, attach);
}

public BaseNode(T nid, T pid, boolean enabled, boolean available, A attach) {
protected BaseNode(T nid, T pid, boolean enabled, boolean available, A attach) {
Assert.isTrue(ObjectUtils.isNotEmpty(nid), "Node id cannot be empty.");
this.nid = nid;
this.pid = pid;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public abstract class NodeId<T extends NodeId<T>> extends ToJsonString implement

protected final T parent;

public NodeId(T parent) {
protected NodeId(T parent) {
this.parent = parent;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.function.UnaryOperator;

/**
* Print binary tree
Expand All @@ -30,8 +31,8 @@ public enum Branch {

private final Appendable output;
private final Function<T, String> nodeLabel;
private final Function<T, T> leftChild;
private final Function<T, T> rightChild;
private final UnaryOperator<T> leftChild;
private final UnaryOperator<T> rightChild;

/**
* 分支是方形还是三角形
Expand All @@ -55,8 +56,8 @@ public enum Branch {

BinaryTreePrinter(Appendable output,
Function<T, String> nodeLabel,
Function<T, T> leftChild,
Function<T, T> rightChild,
UnaryOperator<T> leftChild,
UnaryOperator<T> rightChild,
Branch branch,
boolean directed,
int nodeSpace,
Expand Down Expand Up @@ -144,22 +145,26 @@ public void print(List<T> trees, int lineWidth) throws IOException {
}
}

public static <T> Builder<T> builder(Function<T, String> nodeLabel, Function<T, T> leftChild, Function<T, T> rightChild) {
public static <T> Builder<T> builder(Function<T, String> nodeLabel,
UnaryOperator<T> leftChild,
UnaryOperator<T> rightChild) {
return new Builder<>(nodeLabel, leftChild, rightChild);
}

public static class Builder<T> {
private final Function<T, String> nodeLabel;
private final Function<T, T> leftChild;
private final Function<T, T> rightChild;
private final UnaryOperator<T> leftChild;
private final UnaryOperator<T> rightChild;

private Appendable output = System.out;
private Branch branch = Branch.RECTANGLE;
private boolean directed = true;
private int nodeSpace = 2;
private int treeSpace = 5;

private Builder(Function<T, String> nodeLabel, Function<T, T> leftChild, Function<T, T> rightChild) {
private Builder(Function<T, String> nodeLabel,
UnaryOperator<T> leftChild,
UnaryOperator<T> rightChild) {
this.nodeLabel = nodeLabel;
this.leftChild = leftChild;
this.rightChild = rightChild;
Expand Down Expand Up @@ -201,7 +206,7 @@ public BinaryTreePrinter<T> build() {
// --------------------------------------------------------------------private methods

private void printTreeLines(List<TreeLine> treeLines) throws IOException {
if (treeLines.size() <= 0) {
if (treeLines.isEmpty()) {
return;
}
int minLeftOffset = minLeftOffset(treeLines);
Expand Down Expand Up @@ -260,8 +265,8 @@ private List<TreeLine> buildTreeLines(T root) {
if (branch == Branch.RECTANGLE) {
int adjust = (rootSpacing / 2) + 1;
String horizontal = String.join("", Collections.nCopies(rootSpacing / 2, "─"));
String branch = "┌" + horizontal + "┴" + horizontal + "┐";
allTreeLines.add(new TreeLine(branch, -adjust, adjust));
String branch0 = "┌" + horizontal + "┴" + horizontal + "┐";
allTreeLines.add(new TreeLine(branch0, -adjust, adjust));
rightTreeAdjust = adjust;
leftTreeAdjust = -adjust;
} else {
Expand Down Expand Up @@ -324,7 +329,12 @@ private List<TreeLine> buildTreeLines(T root) {
} else {
left = leftTreeLines.get(i);
right = rightTreeLines.get(i);
int adjustedRootSpacing = (rootSpacing == 1 ? (branch == Branch.RECTANGLE ? 1 : 3) : rootSpacing);
int adjustedRootSpacing;
if (rootSpacing == 1) {
adjustedRootSpacing = (branch == Branch.RECTANGLE) ? 1 : 3;
} else {
adjustedRootSpacing = rootSpacing;
}
TreeLine combined = new TreeLine(
left.line + spaces(adjustedRootSpacing - left.rightOffset + right.leftOffset) + right.line,
left.leftOffset + leftTreeAdjust,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ public static <T, R> Function<T, R> convert(final Consumer<T> consumer, final R
};
}

public static <T> Predicate<T> convert(final Consumer<T> consumer, boolean result) {
return t -> {
consumer.accept(t);
return result;
};
}

public static <T> T doIfTrue(Supplier<T> supplier, Predicate<T> predicate, Runnable action) {
T result = supplier.get();
if (predicate.test(result)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,14 +292,14 @@ private static <T> Class<T> getActualType(Class<?> clazz, Type type) {
}

@SuppressWarnings("unchecked")
private static <T> Class<T> getVariableActualType(Class<?> clazz, TypeVariable<?> var) {
private static <T> Class<T> getVariableActualType(Class<?> clazz, TypeVariable<?> tv) {
if (clazz == null) {
return (Class<T>) Object.class;
}

return (Class<T>) VARIABLE_TYPE_MAPPING
.computeIfAbsent(clazz, GenericUtils::getActualTypeVariableMapping)
.getOrDefault(getTypeVariableName(null, var).get(0), Object.class);
.getOrDefault(getTypeVariableName(null, tv).get(0), Object.class);
}

private static void resolveMapping(Map<String, Class<?>> result, Type type) {
Expand All @@ -319,15 +319,15 @@ private static void resolveMapping(Map<String, Class<?>> result, Type type) {
}
}

private static List<String> getTypeVariableName(Class<?> clazz, TypeVariable<?> var) {
private static List<String> getTypeVariableName(Class<?> clazz, TypeVariable<?> tv) {
List<String> names = new ArrayList<>();
getTypeVariableName(names, clazz, var);
getTypeVariableName(names, clazz, tv);
return names;
}

private static void getTypeVariableName(List<String> names, Class<?> clazz, TypeVariable<?> var) {
private static void getTypeVariableName(List<String> names, Class<?> clazz, TypeVariable<?> tv) {
// Class, Method, Constructor
names.add(var.getGenericDeclaration().toString() + "[" + var.getName() + "]");
names.add(tv.getGenericDeclaration().toString() + "[" + tv.getName() + "]");
if (clazz == null || clazz == Object.class) {
return;
}
Expand All @@ -347,7 +347,7 @@ private static void getTypeVariableName(List<String> names, Class<?> clazz, Type
continue;
}
// find the type variable origin defined class
if (((TypeVariable<?>) types[i]).getName().equals(var.getTypeName())) {
if (((TypeVariable<?>) types[i]).getName().equals(tv.getTypeName())) {
clazz = (Class<?>) ptype.getRawType();
getTypeVariableName(names, clazz, clazz.getTypeParameters()[i]);
break;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,10 @@ public static int progress(Process process, Charset charset, Consumer<String> ve
// return error code: -1
return -1;
} finally {
if (process != null) {
try {
process.destroy();
} catch (Throwable t) {
verbose.accept("Destroy process error: " + ExceptionUtils.getStackTrace(t));
}
try {
process.destroy();
} catch (Throwable t) {
verbose.accept("Destroy process error: " + ExceptionUtils.getStackTrace(t));
}
}
}
Expand Down Expand Up @@ -115,7 +113,9 @@ public static void killProcess(Long pid, Charset charset) {
if (SystemUtils.IS_OS_WINDOWS) {
Process killProcess = new ProcessBuilder("taskkill", "/PID", String.valueOf(pid), "/F", "/T").start();
waitFor(killProcess, () -> "kill process id " + pid);
LOG.info("Stop windows process verbose: {} | {}", pid, processVerbose(killProcess, charset));
if (LOG.isInfoEnabled()) {
LOG.info("Stop windows process verbose: {} | {}", pid, processVerbose(killProcess, charset));
}
destroy(killProcess);
} else if (SystemUtils.IS_OS_UNIX) {
// 1、find child process id
Expand All @@ -132,13 +132,15 @@ public static void killProcess(Long pid, Charset charset) {
// 2、kill current process id
Process killProcess = new ProcessBuilder("kill", "-9", String.valueOf(pid)).start();
waitFor(killProcess, () -> "kill process id " + pid);
LOG.info("Stop unix process verbose: {} | {}", pid, processVerbose(killProcess, charset));
if (LOG.isInfoEnabled()) {
LOG.info("Stop unix process verbose: {} | {}", pid, processVerbose(killProcess, charset));
}
destroy(killProcess);
} else {
LOG.error("Stop process id unknown os name: {}, {}", SystemUtils.OS_NAME, pid);
}
} catch (InterruptedException e) {
LOG.error("Kill process id '" + pid + "' interrupted.");
LOG.error("Kill process id '{}' interrupted.", pid);
ExceptionUtils.rethrow(e);
} catch (Throwable t) {
LOG.error("Kill process id '" + pid + "' error.", t);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public abstract class Server implements Serializable {
*/
protected final int port;

public Server(String host, int port) {
protected Server(String host, int port) {
Assert.isTrue(!host.contains(Str.COLON), "Host cannot contains symbol ':'");
this.host = host;
this.port = port;
Expand Down
Loading

0 comments on commit 1248ffb

Please sign in to comment.