Example 2 - S3nS3IW00/JCommands GitHub Wiki
This example shows you how to work with concatenators and why they are useful. It makes a command with a year, month and a day input argument with number type and concatenates them with a custom concatenator into a date.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Create the command and arguments
ServerCommand dateCommand = new ServerCommand("date", "Constructs a date");
StringArgument<String> yearArgument = new StringArgument<>("year", "Year of the date", String.class);
yearArgument.getArgumentValidator().when(RegexPredicate.notValidFor("\\d{4}")).thenRespond(event -> {
event.getResponder().respondNow()
.setContent("Year must be 4 digit!")
.respond();
});
StringArgument<String> monthArgument = new StringArgument<>("month", "Month of the date", String.class);
monthArgument.getArgumentValidator().when(RegexPredicate.notValidFor("\\d{2}")).thenRespond(event -> {
event.getResponder().respondNow()
.setContent("Month must be 2 digit!")
.respond();
});
StringArgument<String> dayArgument = new StringArgument<>("day", "Day of the date", String.class);
dayArgument.getArgumentValidator().when(RegexPredicate.notValidFor("\\d{2}")).thenRespond(event -> {
event.getResponder().respondNow()
.setContent("Day must be 2 digit!")
.respond();
});
// Make a concatenator that result's type is a Date and returns the arguments as a parsed Date
Concatenator<Date, Date> dateConcatenator = new Concatenator<>(Date.class) {
@Override
public Date concatenate(Object... results) {
try {
return sdf.parse(Arrays.stream(results).map(Object::toString).collect(Collectors.joining("-")));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
};
// Add arguments and concatenator and set action listener
dateCommand.addArgument(yearArgument, monthArgument, dayArgument);
dateCommand.addConcatenator(dateConcatenator, yearArgument, monthArgument, dayArgument);
dateCommand.setOnAction(event -> {
// The argument's result is now a date
Date date = event.getArguments()[0].get();
event.getResponder().respondNow()
.setContent(sdf.format(date))
.respond();
});
CommandHandler.registerCommand(dateCommand, server);