Skip to content

Commit e333a9c

Browse files
bsmahifabapp2
andauthored
Code Improvements in Spring Shell Module (#713)
* Code Improvements Done some code improvements like Pattern Matching for switchExpressions and Method References * Added author details * Replaced with Lambda Expression * Resolved feedback comments --------- Co-authored-by: Fabian Krüger <[email protected]>
1 parent 087c267 commit e333a9c

18 files changed

+87
-79
lines changed

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplicableRecipeListRenderer.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public void listenForStartedScanningEvent(StartedScanningProjectResourceSetEvent
4747
// reset progressbar
4848
pb = null;
4949
long numJavaSources = e.getSize();
50-
if(numJavaSources != 0) {
50+
if (numJavaSources != 0) {
5151
String message = e.getMessage();
5252
message = message.length() > MAX_LENGTH ? message.substring(0, MAX_LENGTH) : message + " ".repeat(MAX_LENGTH - message.length());
5353
pb = createProgressBar(message, numJavaSources);
@@ -60,7 +60,7 @@ public ProgressBar createProgressBar(String message, long numJavaSources) {
6060

6161
@EventListener
6262
public void listenForFinishedScanningProjectResourceSetEvent(FinishedScanningProjectResourceSetEvent e) {
63-
if(pb != null) {
63+
if (pb != null) {
6464
// pb.stepTo(pb.getMax());
6565
pb.close();
6666
}
@@ -69,7 +69,7 @@ public void listenForFinishedScanningProjectResourceSetEvent(FinishedScanningPro
6969
@EventListener
7070
// TODO: listen for finish instead of start here
7171
public void listenForStartedScanningEvent(StartedScanningProjectResourceEvent e) {
72-
if(pb != null) {
72+
if (pb != null) {
7373
pb.stepBy(1);
7474
}
7575
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyCommandRenderer.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import org.springframework.context.event.EventListener;
2323
import org.springframework.sbm.engine.events.*;
2424
import org.springframework.sbm.engine.recipe.Action;
25-
import org.springframework.sbm.engine.recipe.Recipe;
2625
import org.springframework.sbm.shell.renderer.Printer;
2726
import org.springframework.sbm.shell.renderer.RecipeProgressRenderer;
2827
import org.springframework.stereotype.Component;
@@ -36,11 +35,11 @@
3635

3736
/**
3837
* Renders progress information during the runtime of a recipe.
39-
*
38+
* <p>
4039
* {@code RecipeProgressRenderer} handles the rendering of action progress.
4140
* A {@code ScheduledExecutorService} is used to periodically call the {@link RecipeProgressRenderer#render()} method
4241
* which renders a process as loading to provide visual feedback to users during a potentially long-running Action.
43-
*
42+
* <p>
4443
* Logging to console will be disabled and log messages to info, warn and error level are redirected to the matching
4544
* {@link RecipeProgressRenderer#logError(String)},
4645
* {@link RecipeProgressRenderer#logWarning(String)} or
@@ -79,12 +78,12 @@ public AttributedString render(String recipeName, List<Action> actions) {
7978
}
8079

8180
private String getDescriptionWithIndent(Action a) {
82-
if(a == null || a.getDescription() == null) return "";
81+
if (a == null || a.getDescription() == null) return "";
8382

8483
String[] lines = a.getDescription().split("\\r?\\n");
8584
List<String> strings = Arrays.asList(lines);
8685
String collect = "";
87-
if(lines.length > 1) {
86+
if (lines.length > 1) {
8887
collect = strings.subList(1, strings.size()).stream()
8988
.map(l -> String.format(" %s", l))
9089
.collect(Collectors.joining("\n"));
@@ -94,11 +93,11 @@ private String getDescriptionWithIndent(Action a) {
9493

9594
@EventListener
9695
public void onActionStarted(ActionStartedEvent e) {
97-
if(scheduledExecutorService != null && ! scheduledExecutorService.isTerminated()) {
96+
if (scheduledExecutorService != null && !scheduledExecutorService.isTerminated()) {
9897
scheduledExecutorService.shutdown();
9998
}
10099
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
101-
scheduledExecutorService.scheduleWithFixedDelay(() -> recipeProgressRenderer.render(), initialDelay, delay, TimeUnit.MILLISECONDS);
100+
scheduledExecutorService.scheduleWithFixedDelay(recipeProgressRenderer::render, initialDelay, delay, TimeUnit.MILLISECONDS);
102101
recipeProgressRenderer.startProcess(e.getDescription());
103102
}
104103

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ApplyShellCommand.java

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,22 +64,26 @@ public AttributedString apply(@ShellOption(arity = 1, valueProvider = ApplyRecip
6464
List<Recipe> applicableRecipes = applicableRecipeListCommand.execute(projectContext);
6565
AttributedString applicableRecipesOutput = applicableRecipeListRenderer.render(applicableRecipes);
6666

67-
AttributedString output = new AttributedStringBuilder().append(applyCommandOutput).append(System.lineSeparator()).append(applicableRecipesOutput).toAttributedString();
68-
69-
return output;
67+
return new AttributedStringBuilder()
68+
.append(applyCommandOutput)
69+
.append(System.lineSeparator())
70+
.append(applicableRecipesOutput)
71+
.toAttributedString();
7072
}
7173

7274
@NotNull
7375
private AttributedStringBuilder buildHeader(String recipeName) {
7476
AttributedStringBuilder builder = new AttributedStringBuilder();
7577
builder.append("Applying recipe ");
7678
builder.style(AttributedStyle.DEFAULT.italicDefault().boldDefault().foreground(Colors.rgbColor("yellow")));
77-
builder.append("'" + recipeName + "'");
79+
builder.append("'")
80+
.append(recipeName)
81+
.append("'");
7882
return builder;
7983
}
8084

8185
public Availability availabilityCheck() {
82-
if(projectContextHolder.getProjectContext() != null) {
86+
if (projectContextHolder.getProjectContext() != null) {
8387
return Availability.available();
8488
} else {
8589
return Availability.unavailable("You need to scan first");
@@ -89,7 +93,7 @@ public Availability availabilityCheck() {
8993

9094
@Component
9195
@RequiredArgsConstructor
92-
class ApplyRecipeValueProvider implements ValueProvider{
96+
class ApplyRecipeValueProvider implements ValueProvider {
9397

9498
private final ProjectContextHolder projectContextHolder;
9599
private final ApplicableRecipeListCommand applicableRecipeListCommand;
@@ -98,7 +102,11 @@ class ApplyRecipeValueProvider implements ValueProvider{
98102
public List<CompletionProposal> complete(CompletionContext completionContext) {
99103
ProjectContext projectContext = projectContextHolder.getProjectContext();
100104
List<Recipe> applicableRecipes = applicableRecipeListCommand.execute(projectContext);
101-
return applicableRecipes.stream().map(Recipe::getName).map(CompletionProposal::new).toList();
105+
106+
return applicableRecipes.stream()
107+
.map(Recipe::getName)
108+
.map(CompletionProposal::new)
109+
.toList();
102110
}
103111

104112
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/DescribeCommandRenderer.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public class DescribeCommandRenderer {
2525
public AttributedString render(Recipe recipe) {
2626
AttributedStringBuilder builder = new AttributedStringBuilder();
2727
builder.append(recipe.getDetails());
28+
2829
return builder.toAttributedString();
2930
}
3031
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/DescribeShellCommand.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public class DescribeShellCommand {
3333
@ShellMethod(key = {"describe", "d"}, value = "Describe a given recipe.")
3434
public AttributedString describe(@ShellOption(help = "The name of the recipe.") String recipe) {
3535
final Recipe recipeResult = describeCommand.execute(recipe);
36+
3637
return describeCommandRenderer.render(recipeResult);
3738
}
3839
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ExceptionUtil.java

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -23,23 +23,25 @@
2323
*/
2424
public class ExceptionUtil {
2525

26-
public static Throwable getDeepestCause(Throwable e) {
27-
Throwable cause = e;
28-
Throwable parent = e.getCause();
29-
while (parent != null && parent != e) {
30-
cause = parent;
31-
parent = cause.getCause();
32-
}
33-
return cause;
34-
}
26+
public static Throwable getDeepestCause(Throwable e) {
27+
Throwable cause = e;
28+
Throwable parent = e.getCause();
29+
while (parent != null && parent != e) {
30+
cause = parent;
31+
parent = cause.getCause();
32+
}
33+
34+
return cause;
35+
}
36+
37+
public static String getMessage(Throwable e) {
38+
// The message of nested exception is usually more interesting than the
39+
// one on top.
40+
Throwable cause = getDeepestCause(e);
41+
String errorType = cause.getClass().getSimpleName();
42+
String msg = cause.getMessage();
43+
44+
return errorType + ": " + msg;
45+
}
3546

36-
public static String getMessage(Throwable e) {
37-
// The message of nested exception is usually more interesting than the
38-
// one on top.
39-
Throwable cause = getDeepestCause(e);
40-
String errorType = cause.getClass().getSimpleName();
41-
String msg = cause.getMessage();
42-
return errorType + ": " + msg;
43-
}
44-
4547
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ListShellCommand.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ public class ListShellCommand {
3434
@ShellMethod(key = {"list", "l"}, value = "List all existing (applicable and non-applicable) recipes.")
3535
public AttributedString list() {
3636
final List<Recipe> recipes = listCommand.execute();
37+
3738
return recipeListRenderer.render(recipes);
3839
}
3940
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/PreconditionVerificationRenderer.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,30 +31,29 @@ public String renderPreconditionCheckResults(PreconditionVerificationResult resu
3131
stringBuilder.style(stringBuilder.style().DEFAULT.bold().foreground(Colors.rgbColor("black")));
3232
stringBuilder.append("\n\n").append(String.format("Checked preconditions for '%s'", result.getProjectRoot())).append("\n");
3333

34-
result.getResults().forEach(r -> {
35-
stringBuilder.append(renderCheckResult(r));
36-
});
34+
result.getResults().forEach(r -> stringBuilder.append(renderCheckResult(r)));
3735
stringBuilder.append("\n");
36+
3837
return stringBuilder.toAnsi();
3938
}
4039

4140
private String renderCheckResult(PreconditionCheckResult r) {
4241
AttributedStringBuilder builder = new AttributedStringBuilder();
4342

4443
// TODO: move rendering of status into central place
45-
if(r.getState().equals(PreconditionCheck.ResultState.FAILED)) {
44+
if (r.getState().equals(PreconditionCheck.ResultState.FAILED)) {
4645
builder.style(builder.style().DEFAULT.bold().foreground(Colors.rgbColor("red")));
4746
builder.append(" [X]");
4847
builder.style(builder.style().DEFAULT);
4948
}
5049

51-
if(r.getState().equals(PreconditionCheck.ResultState.PASSED)) {
50+
if (r.getState().equals(PreconditionCheck.ResultState.PASSED)) {
5251
builder.style(AttributedStyle.DEFAULT.bold().foreground(Colors.rgbColor("green")));
5352
builder.append("[ok]");
5453
builder.style(AttributedStyle.DEFAULT);
5554
}
5655

57-
if(r.getState().equals(PreconditionCheck.ResultState.WARN)) {
56+
if (r.getState().equals(PreconditionCheck.ResultState.WARN)) {
5857
builder.style(AttributedStyle.DEFAULT.bold().foreground(Colors.rgbColor("yellow")));
5958
builder.append(" [!]");
6059
builder.style(AttributedStyle.DEFAULT);

applications/spring-shell/src/main/java/org/springframework/sbm/shell/RecipeRenderer.java

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ public AttributedStringBuilder buildRecipePresentation(AttributedStringBuilder b
6565
builder.style(AttributedStyle.DEFAULT.italicDefault().boldDefault().foreground(Colors.rgbColor("yellow")));
6666
builder.append(recipe.getName());
6767
builder.style(AttributedStyle.DEFAULT);
68-
builder.append(" [" + getAutomationEmoji(recipe.getAutomationInfo()) + "]");
69-
builder.append("\n -> " + recipe.getDescription());
68+
builder.append(" [").append(getAutomationEmoji(recipe.getAutomationInfo())).append("]");
69+
builder.append("\n -> ").append(recipe.getDescription());
7070
builder.append("\n");
7171
return builder;
7272
}
@@ -81,13 +81,10 @@ private AttributedString renderTitle(String title) {
8181
}
8282

8383
private String getAutomationEmoji(RecipeAutomation recipeAutomation) {
84-
switch (recipeAutomation) {
85-
case AUTOMATED:
86-
return AUTOMATED_EMOJI;
87-
case PARTIALLY_AUTOMATED:
88-
return MANUAL_EMOJI + " " + AUTOMATED_EMOJI;
89-
default:
90-
return MANUAL_EMOJI;
91-
}
84+
return switch (recipeAutomation) {
85+
case AUTOMATED -> AUTOMATED_EMOJI;
86+
case PARTIALLY_AUTOMATED -> MANUAL_EMOJI + " " + AUTOMATED_EMOJI;
87+
default -> MANUAL_EMOJI;
88+
};
9289
}
9390
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ScanCommandHeaderRenderer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public String renderHeader(String projectRoot) {
2626
AttributedStringBuilder builder = new AttributedStringBuilder();
2727
builder.append("\n");
2828
builder.style(AttributedStyle.DEFAULT.italicDefault().boldDefault().foreground(Colors.rgbColor("green")));
29-
builder.append("scanning '" + projectRoot + "'");
29+
builder.append("scanning '").append(projectRoot).append("'");
3030
return builder.toAnsi();
3131
}
3232
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ScanShellCommand.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,8 @@
3636
public class ScanShellCommand {
3737

3838
private final ScanCommand scanCommand;
39-
4039
private final ApplicableRecipeListRenderer applicableRecipeListRenderer;
41-
4240
private final ApplicableRecipeListCommand applicableRecipeListCommand;
43-
4441
private final ProjectContextHolder contextHolder;
4542
private final PreconditionVerificationRenderer preconditionVerificationRenderer;
4643
private final ScanCommandHeaderRenderer scanCommandHeaderRenderer;

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ShellPromptProvider.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
@Component
2727
public class ShellPromptProvider implements PromptProvider {
2828

29+
private static final String MIGRATOR_CONSTANT = "migrator";
30+
2931
@Autowired
3032
ProjectContextHolder holder;
3133

@@ -35,12 +37,9 @@ public AttributedString getPrompt() {
3537
}
3638

3739
private String promptString() {
38-
ProjectContext pc = holder.getProjectContext();
39-
if (pc==null) {
40-
return "migrator";
41-
} else {
42-
return pc.getProjectRootDirectory().getFileName().toString();
43-
}
40+
ProjectContext projectContext = holder.getProjectContext();
41+
42+
return projectContext == null ? MIGRATOR_CONSTANT : projectContext.getProjectRootDirectory().getFileName().toString();
4443
}
4544

4645
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/ShellUserInteractions.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ public boolean askUserYesOrNo(String question) {
4040
while (!YES_RESPONSE.equalsIgnoreCase(input) && !NO_RESPONSE.equalsIgnoreCase(input)) {
4141
input = lineReader.get().readLine("\n" + question + " > ").trim();
4242
}
43+
4344
return YES_RESPONSE.equalsIgnoreCase(input);
4445
}
4546

applications/spring-shell/src/main/java/org/springframework/sbm/shell/renderer/LogStep.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public String render() {
3939
AttributedStringBuilder builder = new AttributedStringBuilder();
4040
builder.style(AttributedStyle.DEFAULT.bold().foreground(Colors.rgbColor("green")));
4141
builder.append("[ok]");
42+
4243
return " ".repeat(indent.get()) + " " + builder.toAttributedString().toAnsi() + " " + logMessage;
4344
}
4445

@@ -51,6 +52,7 @@ public String renderError() {
5152
.style(AttributedStyle.DEFAULT)
5253
.append(" ")
5354
.append(logMessage);
55+
5456
return builder.toAttributedString().toAnsi();
5557
}
5658

@@ -63,6 +65,7 @@ public String renderWarning() {
6365
.style(AttributedStyle.DEFAULT)
6466
.append(" ")
6567
.append(logMessage);
68+
6669
return builder.toAttributedString().toAnsi();
6770
}
6871
}

applications/spring-shell/src/main/java/org/springframework/sbm/shell/renderer/Printer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public void println(String out) {
3131
}
3232

3333
synchronized public void print(String text) {
34-
if(previousLine != null && previousLine.get() != null && !previousLine.get().isEmpty()) {
34+
if(previousLine.get() != null && !previousLine.get().isEmpty()) {
3535
clearPreviousLine();
3636
}
3737
previousLine.set(text);

applications/spring-shell/src/main/java/org/springframework/sbm/shell/renderer/ProcessStep.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public boolean isPaused() {
8080
return isPaused;
8181
}
8282

83-
private class Loader {
83+
private static class Loader {
8484
private static final int LENGTH = 4;
8585
private int cnt = 0;
8686
private String renderLoader() {

0 commit comments

Comments
 (0)