Skip to content

Example 2

Gellért Dániel edited this page Apr 4, 2023 · 11 revisions

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.

Code

// Create the command and arguments without any limitation for now
ServerCommand dateCommand = new ServerCommand("date", "Constructs a date");
NumberArgument<Long> yearArgument = new NumberArgument<>("year", "Year of the date", Long.class);
NumberArgument<Long> monthArgument = new NumberArgument<>("month", "Month of the date", Long.class);
NumberArgument<Long> dayArgument = new NumberArgument<>("day", "Day of the date", Long.class);

// Make a concatenator that result's type is a Date and returns the arguments as a parsed Date
Concatenator dateConcatenator = new Concatenator(Date.class) {
    @Override
    public Object concatenate(ArgumentResult... results) {
        return new SimpleDateFormat("yyyy-MM-dd").parse(Arrays.stream(results).map(result -> result.get().toString()).collect(Collectors.joining("-")));
    }
};

// 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(DateConverter.DATE_FORMAT.format(date))
            .respond();
});

CommandHandler.registerCommand(dateCommand, server);

Test

example