Skip to content

Commit 4733c3c

Browse files
committed
Add custom renderer example for component
1 parent 547e82a commit 4733c3c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

spring-shell-samples/src/main/java/org/springframework/shell/samples/standard/ComponentCommands.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,15 @@
1616
package org.springframework.shell.samples.standard;
1717

1818
import java.util.ArrayList;
19+
import java.util.Arrays;
1920
import java.util.List;
2021
import java.util.Optional;
22+
import java.util.function.Function;
2123
import java.util.stream.Collectors;
2224

25+
import org.jline.utils.AttributedString;
26+
import org.jline.utils.AttributedStringBuilder;
27+
2328
import org.springframework.shell.component.ConfirmationInput;
2429
import org.springframework.shell.component.ConfirmationInput.ConfirmationInputContext;
2530
import org.springframework.shell.component.MultiItemSelector;
@@ -34,6 +39,7 @@
3439
import org.springframework.shell.standard.AbstractShellComponent;
3540
import org.springframework.shell.standard.ShellComponent;
3641
import org.springframework.shell.standard.ShellMethod;
42+
import org.springframework.util.StringUtils;
3743

3844
@ShellComponent
3945
public class ComponentCommands extends AbstractShellComponent {
@@ -100,4 +106,42 @@ public String multiSelector() {
100106
.collect(Collectors.joining(","));
101107
return "Got value " + result;
102108
}
109+
110+
@ShellMethod(key = "component stringcustom", value = "String input", group = "Components")
111+
public String stringInputCustom(boolean mask) {
112+
StringInput component = new StringInput(getTerminal(), "Enter value", "myvalue",
113+
new StringInputCustomRenderer());
114+
component.setResourceLoader(getResourceLoader());
115+
component.setTemplateExecutor(getTemplateExecutor());
116+
if (mask) {
117+
component.setMaskCharater('*');
118+
}
119+
StringInputContext context = component.run(StringInputContext.empty());
120+
return "Got value " + context.getResultValue();
121+
}
122+
123+
private static class StringInputCustomRenderer implements Function<StringInputContext, List<AttributedString>> {
124+
125+
@Override
126+
public List<AttributedString> apply(StringInputContext context) {
127+
AttributedStringBuilder builder = new AttributedStringBuilder();
128+
builder.append(context.getName());
129+
builder.append(" ");
130+
131+
if (context.getResultValue() != null) {
132+
builder.append(context.getResultValue());
133+
}
134+
else {
135+
String input = context.getInput();
136+
if (StringUtils.hasText(input)) {
137+
builder.append(input);
138+
}
139+
else {
140+
builder.append("[Default " + context.getDefaultValue() + "]");
141+
}
142+
}
143+
144+
return Arrays.asList(builder.toAttributedString());
145+
}
146+
}
103147
}

0 commit comments

Comments
 (0)