Skip to content

Commit

Permalink
(chores) camel-jbang: minor cleanups
Browse files Browse the repository at this point in the history
- Simplify switch expressions
- Break a few large methods
- Use simpler methods/expressions
- Use lambdas
- Use more efficient operations

Signed-off-by: Otavio R. Piske <[email protected]>
  • Loading branch information
orpiske committed Nov 10, 2024
1 parent c7702ba commit dca750d
Show file tree
Hide file tree
Showing 15 changed files with 124 additions and 132 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ private void replacePlaceholders() throws Exception {
var provider = spec.defaultValueProvider();
String defaultValue = provider != null ? provider.defaultValue(argSpec) : null;
if (defaultValue != null &&
argSpec instanceof CommandLine.Model.OptionSpec) {
CommandLine.Model.OptionSpec optionSpec = (CommandLine.Model.OptionSpec) argSpec;
argSpec instanceof CommandLine.Model.OptionSpec optionSpec) {
for (String name : optionSpec.names()) {
String placeholder = "#" + StringHelper.after(name, "--");
Object v = argSpec.getValue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,60 +152,13 @@ public Integer doCall() throws Exception {
// read log input
final AtomicBoolean quit = new AtomicBoolean();
final Console c = System.console();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
do {
InputStreamReader isr = new InputStreamReader(spawnOutput);
try {
BufferedReader reader = buffered(isr);
while (true) {
String line = reader.readLine();
if (line != null) {
while (logBuffer.size() >= 100) {
logBuffer.remove(0);
}
logBuffer.add(line);
logUpdated.set(true);
} else {
break;
}
}
} catch (Exception e) {
// ignore
}
} while (!quit.get());
}
Thread t = new Thread(() -> {
doReadLog(quit);
}, "ReadLog");
t.start();

// read CLI input from user
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
do {
String line = c.readLine();
if (line != null) {
line = line.trim();
if ("quit".equalsIgnoreCase(line) || "exit".equalsIgnoreCase(line)) {
quit.set(true);
} else {
// continue breakpoint
if (suspendedRow != null) {
// step to exit because it was the last
if (suspendedRow.last) {
// we need to clear screen so fool by saying log is updated
logUpdated.set(true);
}
}
sendDebugCommand(spawnPid, "step", null);
}
// user have pressed ENTER so continue
waitForUser.set(false);
}
} while (!quit.get());
}
}, "ReadCommand");
Thread t2 = new Thread(() -> doRead(c, quit), "ReadCommand");
t2.start();

do {
Expand All @@ -228,6 +181,53 @@ public void run() {
return 0;
}

private void doReadLog(AtomicBoolean quit) {
do {
InputStreamReader isr = new InputStreamReader(spawnOutput);
try {
BufferedReader reader = buffered(isr);
while (true) {
String line = reader.readLine();
if (line != null) {
while (logBuffer.size() >= 100) {
logBuffer.remove(0);
}
logBuffer.add(line);
logUpdated.set(true);
} else {
break;
}
}
} catch (Exception e) {
// ignore
}
} while (!quit.get());
}

private void doRead(Console c, AtomicBoolean quit) {
do {
String line = c.readLine();
if (line != null) {
line = line.trim();
if ("quit".equalsIgnoreCase(line) || "exit".equalsIgnoreCase(line)) {
quit.set(true);
} else {
// continue breakpoint
if (suspendedRow != null) {
// step to exit because it was the last
if (suspendedRow.last) {
// we need to clear screen so fool by saying log is updated
logUpdated.set(true);
}
}
sendDebugCommand(spawnPid, "step", null);
}
// user have pressed ENTER so continue
waitForUser.set(false);
}
} while (!quit.get());
}

@Override
protected int runDebug(KameletMain main) throws Exception {
List<String> cmds = new ArrayList<>(spec.commandLine().getParseResult().originalArgs());
Expand Down Expand Up @@ -266,13 +266,11 @@ protected int runDebug(KameletMain main) throws Exception {
}

private void removeDebugOnlyOptions(List<String> cmds) {
ReflectionHelper.doWithFields(Debug.class, fc -> {
cmds.removeIf(c -> {
String n1 = "--" + fc.getName();
String n2 = "--" + StringHelper.camelCaseToDash(fc.getName());
return c.startsWith(n1) || c.startsWith(n2);
});
});
ReflectionHelper.doWithFields(Debug.class, fc -> cmds.removeIf(c -> {
String n1 = "--" + fc.getName();
String n2 = "--" + StringHelper.camelCaseToDash(fc.getName());
return c.startsWith(n1) || c.startsWith(n2);
}));
}

protected int doWatch() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,35 +203,47 @@ public int compare(MavenGav o1, MavenGav o2) {

int rankGroupId(MavenGav o1) {
String g1 = o1.getGroupId();
if ("org.springframework.boot".equals(g1)) {
return 30;
} else if ("io.quarkus".equals(g1)) {
return 30;
} else if ("org.apache.camel.quarkus".equals(g1)) {
String a1 = o1.getArtifactId();
// main/core/engine first
if ("camel-quarkus-core".equals(a1)) {
return 21;
if (g1 == null) {
return 0;
}

switch (g1) {
case "org.springframework.boot" -> {
return 30;
}
return 20;
} else if ("org.apache.camel.springboot".equals(g1)) {
String a1 = o1.getArtifactId();
// main/core/engine first
if ("camel-spring-boot-engine-starter".equals(a1)) {
return 21;
case "io.quarkus" -> {
return 30;
}
return 20;
} else if ("org.apache.camel".equals(g1)) {
String a1 = o1.getArtifactId();
// main/core/engine first
if ("camel-main".equals(a1)) {
return 11;
case "org.apache.camel.quarkus" -> {
String a1 = o1.getArtifactId();
// main/core/engine first
if ("camel-quarkus-core".equals(a1)) {
return 21;
}
return 20;
}
case "org.apache.camel.springboot" -> {
String a1 = o1.getArtifactId();
// main/core/engine first
if ("camel-spring-boot-engine-starter".equals(a1)) {
return 21;
}
return 20;
}
case "org.apache.camel" -> {
String a1 = o1.getArtifactId();
// main/core/engine first
if ("camel-main".equals(a1)) {
return 11;
}
return 10;
}
case "org.apache.camel.kamelets" -> {
return 5;
}
default -> {
return 0;
}
return 10;
} else if ("org.apache.camel.kamelets".equals(g1)) {
return 5;
} else {
return 0;
}
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -274,11 +274,8 @@ private void createBuildGradle(File settings, File gradleBuild, Set<String> deps
context = context.replaceAll("\\{\\{ \\.SpringBootVersion }}", springBootVersion);
context = context.replaceFirst("\\{\\{ \\.JavaVersion }}", javaVersion);
context = context.replaceAll("\\{\\{ \\.CamelVersion }}", camelVersion);
if (camelSpringBootVersion != null) {
context = context.replaceFirst("\\{\\{ \\.CamelSpringBootVersion }}", camelSpringBootVersion);
} else {
context = context.replaceFirst("\\{\\{ \\.CamelSpringBootVersion }}", camelVersion);
}
context = context.replaceFirst("\\{\\{ \\.CamelSpringBootVersion }}",
Objects.requireNonNullElse(camelSpringBootVersion, camelVersion));

if (repos == null || repos.isEmpty()) {
context = context.replaceFirst("\\{\\{ \\.MavenRepositories }}", "");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,8 @@ public Integer doCall() throws Exception {
printer().println(StringHelper.padString(1, 55) + "STACK-TRACE");
printer().println(StringHelper.fillChars('-', 120));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < stackTrace.size(); i++) {
sb.append(String.format("\t%s%n", stackTrace.get(i)));
for (String s : stackTrace) {
sb.append(String.format("\t%s%n", s));
}
printer().println(String.valueOf(sb));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,7 @@ protected int sortRow(Row o1, Row o2) {
// sort for highest mean value as we want the slowest in the top
long m1 = o1.mean != null ? Long.parseLong(o1.mean) : 0;
long m2 = o2.mean != null ? Long.parseLong(o2.mean) : 0;
if (m1 < m2) {
return 1;
} else if (m1 > m2) {
return -1;
} else {
return 0;
}
return Long.compare(m2, m1);
}

private static class Row {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
Expand Down Expand Up @@ -249,7 +250,7 @@ public String getDataAsTable(
new Column().dataAlign(HorizontalAlign.LEFT).with(TableRow::typeAndLengthAsString)));
// body value only (span)
if (bodyRow.value != null) {
tab6 = AsciiTable.getTable(AsciiTable.NO_BORDERS, List.of(bodyRow), Arrays.asList(
tab6 = AsciiTable.getTable(AsciiTable.NO_BORDERS, List.of(bodyRow), Collections.singletonList(
new Column().dataAlign(HorizontalAlign.LEFT).maxWidth(160, OverflowBehaviour.NEWLINE)
.with(b -> pretty ? bodyRow.valueAsStringPretty() : bodyRow.valueAsString())));
}
Expand All @@ -275,7 +276,7 @@ public String getDataAsTable(
if (value != null) {
value = Jsoner.unescape(value);
eRow = new TableRow("Stacktrace", null, null, value);
tab8 = AsciiTable.getTable(AsciiTable.NO_BORDERS, List.of(eRow), Arrays.asList(
tab8 = AsciiTable.getTable(AsciiTable.NO_BORDERS, List.of(eRow), Collections.singletonList(
new Column().dataAlign(HorizontalAlign.LEFT).maxWidth(160, OverflowBehaviour.NEWLINE)
.with(TableRow::valueAsStringRed)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected int sortRow(Row o1, Row o2) {
long m1 = o1.mean != null ? Long.parseLong(o1.mean) : 0;
long m2 = o2.mean != null ? Long.parseLong(o2.mean) : 0;
if (m1 < m2) {
answer = 1 * negate;
answer = negate;
} else if (m1 > m2) {
answer = -1 * negate;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ protected int sortRow(Row o1, Row o2) {
long m1 = o1.mean != null ? Long.parseLong(o1.mean) : 0;
long m2 = o2.mean != null ? Long.parseLong(o2.mean) : 0;
if (m1 < m2) {
answer = 1 * negate;
answer = negate;
} else if (m1 > m2) {
answer = -1 * negate;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ private String getFailure(Row r) {
if (r.failedCalls <= 0) {
return "";
} else if (r.failureRate > 0) {
return +r.failedCalls + " (" + String.format("%.0f", r.failureRate) + "%)";
return r.failedCalls + " (" + String.format("%.0f", r.failureRate) + "%)";
} else {
return Integer.toString(r.failedCalls);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,9 +230,7 @@ public Integer doProcessWatchCall() throws Exception {
sb.append(String.format("\tSINCE: %s%n", row.sinceStartFailure));
if (row.customMeta != null) {
sb.append(String.format("\tMETADATA:%n"));
row.customMeta.forEach((k, v) -> {
sb.append(String.format("\t\t%s = %s%n", k, v));
});
row.customMeta.forEach((k, v) -> sb.append(String.format("\t\t%s = %s%n", k, v)));
}
sb.append(String.format("\tMESSAGE: %s%n", row.message));
for (int i = 0; i < depth && i < row.stackTrace.size(); i++) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,14 +200,11 @@ private static String sanitizeLocation(String loc) {
if (loc == null) {
return "";
}
if ("initial".equals(loc) || "override".equals(loc)) {
loc = "camel-main";
} else if ("SYS".equals(loc)) {
loc = "JVM System Property";
} else if ("ENV".equals(loc) || "env".equals(loc)) {
loc = "OS Environment Variable";
} else if ("arguments".equals(loc) || "CLI".equals(loc)) {
loc = "Command Line";
switch (loc) {
case "initial", "override" -> loc = "camel-main";
case "SYS" -> loc = "JVM System Property";
case "ENV", "env" -> loc = "OS Environment Variable";
case "arguments", "CLI" -> loc = "Command Line";
}
return loc;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,8 @@ public class MetadataHelper {
ProcessorReifier.registerReifier(CircuitBreakerDefinition.class, DisabledReifier::new);

COMPONENT_CUSTOMIZERS = new HashMap<>();
COMPONENT_CUSTOMIZERS.put(Capability.PlatformHttp.getValue(), (catalog, meta) -> {
meta.capabilities.add(Capability.PlatformHttp);
});
COMPONENT_CUSTOMIZERS.put(Capability.PlatformHttp.getValue(),
(catalog, meta) -> meta.capabilities.add(Capability.PlatformHttp));
}

private MetadataHelper() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ public Component resolveComponent(String name, CamelContext context) {
final boolean accept = accept(name);
final Component answer = super.resolveComponent(accept ? name : "stub", context);

if ((silent || stubPattern != null) && answer instanceof StubComponent) {
StubComponent sc = (StubComponent) answer;
if ((silent || stubPattern != null) && answer instanceof StubComponent sc) {
// enable shadow mode on stub component
sc.setShadow(true);
sc.setShadowPattern(stubPattern);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,18 +87,16 @@ public void apply(Traits traitConfig, TraitContext context) {

// Deployment
Optional<DeploymentBuilder> deployment = context.getDeployment();
deployment.ifPresent(d -> {
d.editOrNewSpec()
.editOrNewTemplate()
.editOrNewSpec()
.addAllToVolumes(volumes)
.editFirstContainer()
.addAllToVolumeMounts(volumeMounts)
.endContainer()
.endSpec()
.endTemplate()
.endSpec();
});
deployment.ifPresent(d -> d.editOrNewSpec()
.editOrNewTemplate()
.editOrNewSpec()
.addAllToVolumes(volumes)
.editFirstContainer()
.addAllToVolumeMounts(volumeMounts)
.endContainer()
.endSpec()
.endTemplate()
.endSpec());
}

private void configureVolumesAndMounts(Mount mountTrait, List<Volume> volumes, List<VolumeMount> volumeMounts) {
Expand Down

0 comments on commit dca750d

Please sign in to comment.