From 2aac3980d55f672a3e80b169eb0e87f330a62949 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20S=C3=B6derberg?= Date: Tue, 6 Oct 2020 22:48:30 +0200 Subject: [PATCH] :recycle: Reformat + Update .editorconfig --- .editorconfig | 831 +++++++++++++++++- .github/FUNDING.yml | 2 +- .github/dependabot.yml | 8 +- .github/workflows/gradle.yml | 28 +- build.gradle | 8 +- .../annotations/AnnotationParser.java | 97 +- .../annotations/ArgumentParameterPair.java | 6 +- .../annotations/CommandMethodPair.java | 6 +- .../annotations/Confirmation.java | 1 + .../annotations/FlagExtractor.java | 24 +- .../commandframework/annotations/Hidden.java | 1 + .../annotations/MetaFactory.java | 8 +- .../MethodCommandExecutionHandler.java | 10 +- .../annotations/SyntaxFragment.java | 8 +- .../annotations/SyntaxParser.java | 6 +- .../annotations/AnnotationParserTest.java | 17 +- .../annotations/TestCommandManager.java | 6 +- .../java/cloud/commandframework/Command.java | 354 ++++---- .../commandframework/CommandHelpHandler.java | 164 ++-- .../commandframework/CommandManager.java | 156 ++-- .../cloud/commandframework/CommandTree.java | 301 ++++--- .../cloud/commandframework/Description.java | 2 +- .../annotations/specifier/Greedy.java | 1 + .../arguments/CommandArgument.java | 80 +- .../arguments/CommandSyntaxFormatter.java | 6 +- .../DelegatingSuggestionsProvider.java | 3 +- .../StandardCommandSyntaxFormatter.java | 28 +- .../arguments/StaticArgument.java | 18 +- .../arguments/compound/ArgumentPair.java | 93 +- .../arguments/compound/ArgumentTriplet.java | 122 +-- .../arguments/compound/CompoundArgument.java | 59 +- .../arguments/compound/FlagArgument.java | 30 +- .../arguments/flags/CommandFlag.java | 20 +- .../arguments/flags/FlagContext.java | 14 +- .../arguments/parser/ArgumentParseResult.java | 1 + .../arguments/parser/ArgumentParser.java | 12 +- .../arguments/parser/ParserParameter.java | 6 +- .../arguments/parser/ParserParameters.java | 18 +- .../arguments/parser/ParserRegistry.java | 38 +- .../arguments/parser/StandardParameters.java | 6 +- .../parser/StandardParserRegistry.java | 93 +- .../arguments/standard/BooleanArgument.java | 45 +- .../arguments/standard/ByteArgument.java | 45 +- .../arguments/standard/CharArgument.java | 29 +- .../arguments/standard/DoubleArgument.java | 28 +- .../arguments/standard/EnumArgument.java | 55 +- .../arguments/standard/FloatArgument.java | 28 +- .../arguments/standard/IntegerArgument.java | 34 +- .../arguments/standard/LongArgument.java | 34 +- .../arguments/standard/ShortArgument.java | 34 +- .../arguments/standard/StringArgument.java | 65 +- .../arguments/standard/UUIDArgument.java | 24 +- .../context/CommandContext.java | 18 +- .../context/CommandContextFactory.java | 2 +- .../exceptions/AmbiguousNodeException.java | 10 +- .../exceptions/ArgumentParseException.java | 8 +- .../exceptions/CommandParseException.java | 6 +- .../InvalidCommandSenderException.java | 17 +- .../exceptions/InvalidSyntaxException.java | 8 +- .../exceptions/NoPermissionException.java | 8 +- .../exceptions/NoSuchCommandException.java | 8 +- .../parsing/NumberParseException.java | 8 +- ...ynchronousCommandExecutionCoordinator.java | 14 +- .../CommandExecutionCoordinator.java | 12 +- .../FilteringCommandSuggestionProcessor.java | 6 +- .../CommandPostprocessingContext.java | 6 +- .../postprocessor/CommandPostprocessor.java | 1 + .../CommandPreprocessingContext.java | 6 +- .../preprocessor/CommandPreprocessor.java | 1 + .../CommandConfirmationManager.java | 20 +- .../internal/CommandRegistrationHandler.java | 2 +- .../meta/SimpleCommandMeta.java | 6 +- .../commandframework/types/tuples/Pair.java | 12 +- .../types/tuples/Quartet.java | 20 +- .../types/tuples/Quintet.java | 15 +- .../commandframework/types/tuples/Sextet.java | 30 +- .../types/tuples/Triplet.java | 16 +- .../CommandHelpHandlerTest.java | 17 +- .../CommandPerformanceTest.java | 7 +- .../CommandPermissionTest.java | 7 +- .../CommandPostProcessorTest.java | 8 +- .../CommandPreProcessorTest.java | 26 +- .../CommandSuggestionsTest.java | 50 +- .../cloud/commandframework/CommandTest.java | 2 +- .../commandframework/CommandTreeTest.java | 154 ++-- .../commandframework/ParserRegistryTest.java | 16 +- .../standard/StringArgumentTest.java | 42 +- .../javacord/JavacordCommand.java | 116 +-- .../javacord/JavacordCommandManager.java | 24 +- .../javacord/JavacordRegistrationHandler.java | 50 +- .../sender/JavacordPrivateSender.java | 5 +- .../javacord/sender/JavacordServerSender.java | 9 +- .../jda/JDACommandListener.java | 89 +- .../jda/JDACommandManager.java | 16 +- .../jda/JDACommandSender.java | 20 +- .../commandframework/jda/JDAGuildSender.java | 1 + .../jda/JDAPrivateSender.java | 1 + .../jda/parsers/UserArgument.java | 19 +- .../jline/JLineCommandManager.java | 90 +- .../brigadier/CloudBrigadierManager.java | 138 +-- .../bukkit/BukkitBrigadierMapper.java | 45 +- .../bukkit/BukkitCommand.java | 150 ++-- .../bukkit/BukkitCommandManager.java | 80 +- .../bukkit/BukkitPlayerSender.java | 1 + .../BukkitPluginRegistrationHandler.java | 33 +- .../bukkit/BukkitSynchronizer.java | 12 +- .../bukkit/CloudBukkitCapabilities.java | 5 +- .../bukkit/CloudCommodoreManager.java | 22 +- .../arguments/selector/EntitySelector.java | 6 +- .../selector/MultipleEntitySelector.java | 6 +- .../selector/MultiplePlayerSelector.java | 6 +- .../selector/SingleEntitySelector.java | 6 +- .../selector/SinglePlayerSelector.java | 6 +- .../bukkit/parsers/MaterialArgument.java | 27 +- .../bukkit/parsers/OfflinePlayerArgument.java | 36 +- .../bukkit/parsers/PlayerArgument.java | 33 +- .../bukkit/parsers/WorldArgument.java | 24 +- .../MultipleEntitySelectorArgument.java | 31 +- .../MultiplePlayerSelectorArgument.java | 37 +- .../selector/SelectorParseException.java | 1 + .../SingleEntitySelectorArgument.java | 28 +- .../SinglePlayerSelectorArgument.java | 34 +- .../bungee/BungeeCommand.java | 178 ++-- .../bungee/BungeeCommandManager.java | 18 +- .../BungeePluginRegistrationHandler.java | 5 +- .../cloudburst/CloudburstCommand.java | 130 +-- .../cloudburst/CloudburstCommandManager.java | 18 +- .../cloud/commandframework/MinecraftHelp.java | 122 ++- .../AsyncCommandSuggestionsListener.java | 9 +- .../paper/PaperBrigadierListener.java | 22 +- .../paper/PaperCommandManager.java | 18 +- .../velocity/VelocityCommandManager.java | 3 +- .../VelocityPluginRegistrationHandler.java | 171 ++-- .../services/AnnotatedMethodService.java | 95 +- .../AnnotatedMethodServiceFactory.java | 36 +- .../services/ChunkedRequestContext.java | 46 +- .../services/ExecutionOrder.java | 7 +- .../services/ServiceFilterHandler.java | 6 +- .../services/ServicePipeline.java | 34 +- .../services/ServicePump.java | 12 +- .../services/ServiceRepository.java | 21 +- .../services/ServiceSpigot.java | 12 +- .../services/annotations/Order.java | 1 + .../annotations/ServiceImplementation.java | 3 +- .../services/types/ConsumerService.java | 78 +- .../services/types/PartialResultService.java | 36 +- .../services/types/Service.java | 56 +- .../services/types/SideEffectService.java | 26 +- .../services/ServicesTest.java | 158 +++- .../mock/CompletingPartialResultService.java | 22 +- .../services/mock/DefaultMockService.java | 18 +- .../mock/DefaultPartialRequestService.java | 16 +- .../mock/DefaultSideEffectService.java | 10 +- .../mock/InterruptingMockConsumer.java | 8 +- .../services/mock/MockChunkedRequest.java | 46 +- .../services/mock/MockOrderedFirst.java | 8 +- .../services/mock/MockOrderedLast.java | 8 +- .../mock/MockPartialResultService.java | 2 +- .../services/mock/MockResultConsumer.java | 8 +- .../services/mock/MockService.java | 28 +- .../services/mock/SecondaryMockService.java | 16 +- .../mock/SecondaryMockSideEffectService.java | 8 +- .../mock/StateSettingConsumerService.java | 8 +- .../commandframework/tasks/TaskFunction.java | 12 +- .../commandframework/tasks/TaskRecipe.java | 18 +- .../tasks/TaskRecipeStep.java | 1 + config/checkstyle/checkstyle.xml | 8 +- .../examples/bukkit/ExamplePlugin.java | 147 ++-- icons/cloud.svg | 87 +- 169 files changed, 4261 insertions(+), 2448 deletions(-) diff --git a/.editorconfig b/.editorconfig index 7723335e..f72383ca 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,55 +1,85 @@ -root = true - [*] charset = utf-8 end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true -max_line_length = 120 +max_line_length = 130 tab_width = 4 ij_continuation_indent_size = 8 ij_formatter_off_tag = @formatter:off ij_formatter_on_tag = @formatter:on -ij_formatter_tags_enabled = true +ij_formatter_tags_enabled = false ij_smart_tabs = false -ij_visual_guides = 130 -ij_wrap_on_typing = false +ij_wrap_on_typing = true + +[*.conf] +indent_size = 2 +tab_width = 2 +ij_continuation_indent_size = 2 +ij_hocon_keep_blank_lines_before_right_brace = 2 +ij_hocon_keep_indents_on_empty_lines = false +ij_hocon_keep_line_breaks = true +ij_hocon_space_after_colon = true +ij_hocon_space_after_comma = true +ij_hocon_space_before_colon = true +ij_hocon_space_before_comma = false +ij_hocon_spaces_within_braces = false +ij_hocon_spaces_within_brackets = false +ij_hocon_spaces_within_method_call_parentheses = false + +[*.css] +ij_css_align_closing_brace_with_properties = false +ij_css_blank_lines_around_nested_selector = 1 +ij_css_blank_lines_between_blocks = 1 +ij_css_brace_placement = end_of_line +ij_css_enforce_quotes_on_format = false +ij_css_hex_color_long_format = false +ij_css_hex_color_lower_case = false +ij_css_hex_color_short_format = false +ij_css_hex_color_upper_case = false +ij_css_keep_blank_lines_in_code = 2 +ij_css_keep_indents_on_empty_lines = false +ij_css_keep_single_line_blocks = false +ij_css_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow +ij_css_space_after_colon = true +ij_css_space_before_opening_brace = true +ij_css_use_double_quotes = true +ij_css_value_alignment = do_not_align [*.java] -max_line_length = 130 ij_java_align_consecutive_assignments = false ij_java_align_consecutive_variable_declarations = false ij_java_align_group_field_declarations = false -ij_java_align_multiline_annotation_parameters = true -ij_java_align_multiline_array_initializer_expression = true +ij_java_align_multiline_annotation_parameters = false +ij_java_align_multiline_array_initializer_expression = false ij_java_align_multiline_assignment = false ij_java_align_multiline_binary_operation = false -ij_java_align_multiline_chained_methods = true +ij_java_align_multiline_chained_methods = false ij_java_align_multiline_extends_list = false ij_java_align_multiline_for = true ij_java_align_multiline_method_parentheses = false ij_java_align_multiline_parameters = true -ij_java_align_multiline_parameters_in_calls = true +ij_java_align_multiline_parameters_in_calls = false ij_java_align_multiline_parenthesized_expression = false ij_java_align_multiline_records = true ij_java_align_multiline_resources = true -ij_java_align_multiline_ternary_operation = true +ij_java_align_multiline_ternary_operation = false ij_java_align_multiline_text_blocks = false ij_java_align_multiline_throws_list = false ij_java_align_subsequent_simple_methods = false ij_java_align_throws_keyword = false ij_java_annotation_parameter_wrap = off -ij_java_array_initializer_new_line_after_left_brace = true -ij_java_array_initializer_right_brace_on_new_line = true -ij_java_array_initializer_wrap = on_every_item +ij_java_array_initializer_new_line_after_left_brace = false +ij_java_array_initializer_right_brace_on_new_line = false +ij_java_array_initializer_wrap = off ij_java_assert_statement_colon_on_next_line = false ij_java_assert_statement_wrap = off ij_java_assignment_wrap = off ij_java_binary_operation_sign_on_next_line = false ij_java_binary_operation_wrap = off ij_java_blank_lines_after_anonymous_class_header = 0 -ij_java_blank_lines_after_class_header = 0 +ij_java_blank_lines_after_class_header = 1 ij_java_blank_lines_after_imports = 1 ij_java_blank_lines_after_package = 1 ij_java_blank_lines_around_class = 1 @@ -58,23 +88,23 @@ ij_java_blank_lines_around_field_in_interface = 0 ij_java_blank_lines_around_initializer = 1 ij_java_blank_lines_around_method = 1 ij_java_blank_lines_around_method_in_interface = 1 -ij_java_blank_lines_before_class_end = 0 +ij_java_blank_lines_before_class_end = 1 ij_java_blank_lines_before_imports = 1 ij_java_blank_lines_before_method_body = 0 ij_java_blank_lines_before_package = 0 ij_java_block_brace_style = end_of_line ij_java_block_comment_at_first_column = true -ij_java_call_parameters_new_line_after_left_paren = false -ij_java_call_parameters_right_paren_on_new_line = false -ij_java_call_parameters_wrap = normal +ij_java_call_parameters_new_line_after_left_paren = true +ij_java_call_parameters_right_paren_on_new_line = true +ij_java_call_parameters_wrap = on_every_item ij_java_case_statement_on_separate_line = true ij_java_catch_on_new_line = false ij_java_class_annotation_wrap = split_into_lines ij_java_class_brace_style = end_of_line -ij_java_class_count_to_use_import_on_demand = 9999999 +ij_java_class_count_to_use_import_on_demand = 100000 ij_java_class_names_in_javadoc = 1 ij_java_do_not_indent_top_level_class_members = false -ij_java_do_not_wrap_after_single_annotation = true +ij_java_do_not_wrap_after_single_annotation = false ij_java_do_while_brace_force = always ij_java_doc_add_blank_line_after_description = true ij_java_doc_add_blank_line_after_param_comments = false @@ -85,12 +115,12 @@ ij_java_doc_align_param_comments = true ij_java_doc_do_not_wrap_if_one_line = false ij_java_doc_enable_formatting = true ij_java_doc_enable_leading_asterisks = true -ij_java_doc_indent_on_continuation = false +ij_java_doc_indent_on_continuation = true ij_java_doc_keep_empty_lines = true ij_java_doc_keep_empty_parameter_tag = true ij_java_doc_keep_empty_return_tag = true ij_java_doc_keep_empty_throws_tag = true -ij_java_doc_keep_invalid_tags = true +ij_java_doc_keep_invalid_tags = false ij_java_doc_param_description_on_new_line = false ij_java_doc_preserve_line_breaks = false ij_java_doc_use_throws_not_exception_tag = true @@ -133,18 +163,18 @@ ij_java_line_comment_at_first_column = true ij_java_method_annotation_wrap = split_into_lines ij_java_method_brace_style = end_of_line ij_java_method_call_chain_wrap = on_every_item -ij_java_method_parameters_new_line_after_left_paren = false -ij_java_method_parameters_right_paren_on_new_line = false +ij_java_method_parameters_new_line_after_left_paren = true +ij_java_method_parameters_right_paren_on_new_line = true ij_java_method_parameters_wrap = on_every_item ij_java_modifier_list_wrap = false -ij_java_names_count_to_use_import_on_demand = 9999999 +ij_java_names_count_to_use_import_on_demand = 100000 ij_java_new_line_after_lparen_in_record_header = false -ij_java_parameter_annotation_wrap = on_every_item +ij_java_parameter_annotation_wrap = off ij_java_parentheses_expression_new_line_after_left_paren = false ij_java_parentheses_expression_right_paren_on_new_line = false ij_java_place_assignment_sign_on_next_line = false -ij_java_prefer_longer_names = true -ij_java_prefer_parameters_wrap = false +ij_java_prefer_longer_names = false +ij_java_prefer_parameters_wrap = true ij_java_record_components_wrap = normal ij_java_repeat_synchronized = true ij_java_replace_instanceof_and_cast = false @@ -230,7 +260,7 @@ ij_java_spaces_within_try_parentheses = false ij_java_spaces_within_while_parentheses = false ij_java_special_else_if_treatment = true ij_java_subclass_name_suffix = Impl -ij_java_ternary_operation_signs_on_next_line = false +ij_java_ternary_operation_signs_on_next_line = true ij_java_ternary_operation_wrap = on_every_item ij_java_test_name_suffix = Test ij_java_throws_keyword_wrap = off @@ -239,10 +269,745 @@ ij_java_use_external_annotations = false ij_java_use_fq_class_names = false ij_java_use_relative_indents = false ij_java_use_single_class_imports = true -ij_java_variable_annotation_wrap = on_every_item +ij_java_variable_annotation_wrap = off ij_java_visibility = public ij_java_while_brace_force = always ij_java_while_on_new_line = false ij_java_wrap_comments = false -ij_java_wrap_first_method_in_call_chain = false +ij_java_wrap_first_method_in_call_chain = true ij_java_wrap_long_lines = false + +[*.nbtt] +max_line_length = 150 +ij_continuation_indent_size = 4 +ij_nbtt_keep_indents_on_empty_lines = false +ij_nbtt_space_after_colon = true +ij_nbtt_space_after_comma = true +ij_nbtt_space_before_colon = true +ij_nbtt_space_before_comma = false +ij_nbtt_spaces_within_brackets = false +ij_nbtt_spaces_within_parentheses = false + +[*.properties] +ij_properties_align_group_field_declarations = false +ij_properties_keep_blank_lines = false +ij_properties_key_value_delimiter = equals +ij_properties_spaces_around_key_value_delimiter = false + +[*.sass] +indent_size = 2 +ij_sass_align_closing_brace_with_properties = false +ij_sass_blank_lines_around_nested_selector = 1 +ij_sass_blank_lines_between_blocks = 1 +ij_sass_brace_placement = 0 +ij_sass_enforce_quotes_on_format = false +ij_sass_hex_color_long_format = false +ij_sass_hex_color_lower_case = false +ij_sass_hex_color_short_format = false +ij_sass_hex_color_upper_case = false +ij_sass_keep_blank_lines_in_code = 2 +ij_sass_keep_indents_on_empty_lines = false +ij_sass_keep_single_line_blocks = false +ij_sass_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow +ij_sass_space_after_colon = true +ij_sass_space_before_opening_brace = true +ij_sass_use_double_quotes = true +ij_sass_value_alignment = 0 + +[*.scss] +indent_size = 2 +ij_scss_align_closing_brace_with_properties = false +ij_scss_blank_lines_around_nested_selector = 1 +ij_scss_blank_lines_between_blocks = 1 +ij_scss_brace_placement = 0 +ij_scss_enforce_quotes_on_format = false +ij_scss_hex_color_long_format = false +ij_scss_hex_color_lower_case = false +ij_scss_hex_color_short_format = false +ij_scss_hex_color_upper_case = false +ij_scss_keep_blank_lines_in_code = 2 +ij_scss_keep_indents_on_empty_lines = false +ij_scss_keep_single_line_blocks = false +ij_scss_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow +ij_scss_space_after_colon = true +ij_scss_space_before_opening_brace = true +ij_scss_use_double_quotes = true +ij_scss_value_alignment = 0 + +[.editorconfig] +ij_editorconfig_align_group_field_declarations = false +ij_editorconfig_space_after_colon = false +ij_editorconfig_space_after_comma = true +ij_editorconfig_space_before_colon = false +ij_editorconfig_space_before_comma = false +ij_editorconfig_spaces_around_assignment_operators = true + +[{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.pom, *.rng, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul}] +ij_xml_align_attributes = true +ij_xml_align_text = false +ij_xml_attribute_wrap = normal +ij_xml_block_comment_at_first_column = true +ij_xml_keep_blank_lines = 2 +ij_xml_keep_indents_on_empty_lines = false +ij_xml_keep_line_breaks = true +ij_xml_keep_line_breaks_in_text = true +ij_xml_keep_whitespaces = false +ij_xml_keep_whitespaces_around_cdata = preserve +ij_xml_keep_whitespaces_inside_cdata = false +ij_xml_line_comment_at_first_column = true +ij_xml_space_after_tag_name = false +ij_xml_space_around_equals_in_attribute = false +ij_xml_space_inside_empty_tag = false +ij_xml_text_wrap = normal + +[{*.ats, *.ts}] +ij_continuation_indent_size = 4 +ij_typescript_align_imports = false +ij_typescript_align_multiline_array_initializer_expression = false +ij_typescript_align_multiline_binary_operation = false +ij_typescript_align_multiline_chained_methods = false +ij_typescript_align_multiline_extends_list = false +ij_typescript_align_multiline_for = true +ij_typescript_align_multiline_parameters = true +ij_typescript_align_multiline_parameters_in_calls = false +ij_typescript_align_multiline_ternary_operation = false +ij_typescript_align_object_properties = 0 +ij_typescript_align_union_types = false +ij_typescript_align_var_statements = 0 +ij_typescript_array_initializer_new_line_after_left_brace = false +ij_typescript_array_initializer_right_brace_on_new_line = false +ij_typescript_array_initializer_wrap = off +ij_typescript_assignment_wrap = off +ij_typescript_binary_operation_sign_on_next_line = false +ij_typescript_binary_operation_wrap = off +ij_typescript_blacklist_imports = rxjs/Rx, node_modules/**, **/node_modules/**, @angular/material, @angular/material/typings/** +ij_typescript_blank_lines_after_imports = 1 +ij_typescript_blank_lines_around_class = 1 +ij_typescript_blank_lines_around_field = 0 +ij_typescript_blank_lines_around_field_in_interface = 0 +ij_typescript_blank_lines_around_function = 1 +ij_typescript_blank_lines_around_method = 1 +ij_typescript_blank_lines_around_method_in_interface = 1 +ij_typescript_block_brace_style = end_of_line +ij_typescript_call_parameters_new_line_after_left_paren = false +ij_typescript_call_parameters_right_paren_on_new_line = false +ij_typescript_call_parameters_wrap = off +ij_typescript_catch_on_new_line = false +ij_typescript_chained_call_dot_on_new_line = true +ij_typescript_class_brace_style = end_of_line +ij_typescript_comma_on_new_line = false +ij_typescript_do_while_brace_force = never +ij_typescript_else_on_new_line = false +ij_typescript_enforce_trailing_comma = keep +ij_typescript_extends_keyword_wrap = off +ij_typescript_extends_list_wrap = off +ij_typescript_field_prefix = _ +ij_typescript_file_name_style = relaxed +ij_typescript_finally_on_new_line = false +ij_typescript_for_brace_force = never +ij_typescript_for_statement_new_line_after_left_paren = false +ij_typescript_for_statement_right_paren_on_new_line = false +ij_typescript_for_statement_wrap = off +ij_typescript_force_quote_style = false +ij_typescript_force_semicolon_style = false +ij_typescript_function_expression_brace_style = end_of_line +ij_typescript_if_brace_force = never +ij_typescript_import_merge_members = global +ij_typescript_import_prefer_absolute_path = global +ij_typescript_import_sort_members = true +ij_typescript_import_sort_module_name = false +ij_typescript_import_use_node_resolution = true +ij_typescript_imports_wrap = on_every_item +ij_typescript_indent_case_from_switch = true +ij_typescript_indent_chained_calls = true +ij_typescript_indent_package_children = 0 +ij_typescript_jsdoc_include_types = false +ij_typescript_jsx_attribute_value = braces +ij_typescript_keep_blank_lines_in_code = 2 +ij_typescript_keep_first_column_comment = true +ij_typescript_keep_indents_on_empty_lines = false +ij_typescript_keep_line_breaks = true +ij_typescript_keep_simple_blocks_in_one_line = false +ij_typescript_keep_simple_methods_in_one_line = false +ij_typescript_line_comment_add_space = true +ij_typescript_line_comment_at_first_column = false +ij_typescript_method_brace_style = end_of_line +ij_typescript_method_call_chain_wrap = off +ij_typescript_method_parameters_new_line_after_left_paren = false +ij_typescript_method_parameters_right_paren_on_new_line = false +ij_typescript_method_parameters_wrap = off +ij_typescript_object_literal_wrap = on_every_item +ij_typescript_parentheses_expression_new_line_after_left_paren = false +ij_typescript_parentheses_expression_right_paren_on_new_line = false +ij_typescript_place_assignment_sign_on_next_line = false +ij_typescript_prefer_as_type_cast = false +ij_typescript_prefer_explicit_types_function_expression_returns = false +ij_typescript_prefer_explicit_types_function_returns = false +ij_typescript_prefer_explicit_types_vars_fields = false +ij_typescript_prefer_parameters_wrap = false +ij_typescript_reformat_c_style_comments = false +ij_typescript_space_after_colon = true +ij_typescript_space_after_comma = true +ij_typescript_space_after_dots_in_rest_parameter = false +ij_typescript_space_after_generator_mult = true +ij_typescript_space_after_property_colon = true +ij_typescript_space_after_quest = true +ij_typescript_space_after_type_colon = true +ij_typescript_space_after_unary_not = false +ij_typescript_space_before_async_arrow_lparen = true +ij_typescript_space_before_catch_keyword = true +ij_typescript_space_before_catch_left_brace = true +ij_typescript_space_before_catch_parentheses = true +ij_typescript_space_before_class_lbrace = true +ij_typescript_space_before_class_left_brace = true +ij_typescript_space_before_colon = true +ij_typescript_space_before_comma = false +ij_typescript_space_before_do_left_brace = true +ij_typescript_space_before_else_keyword = true +ij_typescript_space_before_else_left_brace = true +ij_typescript_space_before_finally_keyword = true +ij_typescript_space_before_finally_left_brace = true +ij_typescript_space_before_for_left_brace = true +ij_typescript_space_before_for_parentheses = true +ij_typescript_space_before_for_semicolon = false +ij_typescript_space_before_function_left_parenth = true +ij_typescript_space_before_generator_mult = false +ij_typescript_space_before_if_left_brace = true +ij_typescript_space_before_if_parentheses = true +ij_typescript_space_before_method_call_parentheses = false +ij_typescript_space_before_method_left_brace = true +ij_typescript_space_before_method_parentheses = false +ij_typescript_space_before_property_colon = false +ij_typescript_space_before_quest = true +ij_typescript_space_before_switch_left_brace = true +ij_typescript_space_before_switch_parentheses = true +ij_typescript_space_before_try_left_brace = true +ij_typescript_space_before_type_colon = false +ij_typescript_space_before_unary_not = false +ij_typescript_space_before_while_keyword = true +ij_typescript_space_before_while_left_brace = true +ij_typescript_space_before_while_parentheses = true +ij_typescript_spaces_around_additive_operators = true +ij_typescript_spaces_around_arrow_function_operator = true +ij_typescript_spaces_around_assignment_operators = true +ij_typescript_spaces_around_bitwise_operators = true +ij_typescript_spaces_around_equality_operators = true +ij_typescript_spaces_around_logical_operators = true +ij_typescript_spaces_around_multiplicative_operators = true +ij_typescript_spaces_around_relational_operators = true +ij_typescript_spaces_around_shift_operators = true +ij_typescript_spaces_around_unary_operator = false +ij_typescript_spaces_within_array_initializer_brackets = false +ij_typescript_spaces_within_brackets = false +ij_typescript_spaces_within_catch_parentheses = false +ij_typescript_spaces_within_for_parentheses = false +ij_typescript_spaces_within_if_parentheses = false +ij_typescript_spaces_within_imports = false +ij_typescript_spaces_within_interpolation_expressions = false +ij_typescript_spaces_within_method_call_parentheses = false +ij_typescript_spaces_within_method_parentheses = false +ij_typescript_spaces_within_object_literal_braces = false +ij_typescript_spaces_within_object_type_braces = true +ij_typescript_spaces_within_parentheses = false +ij_typescript_spaces_within_switch_parentheses = false +ij_typescript_spaces_within_type_assertion = false +ij_typescript_spaces_within_union_types = true +ij_typescript_spaces_within_while_parentheses = false +ij_typescript_special_else_if_treatment = true +ij_typescript_ternary_operation_signs_on_next_line = false +ij_typescript_ternary_operation_wrap = off +ij_typescript_union_types_wrap = on_every_item +ij_typescript_use_chained_calls_group_indents = false +ij_typescript_use_double_quotes = true +ij_typescript_use_explicit_js_extension = global +ij_typescript_use_path_mapping = always +ij_typescript_use_public_modifier = false +ij_typescript_use_semicolon_after_statement = true +ij_typescript_var_declaration_wrap = normal +ij_typescript_while_brace_force = never +ij_typescript_while_on_new_line = false +ij_typescript_wrap_comments = false + +[{*.bash, *.sh, *.zsh}] +indent_size = 2 +tab_width = 2 +ij_shell_binary_ops_start_line = false +ij_shell_keep_column_alignment_padding = false +ij_shell_minify_program = false +ij_shell_redirect_followed_by_space = false +ij_shell_switch_cases_indented = false + +[{*.cjs, *.js}] +ij_continuation_indent_size = 4 +ij_javascript_align_imports = false +ij_javascript_align_multiline_array_initializer_expression = false +ij_javascript_align_multiline_binary_operation = false +ij_javascript_align_multiline_chained_methods = false +ij_javascript_align_multiline_extends_list = false +ij_javascript_align_multiline_for = true +ij_javascript_align_multiline_parameters = true +ij_javascript_align_multiline_parameters_in_calls = false +ij_javascript_align_multiline_ternary_operation = false +ij_javascript_align_object_properties = 0 +ij_javascript_align_union_types = false +ij_javascript_align_var_statements = 0 +ij_javascript_array_initializer_new_line_after_left_brace = false +ij_javascript_array_initializer_right_brace_on_new_line = false +ij_javascript_array_initializer_wrap = off +ij_javascript_assignment_wrap = off +ij_javascript_binary_operation_sign_on_next_line = false +ij_javascript_binary_operation_wrap = off +ij_javascript_blacklist_imports = rxjs/Rx, node_modules/**, **/node_modules/**, @angular/material, @angular/material/typings/** +ij_javascript_blank_lines_after_imports = 1 +ij_javascript_blank_lines_around_class = 1 +ij_javascript_blank_lines_around_field = 0 +ij_javascript_blank_lines_around_function = 1 +ij_javascript_blank_lines_around_method = 1 +ij_javascript_block_brace_style = end_of_line +ij_javascript_call_parameters_new_line_after_left_paren = false +ij_javascript_call_parameters_right_paren_on_new_line = false +ij_javascript_call_parameters_wrap = off +ij_javascript_catch_on_new_line = false +ij_javascript_chained_call_dot_on_new_line = true +ij_javascript_class_brace_style = end_of_line +ij_javascript_comma_on_new_line = false +ij_javascript_do_while_brace_force = never +ij_javascript_else_on_new_line = false +ij_javascript_enforce_trailing_comma = keep +ij_javascript_extends_keyword_wrap = off +ij_javascript_extends_list_wrap = off +ij_javascript_field_prefix = _ +ij_javascript_file_name_style = relaxed +ij_javascript_finally_on_new_line = false +ij_javascript_for_brace_force = never +ij_javascript_for_statement_new_line_after_left_paren = false +ij_javascript_for_statement_right_paren_on_new_line = false +ij_javascript_for_statement_wrap = off +ij_javascript_force_quote_style = false +ij_javascript_force_semicolon_style = false +ij_javascript_function_expression_brace_style = end_of_line +ij_javascript_if_brace_force = never +ij_javascript_import_merge_members = global +ij_javascript_import_prefer_absolute_path = global +ij_javascript_import_sort_members = true +ij_javascript_import_sort_module_name = false +ij_javascript_import_use_node_resolution = true +ij_javascript_imports_wrap = on_every_item +ij_javascript_indent_case_from_switch = true +ij_javascript_indent_chained_calls = true +ij_javascript_indent_package_children = 0 +ij_javascript_jsx_attribute_value = braces +ij_javascript_keep_blank_lines_in_code = 2 +ij_javascript_keep_first_column_comment = true +ij_javascript_keep_indents_on_empty_lines = false +ij_javascript_keep_line_breaks = true +ij_javascript_keep_simple_blocks_in_one_line = false +ij_javascript_keep_simple_methods_in_one_line = false +ij_javascript_line_comment_add_space = true +ij_javascript_line_comment_at_first_column = false +ij_javascript_method_brace_style = end_of_line +ij_javascript_method_call_chain_wrap = off +ij_javascript_method_parameters_new_line_after_left_paren = false +ij_javascript_method_parameters_right_paren_on_new_line = false +ij_javascript_method_parameters_wrap = off +ij_javascript_object_literal_wrap = on_every_item +ij_javascript_parentheses_expression_new_line_after_left_paren = false +ij_javascript_parentheses_expression_right_paren_on_new_line = false +ij_javascript_place_assignment_sign_on_next_line = false +ij_javascript_prefer_as_type_cast = false +ij_javascript_prefer_explicit_types_function_expression_returns = false +ij_javascript_prefer_explicit_types_function_returns = false +ij_javascript_prefer_explicit_types_vars_fields = false +ij_javascript_prefer_parameters_wrap = false +ij_javascript_reformat_c_style_comments = false +ij_javascript_space_after_colon = true +ij_javascript_space_after_comma = true +ij_javascript_space_after_dots_in_rest_parameter = false +ij_javascript_space_after_generator_mult = true +ij_javascript_space_after_property_colon = true +ij_javascript_space_after_quest = true +ij_javascript_space_after_type_colon = true +ij_javascript_space_after_unary_not = false +ij_javascript_space_before_async_arrow_lparen = true +ij_javascript_space_before_catch_keyword = true +ij_javascript_space_before_catch_left_brace = true +ij_javascript_space_before_catch_parentheses = true +ij_javascript_space_before_class_lbrace = true +ij_javascript_space_before_class_left_brace = true +ij_javascript_space_before_colon = true +ij_javascript_space_before_comma = false +ij_javascript_space_before_do_left_brace = true +ij_javascript_space_before_else_keyword = true +ij_javascript_space_before_else_left_brace = true +ij_javascript_space_before_finally_keyword = true +ij_javascript_space_before_finally_left_brace = true +ij_javascript_space_before_for_left_brace = true +ij_javascript_space_before_for_parentheses = true +ij_javascript_space_before_for_semicolon = false +ij_javascript_space_before_function_left_parenth = true +ij_javascript_space_before_generator_mult = false +ij_javascript_space_before_if_left_brace = true +ij_javascript_space_before_if_parentheses = true +ij_javascript_space_before_method_call_parentheses = false +ij_javascript_space_before_method_left_brace = true +ij_javascript_space_before_method_parentheses = false +ij_javascript_space_before_property_colon = false +ij_javascript_space_before_quest = true +ij_javascript_space_before_switch_left_brace = true +ij_javascript_space_before_switch_parentheses = true +ij_javascript_space_before_try_left_brace = true +ij_javascript_space_before_type_colon = false +ij_javascript_space_before_unary_not = false +ij_javascript_space_before_while_keyword = true +ij_javascript_space_before_while_left_brace = true +ij_javascript_space_before_while_parentheses = true +ij_javascript_spaces_around_additive_operators = true +ij_javascript_spaces_around_arrow_function_operator = true +ij_javascript_spaces_around_assignment_operators = true +ij_javascript_spaces_around_bitwise_operators = true +ij_javascript_spaces_around_equality_operators = true +ij_javascript_spaces_around_logical_operators = true +ij_javascript_spaces_around_multiplicative_operators = true +ij_javascript_spaces_around_relational_operators = true +ij_javascript_spaces_around_shift_operators = true +ij_javascript_spaces_around_unary_operator = false +ij_javascript_spaces_within_array_initializer_brackets = false +ij_javascript_spaces_within_brackets = false +ij_javascript_spaces_within_catch_parentheses = false +ij_javascript_spaces_within_for_parentheses = false +ij_javascript_spaces_within_if_parentheses = false +ij_javascript_spaces_within_imports = false +ij_javascript_spaces_within_interpolation_expressions = false +ij_javascript_spaces_within_method_call_parentheses = false +ij_javascript_spaces_within_method_parentheses = false +ij_javascript_spaces_within_object_literal_braces = false +ij_javascript_spaces_within_object_type_braces = true +ij_javascript_spaces_within_parentheses = false +ij_javascript_spaces_within_switch_parentheses = false +ij_javascript_spaces_within_type_assertion = false +ij_javascript_spaces_within_union_types = true +ij_javascript_spaces_within_while_parentheses = false +ij_javascript_special_else_if_treatment = true +ij_javascript_ternary_operation_signs_on_next_line = false +ij_javascript_ternary_operation_wrap = off +ij_javascript_union_types_wrap = on_every_item +ij_javascript_use_chained_calls_group_indents = false +ij_javascript_use_double_quotes = true +ij_javascript_use_explicit_js_extension = global +ij_javascript_use_path_mapping = always +ij_javascript_use_public_modifier = false +ij_javascript_use_semicolon_after_statement = true +ij_javascript_var_declaration_wrap = normal +ij_javascript_while_brace_force = never +ij_javascript_while_on_new_line = false +ij_javascript_wrap_comments = false + +[{*.ft, *.vm, *.vsl}] +ij_vtl_keep_indents_on_empty_lines = false + +[{*.gant, *.gradle, *.groovy, *.gy}] +ij_groovy_align_group_field_declarations = false +ij_groovy_align_multiline_array_initializer_expression = false +ij_groovy_align_multiline_assignment = false +ij_groovy_align_multiline_binary_operation = false +ij_groovy_align_multiline_chained_methods = false +ij_groovy_align_multiline_extends_list = false +ij_groovy_align_multiline_for = true +ij_groovy_align_multiline_list_or_map = true +ij_groovy_align_multiline_method_parentheses = false +ij_groovy_align_multiline_parameters = true +ij_groovy_align_multiline_parameters_in_calls = false +ij_groovy_align_multiline_resources = true +ij_groovy_align_multiline_ternary_operation = false +ij_groovy_align_multiline_throws_list = false +ij_groovy_align_named_args_in_map = true +ij_groovy_align_throws_keyword = false +ij_groovy_array_initializer_new_line_after_left_brace = false +ij_groovy_array_initializer_right_brace_on_new_line = false +ij_groovy_array_initializer_wrap = off +ij_groovy_assert_statement_wrap = off +ij_groovy_assignment_wrap = off +ij_groovy_binary_operation_wrap = off +ij_groovy_blank_lines_after_class_header = 0 +ij_groovy_blank_lines_after_imports = 1 +ij_groovy_blank_lines_after_package = 1 +ij_groovy_blank_lines_around_class = 1 +ij_groovy_blank_lines_around_field = 0 +ij_groovy_blank_lines_around_field_in_interface = 0 +ij_groovy_blank_lines_around_method = 1 +ij_groovy_blank_lines_around_method_in_interface = 1 +ij_groovy_blank_lines_before_imports = 1 +ij_groovy_blank_lines_before_method_body = 0 +ij_groovy_blank_lines_before_package = 0 +ij_groovy_block_brace_style = end_of_line +ij_groovy_block_comment_at_first_column = true +ij_groovy_call_parameters_new_line_after_left_paren = false +ij_groovy_call_parameters_right_paren_on_new_line = false +ij_groovy_call_parameters_wrap = off +ij_groovy_catch_on_new_line = false +ij_groovy_class_annotation_wrap = split_into_lines +ij_groovy_class_brace_style = end_of_line +ij_groovy_class_count_to_use_import_on_demand = 5 +ij_groovy_do_while_brace_force = never +ij_groovy_else_on_new_line = false +ij_groovy_enum_constants_wrap = off +ij_groovy_extends_keyword_wrap = off +ij_groovy_extends_list_wrap = off +ij_groovy_field_annotation_wrap = split_into_lines +ij_groovy_finally_on_new_line = false +ij_groovy_for_brace_force = never +ij_groovy_for_statement_new_line_after_left_paren = false +ij_groovy_for_statement_right_paren_on_new_line = false +ij_groovy_for_statement_wrap = off +ij_groovy_if_brace_force = never +ij_groovy_import_annotation_wrap = 2 +ij_groovy_imports_layout = *, |, javax.**, java.**, |, $* +ij_groovy_indent_case_from_switch = true +ij_groovy_indent_label_blocks = true +ij_groovy_insert_inner_class_imports = false +ij_groovy_keep_blank_lines_before_right_brace = 2 +ij_groovy_keep_blank_lines_in_code = 2 +ij_groovy_keep_blank_lines_in_declarations = 2 +ij_groovy_keep_control_statement_in_one_line = true +ij_groovy_keep_first_column_comment = true +ij_groovy_keep_indents_on_empty_lines = false +ij_groovy_keep_line_breaks = true +ij_groovy_keep_multiple_expressions_in_one_line = false +ij_groovy_keep_simple_blocks_in_one_line = false +ij_groovy_keep_simple_classes_in_one_line = true +ij_groovy_keep_simple_lambdas_in_one_line = true +ij_groovy_keep_simple_methods_in_one_line = true +ij_groovy_label_indent_absolute = false +ij_groovy_label_indent_size = 0 +ij_groovy_lambda_brace_style = end_of_line +ij_groovy_layout_static_imports_separately = true +ij_groovy_line_comment_add_space = false +ij_groovy_line_comment_at_first_column = true +ij_groovy_method_annotation_wrap = split_into_lines +ij_groovy_method_brace_style = end_of_line +ij_groovy_method_call_chain_wrap = off +ij_groovy_method_parameters_new_line_after_left_paren = false +ij_groovy_method_parameters_right_paren_on_new_line = false +ij_groovy_method_parameters_wrap = off +ij_groovy_modifier_list_wrap = false +ij_groovy_names_count_to_use_import_on_demand = 3 +ij_groovy_parameter_annotation_wrap = off +ij_groovy_parentheses_expression_new_line_after_left_paren = false +ij_groovy_parentheses_expression_right_paren_on_new_line = false +ij_groovy_prefer_parameters_wrap = false +ij_groovy_resource_list_new_line_after_left_paren = false +ij_groovy_resource_list_right_paren_on_new_line = false +ij_groovy_resource_list_wrap = off +ij_groovy_space_after_assert_separator = true +ij_groovy_space_after_colon = true +ij_groovy_space_after_comma = true +ij_groovy_space_after_comma_in_type_arguments = true +ij_groovy_space_after_for_semicolon = true +ij_groovy_space_after_quest = true +ij_groovy_space_after_type_cast = true +ij_groovy_space_before_annotation_parameter_list = false +ij_groovy_space_before_array_initializer_left_brace = false +ij_groovy_space_before_assert_separator = false +ij_groovy_space_before_catch_keyword = true +ij_groovy_space_before_catch_left_brace = true +ij_groovy_space_before_catch_parentheses = true +ij_groovy_space_before_class_left_brace = true +ij_groovy_space_before_closure_left_brace = true +ij_groovy_space_before_colon = true +ij_groovy_space_before_comma = false +ij_groovy_space_before_do_left_brace = true +ij_groovy_space_before_else_keyword = true +ij_groovy_space_before_else_left_brace = true +ij_groovy_space_before_finally_keyword = true +ij_groovy_space_before_finally_left_brace = true +ij_groovy_space_before_for_left_brace = true +ij_groovy_space_before_for_parentheses = true +ij_groovy_space_before_for_semicolon = false +ij_groovy_space_before_if_left_brace = true +ij_groovy_space_before_if_parentheses = true +ij_groovy_space_before_method_call_parentheses = false +ij_groovy_space_before_method_left_brace = true +ij_groovy_space_before_method_parentheses = false +ij_groovy_space_before_quest = true +ij_groovy_space_before_switch_left_brace = true +ij_groovy_space_before_switch_parentheses = true +ij_groovy_space_before_synchronized_left_brace = true +ij_groovy_space_before_synchronized_parentheses = true +ij_groovy_space_before_try_left_brace = true +ij_groovy_space_before_try_parentheses = true +ij_groovy_space_before_while_keyword = true +ij_groovy_space_before_while_left_brace = true +ij_groovy_space_before_while_parentheses = true +ij_groovy_space_in_named_argument = true +ij_groovy_space_in_named_argument_before_colon = false +ij_groovy_space_within_empty_array_initializer_braces = false +ij_groovy_space_within_empty_method_call_parentheses = false +ij_groovy_spaces_around_additive_operators = true +ij_groovy_spaces_around_assignment_operators = true +ij_groovy_spaces_around_bitwise_operators = true +ij_groovy_spaces_around_equality_operators = true +ij_groovy_spaces_around_lambda_arrow = true +ij_groovy_spaces_around_logical_operators = true +ij_groovy_spaces_around_multiplicative_operators = true +ij_groovy_spaces_around_regex_operators = true +ij_groovy_spaces_around_relational_operators = true +ij_groovy_spaces_around_shift_operators = true +ij_groovy_spaces_within_annotation_parentheses = false +ij_groovy_spaces_within_array_initializer_braces = false +ij_groovy_spaces_within_braces = true +ij_groovy_spaces_within_brackets = false +ij_groovy_spaces_within_cast_parentheses = false +ij_groovy_spaces_within_catch_parentheses = false +ij_groovy_spaces_within_for_parentheses = false +ij_groovy_spaces_within_gstring_injection_braces = false +ij_groovy_spaces_within_if_parentheses = false +ij_groovy_spaces_within_list_or_map = false +ij_groovy_spaces_within_method_call_parentheses = false +ij_groovy_spaces_within_method_parentheses = false +ij_groovy_spaces_within_parentheses = false +ij_groovy_spaces_within_switch_parentheses = false +ij_groovy_spaces_within_synchronized_parentheses = false +ij_groovy_spaces_within_try_parentheses = false +ij_groovy_spaces_within_tuple_expression = false +ij_groovy_spaces_within_while_parentheses = false +ij_groovy_special_else_if_treatment = true +ij_groovy_ternary_operation_wrap = off +ij_groovy_throws_keyword_wrap = off +ij_groovy_throws_list_wrap = off +ij_groovy_use_flying_geese_braces = false +ij_groovy_use_fq_class_names = false +ij_groovy_use_fq_class_names_in_javadoc = true +ij_groovy_use_relative_indents = false +ij_groovy_use_single_class_imports = true +ij_groovy_variable_annotation_wrap = off +ij_groovy_while_brace_force = never +ij_groovy_while_on_new_line = false +ij_groovy_wrap_long_lines = false + +[{*.gradle.kts, *.kt, *.kts, *.main.kts}] +ij_kotlin_align_in_columns_case_branch = false +ij_kotlin_align_multiline_binary_operation = false +ij_kotlin_align_multiline_extends_list = false +ij_kotlin_align_multiline_method_parentheses = false +ij_kotlin_align_multiline_parameters = true +ij_kotlin_align_multiline_parameters_in_calls = false +ij_kotlin_allow_trailing_comma = false +ij_kotlin_allow_trailing_comma_on_call_site = false +ij_kotlin_assignment_wrap = off +ij_kotlin_blank_lines_after_class_header = 0 +ij_kotlin_blank_lines_around_block_when_branches = 0 +ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1 +ij_kotlin_block_comment_at_first_column = true +ij_kotlin_call_parameters_new_line_after_left_paren = false +ij_kotlin_call_parameters_right_paren_on_new_line = false +ij_kotlin_call_parameters_wrap = off +ij_kotlin_catch_on_new_line = false +ij_kotlin_class_annotation_wrap = split_into_lines +ij_kotlin_continuation_indent_for_chained_calls = true +ij_kotlin_continuation_indent_for_expression_bodies = true +ij_kotlin_continuation_indent_in_argument_lists = true +ij_kotlin_continuation_indent_in_elvis = true +ij_kotlin_continuation_indent_in_if_conditions = true +ij_kotlin_continuation_indent_in_parameter_lists = true +ij_kotlin_continuation_indent_in_supertype_lists = true +ij_kotlin_else_on_new_line = false +ij_kotlin_enum_constants_wrap = off +ij_kotlin_extends_list_wrap = off +ij_kotlin_field_annotation_wrap = split_into_lines +ij_kotlin_finally_on_new_line = false +ij_kotlin_if_rparen_on_new_line = false +ij_kotlin_import_nested_classes = false +ij_kotlin_insert_whitespaces_in_simple_one_line_method = true +ij_kotlin_keep_blank_lines_before_right_brace = 2 +ij_kotlin_keep_blank_lines_in_code = 2 +ij_kotlin_keep_blank_lines_in_declarations = 2 +ij_kotlin_keep_first_column_comment = true +ij_kotlin_keep_indents_on_empty_lines = false +ij_kotlin_keep_line_breaks = true +ij_kotlin_lbrace_on_next_line = false +ij_kotlin_line_comment_add_space = false +ij_kotlin_line_comment_at_first_column = true +ij_kotlin_method_annotation_wrap = split_into_lines +ij_kotlin_method_call_chain_wrap = off +ij_kotlin_method_parameters_new_line_after_left_paren = false +ij_kotlin_method_parameters_right_paren_on_new_line = false +ij_kotlin_method_parameters_wrap = off +ij_kotlin_name_count_to_use_star_import = 5 +ij_kotlin_name_count_to_use_star_import_for_members = 3 +ij_kotlin_parameter_annotation_wrap = off +ij_kotlin_space_after_comma = true +ij_kotlin_space_after_extend_colon = true +ij_kotlin_space_after_type_colon = true +ij_kotlin_space_before_catch_parentheses = true +ij_kotlin_space_before_comma = false +ij_kotlin_space_before_extend_colon = true +ij_kotlin_space_before_for_parentheses = true +ij_kotlin_space_before_if_parentheses = true +ij_kotlin_space_before_lambda_arrow = true +ij_kotlin_space_before_type_colon = false +ij_kotlin_space_before_when_parentheses = true +ij_kotlin_space_before_while_parentheses = true +ij_kotlin_spaces_around_additive_operators = true +ij_kotlin_spaces_around_assignment_operators = true +ij_kotlin_spaces_around_equality_operators = true +ij_kotlin_spaces_around_function_type_arrow = true +ij_kotlin_spaces_around_logical_operators = true +ij_kotlin_spaces_around_multiplicative_operators = true +ij_kotlin_spaces_around_range = false +ij_kotlin_spaces_around_relational_operators = true +ij_kotlin_spaces_around_unary_operator = false +ij_kotlin_spaces_around_when_arrow = true +ij_kotlin_variable_annotation_wrap = off +ij_kotlin_while_on_new_line = false +ij_kotlin_wrap_elvis_expressions = 1 +ij_kotlin_wrap_expression_body_functions = 0 +ij_kotlin_wrap_first_method_in_call_chain = false + +[{*.har, *.jsb2, *.jsb3, *.json, .babelrc, .eslintrc, .stylelintrc, bowerrc, jest.config, mcmod.info}] +indent_size = 2 +ij_json_keep_blank_lines_in_code = 0 +ij_json_keep_indents_on_empty_lines = false +ij_json_keep_line_breaks = true +ij_json_space_after_colon = true +ij_json_space_after_comma = true +ij_json_space_before_colon = true +ij_json_space_before_comma = false +ij_json_spaces_within_braces = false +ij_json_spaces_within_brackets = false +ij_json_wrap_long_lines = false + +[{*.htm, *.html, *.sht, *.shtm, *.shtml}] +ij_html_add_new_line_before_tags = body, div, p, form, h1, h2, h3 +ij_html_align_attributes = true +ij_html_align_text = false +ij_html_attribute_wrap = normal +ij_html_block_comment_at_first_column = true +ij_html_do_not_align_children_of_min_lines = 0 +ij_html_do_not_break_if_inline_tags = title, h1, h2, h3, h4, h5, h6, p +ij_html_do_not_indent_children_of_tags = html, body, thead, tbody, tfoot +ij_html_enforce_quotes = false +ij_html_inline_tags = a, abbr, acronym, b, basefont, bdo, big, br, cite, cite, code, dfn, em, font, i, img, input, kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, var +ij_html_keep_blank_lines = 2 +ij_html_keep_indents_on_empty_lines = false +ij_html_keep_line_breaks = true +ij_html_keep_line_breaks_in_text = true +ij_html_keep_whitespaces = false +ij_html_keep_whitespaces_inside = span, pre, textarea +ij_html_line_comment_at_first_column = true +ij_html_new_line_after_last_attribute = never +ij_html_new_line_before_first_attribute = never +ij_html_quote_style = double +ij_html_remove_new_line_before_tags = br +ij_html_space_after_tag_name = false +ij_html_space_around_equality_in_attribute = false +ij_html_space_inside_empty_tag = false +ij_html_text_wrap = normal +ij_html_uniform_ident = false + +[{*.yaml, *.yml}] +indent_size = 2 +ij_yaml_keep_indents_on_empty_lines = false +ij_yaml_keep_line_breaks = true +ij_yaml_space_before_colon = true +ij_yaml_spaces_within_braces = true +ij_yaml_spaces_within_brackets = true diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 1a4eea8c..baa1eac7 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -9,4 +9,4 @@ community_bridge: # Replace with a single Community Bridge project-name e.g., cl liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username -custom: ['https://paypal.me/Sauilitired']# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] +custom: [ 'https://paypal.me/Sauilitired' ]# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 45f317c5..76e22beb 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,7 @@ version: 2 updates: - - package-ecosystem: "maven" # See documentation for possible values - directory: "/" # Location of package manifests - schedule: - interval: "daily" + - package-ecosystem: "maven" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "daily" diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index b3ae1ec8..5132ca74 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -4,21 +4,21 @@ name: Java CI with Maven on: - push: - branches: [ master ] - pull_request: - branches: [ master ] + push: + branches: [ master ] + pull_request: + branches: [ master ] jobs: - build: + build: - runs-on: ubuntu-latest + runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build with Gradle - run: ./gradlew clean build + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Build with Gradle + run: ./gradlew clean build diff --git a/build.gradle b/build.gradle index 8bb6fefb..0614e762 100644 --- a/build.gradle +++ b/build.gradle @@ -171,9 +171,11 @@ subprojects { } signing { - required { project.hasProperty('signing.keyId') && (gradle.taskGraph.hasTask(':publish') - || gradle.taskGraph.hasTask(':publishToSonatype') - || gradle.taskGraph.hasTask(':publishToMavenLocal')) } + required { + project.hasProperty('signing.keyId') && (gradle.taskGraph.hasTask(':publish') + || gradle.taskGraph.hasTask(':publishToSonatype') + || gradle.taskGraph.hasTask(':publishToMavenLocal')) + } sign publishing.publications.mavenJava } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/AnnotationParser.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/AnnotationParser.java index 55426ec3..c15bc765 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/AnnotationParser.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/AnnotationParser.java @@ -30,13 +30,13 @@ import cloud.commandframework.arguments.CommandArgument; import cloud.commandframework.arguments.flags.CommandFlag; import cloud.commandframework.arguments.parser.ArgumentParser; import cloud.commandframework.arguments.parser.ParserParameter; +import cloud.commandframework.arguments.parser.ParserParameters; import cloud.commandframework.arguments.parser.StandardParameters; import cloud.commandframework.execution.CommandExecutionHandler; import cloud.commandframework.extra.confirmation.CommandConfirmationManager; import cloud.commandframework.meta.CommandMeta; import cloud.commandframework.meta.SimpleCommandMeta; import io.leangen.geantyref.TypeToken; -import cloud.commandframework.arguments.parser.ParserParameters; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -77,9 +77,11 @@ public final class AnnotationParser { * {@link ParserParameter}. Mappers for the * parser parameters can be registered using {@link #registerAnnotationMapper(Class, Function)} */ - public AnnotationParser(final @NonNull CommandManager manager, - final @NonNull Class commandSenderClass, - final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper) { + public AnnotationParser( + final @NonNull CommandManager manager, + final @NonNull Class commandSenderClass, + final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper + ) { this.commandSenderClass = commandSenderClass; this.manager = manager; this.metaFactory = new MetaFactory(this, metaMapper); @@ -96,9 +98,11 @@ public final class AnnotationParser { * @param mapper Mapping function * @param Annotation type */ - public void registerAnnotationMapper(final @NonNull Class annotation, - final @NonNull Function<@NonNull A, - @NonNull ParserParameters> mapper) { + public void registerAnnotationMapper( + final @NonNull Class annotation, + final @NonNull Function<@NonNull A, + @NonNull ParserParameters> mapper + ) { this.annotationMappers.put(annotation, mapper); } @@ -122,8 +126,10 @@ public final class AnnotationParser { method.setAccessible(true); } if (method.getReturnType() != Void.TYPE) { - throw new IllegalArgumentException(String.format("@CommandMethod annotated method '%s' has non-void return type", - method.getName())); + throw new IllegalArgumentException(String.format( + "@CommandMethod annotated method '%s' has non-void return type", + method.getName() + )); } commandMethodPairs.add(new CommandMethodPair(method, commandMethod)); } @@ -139,7 +145,8 @@ public final class AnnotationParser { @SuppressWarnings("unchecked") private @NonNull Collection<@NonNull Command> construct( final @NonNull Object instance, - final @NonNull Collection<@NonNull CommandMethodPair> methodPairs) { + final @NonNull Collection<@NonNull CommandMethodPair> methodPairs + ) { final Collection> commands = new ArrayList<>(); for (final CommandMethodPair commandMethodPair : methodPairs) { final CommandMethod commandMethod = commandMethodPair.getCommandMethod(); @@ -149,24 +156,28 @@ public final class AnnotationParser { final String commandToken = commandMethod.value().split(" ")[0].split("\\|")[0]; @SuppressWarnings("ALL") final CommandManager manager = this.manager; final SimpleCommandMeta.Builder metaBuilder = SimpleCommandMeta.builder() - .with(this.metaFactory.apply(method.getAnnotations())); + .with(this.metaFactory.apply(method.getAnnotations())); if (method.isAnnotationPresent(Confirmation.class)) { metaBuilder.with(CommandConfirmationManager.CONFIRMATION_REQUIRED_META, "true"); } @SuppressWarnings("ALL") - Command.Builder builder = manager.commandBuilder(commandToken, - tokens.get(commandToken).getMinor(), - metaBuilder.build()); + Command.Builder builder = manager.commandBuilder( + commandToken, + tokens.get(commandToken).getMinor(), + metaBuilder.build() + ); final Collection arguments = this.argumentExtractor.apply(method); final Collection> flags = this.flagExtractor.apply(method); final Map> commandArguments = new HashMap<>(); final Map, String> argumentDescriptions = new HashMap<>(); /* Go through all annotated parameters and build up the argument tree */ for (final ArgumentParameterPair argumentPair : arguments) { - final CommandArgument argument = this.buildArgument(method, - tokens.get(argumentPair.getArgument().value()), - argumentPair); + final CommandArgument argument = this.buildArgument( + method, + tokens.get(argumentPair.getArgument().value()), + argumentPair + ); commandArguments.put(argument.getName(), argument); argumentDescriptions.put(argument, argumentPair.getArgument().description()); } @@ -209,9 +220,9 @@ public final class AnnotationParser { } if (commandMethod.requiredSender() != Object.class) { - builder = builder.withSenderType(commandMethod.requiredSender()); + builder = builder.senderType(commandMethod.requiredSender()); } else if (senderType != null) { - builder = builder.withSenderType(senderType); + builder = builder.senderType(senderType); } try { /* Construct the handler */ @@ -240,7 +251,7 @@ public final class AnnotationParser { throw new IllegalArgumentException("@ProxiedBy proxies may only contain single literals"); } Command.Builder proxyBuilder = manager.commandBuilder(proxy, builtCommand.getCommandMeta()) - .proxies(builtCommand); + .proxies(builtCommand); if (proxyAnnotation.hidden()) { proxyBuilder = proxyBuilder.hidden(); } @@ -251,34 +262,38 @@ public final class AnnotationParser { } @SuppressWarnings("unchecked") - private @NonNull CommandArgument buildArgument(final @NonNull Method method, - final @Nullable SyntaxFragment syntaxFragment, - final @NonNull ArgumentParameterPair argumentPair) { + private @NonNull CommandArgument buildArgument( + final @NonNull Method method, + final @Nullable SyntaxFragment syntaxFragment, + final @NonNull ArgumentParameterPair argumentPair + ) { final Parameter parameter = argumentPair.getParameter(); final Collection annotations = Arrays.asList(parameter.getAnnotations()); final TypeToken token = TypeToken.get(parameter.getParameterizedType()); final ParserParameters parameters = this.manager.getParserRegistry() - .parseAnnotations(token, annotations); + .parseAnnotations(token, annotations); final ArgumentParser parser; if (argumentPair.getArgument().parserName().isEmpty()) { parser = this.manager.getParserRegistry() - .createParser(token, parameters) - .orElseThrow(() -> new IllegalArgumentException( - String.format("Parameter '%s' in method '%s' " - + "has parser '%s' but no parser exists " - + "for that type", - parameter.getName(), method.getName(), - token.toString()))); + .createParser(token, parameters) + .orElseThrow(() -> new IllegalArgumentException( + String.format("Parameter '%s' in method '%s' " + + "has parser '%s' but no parser exists " + + "for that type", + parameter.getName(), method.getName(), + token.toString() + ))); } else { parser = this.manager.getParserRegistry() - .createParser(argumentPair.getArgument().parserName(), parameters) - .orElseThrow(() -> new IllegalArgumentException( - String.format("Parameter '%s' in method '%s' " - + "has parser '%s' but no parser exists " - + "for that type", - parameter.getName(), method.getName(), - token.toString()))); + .createParser(argumentPair.getArgument().parserName(), parameters) + .orElseThrow(() -> new IllegalArgumentException( + String.format("Parameter '%s' in method '%s' " + + "has parser '%s' but no parser exists " + + "for that type", + parameter.getName(), method.getName(), + token.toString() + ))); } if (syntaxFragment == null || syntaxFragment.getArgumentMode() == ArgumentMode.LITERAL) { @@ -287,8 +302,10 @@ public final class AnnotationParser { + "Missing syntax mapping", argumentPair.getArgument().value(), method.getName())); } final Argument argument = argumentPair.getArgument(); - @SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(parameter.getType(), - argument.value()); + @SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType( + parameter.getType(), + argument.value() + ); if (syntaxFragment.getArgumentMode() == ArgumentMode.OPTIONAL) { if (argument.defaultValue().isEmpty()) { argumentBuilder.asOptional(); diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/ArgumentParameterPair.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/ArgumentParameterPair.java index ab779be8..48105f38 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/ArgumentParameterPair.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/ArgumentParameterPair.java @@ -32,8 +32,10 @@ final class ArgumentParameterPair { private final Parameter parameter; private final Argument argument; - ArgumentParameterPair(final @NonNull Parameter parameter, - final @NonNull Argument argument) { + ArgumentParameterPair( + final @NonNull Parameter parameter, + final @NonNull Argument argument + ) { this.parameter = parameter; this.argument = argument; } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/CommandMethodPair.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/CommandMethodPair.java index a241ef61..a276ec1d 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/CommandMethodPair.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/CommandMethodPair.java @@ -32,8 +32,10 @@ final class CommandMethodPair { private final Method method; private final CommandMethod commandMethod; - CommandMethodPair(final @NonNull Method method, - final @NonNull CommandMethod commandMethod) { + CommandMethodPair( + final @NonNull Method method, + final @NonNull CommandMethod commandMethod + ) { this.method = method; this.commandMethod = commandMethod; } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/Confirmation.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/Confirmation.java index a5279bfa..ff961bf6 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/Confirmation.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/Confirmation.java @@ -34,4 +34,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Confirmation { + } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/FlagExtractor.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/FlagExtractor.java index 7ce7aa52..2939b01c 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/FlagExtractor.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/FlagExtractor.java @@ -55,8 +55,10 @@ final class FlagExtractor implements Function<@NonNull Method, Collection<@NonNu continue; } final Flag flag = parameter.getAnnotation(Flag.class); - final CommandFlag.Builder builder = this.commandManager.flagBuilder(flag.value()) - .withDescription(Description.of(flag.description())).withAliases(flag.aliases()); + final CommandFlag.Builder builder = this.commandManager + .flagBuilder(flag.value()) + .withDescription(Description.of(flag.description())) + .withAliases(flag.aliases()); if (parameter.getType().equals(boolean.class)) { flags.add(builder.build()); } else { @@ -72,15 +74,17 @@ final class FlagExtractor implements Function<@NonNull Method, Collection<@NonNu if (parser == null) { throw new IllegalArgumentException( String.format("Cannot find parser for type '%s' for flag '%s' in method '%s'", - parameter.getType().getCanonicalName(), flag.value(), method.getName())); + parameter.getType().getCanonicalName(), flag.value(), method.getName() + )); } - @SuppressWarnings("ALL") - final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(parameter.getType(), flag.value()); - @SuppressWarnings("ALL") - final CommandArgument argument = argumentBuilder.asRequired() - .manager(this.commandManager) - .withParser(parser) - .build(); + @SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType( + parameter.getType(), + flag.value() + ); + @SuppressWarnings("ALL") final CommandArgument argument = argumentBuilder.asRequired() + .manager(this.commandManager) + .withParser(parser) + .build(); // noinspection unchecked flags.add(builder.withArgument(argument).build()); } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/Hidden.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/Hidden.java index c2ae600e..4bea3cd0 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/Hidden.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/Hidden.java @@ -36,4 +36,5 @@ import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Hidden { + } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/MetaFactory.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/MetaFactory.java index 82f4fb14..781d2a90 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/MetaFactory.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/MetaFactory.java @@ -35,8 +35,10 @@ class MetaFactory implements Function<@NonNull Annotation @NonNull [], @NonNull private final AnnotationParser annotationParser; private final Function metaMapper; - MetaFactory(final @NonNull AnnotationParser annotationParser, - final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper) { + MetaFactory( + final @NonNull AnnotationParser annotationParser, + final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper + ) { this.annotationParser = annotationParser; this.metaMapper = metaMapper; } @@ -46,7 +48,7 @@ class MetaFactory implements Function<@NonNull Annotation @NonNull [], @NonNull final ParserParameters parameters = ParserParameters.empty(); for (final Annotation annotation : annotations) { @SuppressWarnings("ALL") final Function function = this.annotationParser.getAnnotationMappers() - .get(annotation.annotationType()); + .get(annotation.annotationType()); if (function == null) { continue; } diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/MethodCommandExecutionHandler.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/MethodCommandExecutionHandler.java index 0fd5c595..159b90a6 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/MethodCommandExecutionHandler.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/MethodCommandExecutionHandler.java @@ -43,10 +43,12 @@ class MethodCommandExecutionHandler implements CommandExecutionHandler { private final MethodHandle methodHandle; private final Map> commandArguments; - MethodCommandExecutionHandler(final @NonNull Object instance, - final @NonNull Map<@NonNull String, - @NonNull CommandArgument<@NonNull C, @NonNull ?>> commandArguments, - @NonNull final Method method) throws Exception { + MethodCommandExecutionHandler( + final @NonNull Object instance, + final @NonNull Map<@NonNull String, + @NonNull CommandArgument<@NonNull C, @NonNull ?>> commandArguments, + @NonNull final Method method + ) throws Exception { this.commandArguments = commandArguments; method.setAccessible(true); this.methodHandle = MethodHandles.lookup().unreflect(method).bindTo(instance); diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxFragment.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxFragment.java index 4757291f..d61de8b3 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxFragment.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxFragment.java @@ -33,9 +33,11 @@ final class SyntaxFragment { private final List minor; private final ArgumentMode argumentMode; - SyntaxFragment(final @NonNull String major, - final @NonNull List<@NonNull String> minor, - final @NonNull ArgumentMode argumentMode) { + SyntaxFragment( + final @NonNull String major, + final @NonNull List<@NonNull String> minor, + final @NonNull ArgumentMode argumentMode + ) { this.major = major; this.minor = minor; this.argumentMode = argumentMode; diff --git a/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxParser.java b/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxParser.java index fc723e35..4a2fb73d 100644 --- a/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxParser.java +++ b/cloud-annotations/src/main/java/cloud/commandframework/annotations/SyntaxParser.java @@ -40,11 +40,11 @@ import java.util.regex.Pattern; final class SyntaxParser implements Function<@NonNull String, @NonNull LinkedHashMap<@NonNull String, @NonNull SyntaxFragment>> { private static final Predicate PATTERN_ARGUMENT_LITERAL = Pattern.compile("([A-Za-z0-9]+)(|([A-Za-z0-9]+))*") - .asPredicate(); + .asPredicate(); private static final Predicate PATTERN_ARGUMENT_REQUIRED = Pattern.compile("<([A-Za-z0-9]+)>") - .asPredicate(); + .asPredicate(); private static final Predicate PATTERN_ARGUMENT_OPTIONAL = Pattern.compile("\\[([A-Za-z0-9]+)]") - .asPredicate(); + .asPredicate(); @Override public @NonNull LinkedHashMap<@NonNull String, @NonNull SyntaxFragment> apply(final @NonNull String syntax) { diff --git a/cloud-annotations/src/test/java/cloud/commandframework/annotations/AnnotationParserTest.java b/cloud-annotations/src/test/java/cloud/commandframework/annotations/AnnotationParserTest.java index 62a0a536..f151dff7 100644 --- a/cloud-annotations/src/test/java/cloud/commandframework/annotations/AnnotationParserTest.java +++ b/cloud-annotations/src/test/java/cloud/commandframework/annotations/AnnotationParserTest.java @@ -64,17 +64,20 @@ class AnnotationParserTest { @ProxiedBy("proxycommand") @CommandMethod("test|t literal [string]") - public void testCommand(final TestCommandSender sender, - @Argument("int") @Range(max = "100") final int argument, - @Argument(value = "string", defaultValue = "potato", parserName = "potato") - final String string) { + public void testCommand( + final TestCommandSender sender, + @Argument("int") @Range(max = "100") final int argument, + @Argument(value = "string", defaultValue = "potato", parserName = "potato") final String string + ) { System.out.printf("Received int: %d and string '%s'\n", argument, string); } @CommandMethod("flagcommand") - public void testFlags(final TestCommandSender sender, - @Flag(value = "print", aliases = "p") boolean print, - @Flag(value = "word", aliases = "w") String word) { + public void testFlags( + final TestCommandSender sender, + @Flag(value = "print", aliases = "p") boolean print, + @Flag(value = "word", aliases = "w") String word + ) { if (print) { System.out.println(word); } diff --git a/cloud-annotations/src/test/java/cloud/commandframework/annotations/TestCommandManager.java b/cloud-annotations/src/test/java/cloud/commandframework/annotations/TestCommandManager.java index cf53b87d..2d591692 100644 --- a/cloud-annotations/src/test/java/cloud/commandframework/annotations/TestCommandManager.java +++ b/cloud-annotations/src/test/java/cloud/commandframework/annotations/TestCommandManager.java @@ -40,8 +40,10 @@ public class TestCommandManager extends CommandManager { } @Override - public final boolean hasPermission(final TestCommandSender sender, - final String permission) { + public final boolean hasPermission( + final TestCommandSender sender, + final String permission + ) { return !permission.equalsIgnoreCase("no"); } diff --git a/cloud-core/src/main/java/cloud/commandframework/Command.java b/cloud-core/src/main/java/cloud/commandframework/Command.java index 743e0c9b..2a3dd0fe 100644 --- a/cloud-core/src/main/java/cloud/commandframework/Command.java +++ b/cloud-core/src/main/java/cloud/commandframework/Command.java @@ -73,11 +73,13 @@ public class Command { * @param commandPermission Command permission * @param commandMeta Command meta instance */ - public Command(final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, - final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, - final @Nullable Class senderType, - final @NonNull CommandPermission commandPermission, - final @NonNull CommandMeta commandMeta) { + public Command( + final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, + final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, + final @Nullable Class senderType, + final @NonNull CommandPermission commandPermission, + final @NonNull CommandMeta commandMeta + ) { this.arguments = Objects.requireNonNull(commandArguments, "Command arguments may not be null"); if (this.arguments.size() == 0) { throw new IllegalArgumentException("At least one command argument is required"); @@ -90,8 +92,10 @@ public class Command { } if (foundOptional && argument.isRequired()) { throw new IllegalArgumentException( - String.format("Command argument '%s' cannot be placed after an optional argument", - argument.getName())); + String.format( + "Command argument '%s' cannot be placed after an optional argument", + argument.getName() + )); } else if (!argument.isRequired()) { foundOptional = true; } @@ -110,10 +114,12 @@ public class Command { * @param senderType Required sender type. May be {@code null} * @param commandMeta Command meta instance */ - public Command(final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, - final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, - final @Nullable Class senderType, - final @NonNull CommandMeta commandMeta) { + public Command( + final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, + final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, + final @Nullable Class senderType, + final @NonNull CommandMeta commandMeta + ) { this(commandArguments, commandExecutionHandler, senderType, Permission.empty(), commandMeta); } @@ -125,10 +131,12 @@ public class Command { * @param commandPermission Command permission * @param commandMeta Command meta instance */ - public Command(final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, - final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, - final @NonNull CommandPermission commandPermission, - final @NonNull CommandMeta commandMeta) { + public Command( + final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, + final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, + final @NonNull CommandPermission commandPermission, + final @NonNull CommandMeta commandMeta + ) { this(commandArguments, commandExecutionHandler, null, commandPermission, commandMeta); } @@ -143,19 +151,23 @@ public class Command { * @param Command sender type * @return Command builder */ - public static @NonNull Builder newBuilder(final @NonNull String commandName, - final @NonNull CommandMeta commandMeta, - final @NonNull Description description, - final @NonNull String... aliases) { + public static @NonNull Builder newBuilder( + final @NonNull String commandName, + final @NonNull CommandMeta commandMeta, + final @NonNull Description description, + final @NonNull String... aliases + ) { final Map<@NonNull CommandArgument, @NonNull Description> map = new LinkedHashMap<>(); map.put(StaticArgument.of(commandName, aliases), description); - return new Builder<>(null, - commandMeta, - null, - map, - new CommandExecutionHandler.NullCommandExecutionHandler<>(), - Permission.empty(), - Collections.emptyList()); + return new Builder<>( + null, + commandMeta, + null, + map, + new CommandExecutionHandler.NullCommandExecutionHandler<>(), + Permission.empty(), + Collections.emptyList() + ); } /** @@ -168,18 +180,22 @@ public class Command { * @param Command sender type * @return Command builder */ - public static @NonNull Builder newBuilder(final @NonNull String commandName, - final @NonNull CommandMeta commandMeta, - final @NonNull String... aliases) { + public static @NonNull Builder newBuilder( + final @NonNull String commandName, + final @NonNull CommandMeta commandMeta, + final @NonNull String... aliases + ) { final Map, Description> map = new LinkedHashMap<>(); map.put(StaticArgument.of(commandName, aliases), Description.empty()); - return new Builder<>(null, - commandMeta, - null, - map, - new CommandExecutionHandler.NullCommandExecutionHandler<>(), - Permission.empty(), - Collections.emptyList()); + return new Builder<>( + null, + commandMeta, + null, + map, + new CommandExecutionHandler.NullCommandExecutionHandler<>(), + Permission.empty(), + Collections.emptyList() + ); } /** @@ -273,13 +289,15 @@ public class Command { private final CommandManager commandManager; private final Collection> flags; - private Builder(final @Nullable CommandManager commandManager, - final @NonNull CommandMeta commandMeta, - final @Nullable Class senderType, - final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, - final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, - final @NonNull CommandPermission commandPermission, - final @NonNull Collection> flags) { + private Builder( + final @Nullable CommandManager commandManager, + final @NonNull CommandMeta commandMeta, + final @Nullable Class senderType, + final @NonNull Map<@NonNull CommandArgument, @NonNull Description> commandArguments, + final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, + final @NonNull CommandPermission commandPermission, + final @NonNull Collection> flags + ) { this.commandManager = commandManager; this.senderType = senderType; this.commandArguments = Objects.requireNonNull(commandArguments, "Arguments may not be null"); @@ -298,13 +316,15 @@ public class Command { */ public @NonNull Builder meta(final @NonNull String key, final @NonNull String value) { final CommandMeta commandMeta = SimpleCommandMeta.builder().with(this.commandMeta).with(key, value).build(); - return new Builder<>(this.commandManager, - commandMeta, - this.senderType, - this.commandArguments, - this.commandExecutionHandler, - this.commandPermission, - this.flags); + return new Builder<>( + this.commandManager, + commandMeta, + this.senderType, + this.commandArguments, + this.commandExecutionHandler, + this.commandPermission, + this.flags + ); } /** @@ -316,13 +336,15 @@ public class Command { * @return New builder instance using the provided command manager */ public @NonNull Builder manager(final @Nullable CommandManager commandManager) { - return new Builder<>(commandManager, - this.commandMeta, - this.senderType, - this.commandArguments, - this.commandExecutionHandler, - this.commandPermission, - this.flags); + return new Builder<>( + commandManager, + this.commandMeta, + this.senderType, + this.commandArguments, + this.commandExecutionHandler, + this.commandPermission, + this.flags + ); } /** @@ -332,8 +354,10 @@ public class Command { * @param aliases Argument aliases * @return New builder instance with the modified command chain */ - public @NonNull Builder literal(final @NonNull String main, - final @NonNull String... aliases) { + public @NonNull Builder literal( + final @NonNull String main, + final @NonNull String... aliases + ) { return this.argument(StaticArgument.of(main, aliases)); } @@ -345,9 +369,11 @@ public class Command { * @param aliases Argument aliases * @return New builder instance with the modified command chain */ - public @NonNull Builder literal(final @NonNull String main, - final @NonNull Description description, - final @NonNull String... aliases) { + public @NonNull Builder literal( + final @NonNull String main, + final @NonNull Description description, + final @NonNull String... aliases + ) { return this.argument(StaticArgument.of(main, aliases), description); } @@ -382,22 +408,26 @@ public class Command { * @param Argument type * @return New builder instance with the command argument inserted into the argument list */ - public @NonNull Builder argument(final @NonNull CommandArgument argument, - final @NonNull Description description) { + public @NonNull Builder argument( + final @NonNull CommandArgument argument, + final @NonNull Description description + ) { if (argument.isArgumentRegistered()) { throw new IllegalArgumentException("The provided argument has already been associated with a command." - + " Use CommandArgument#copy to create a copy of the argument."); + + " Use CommandArgument#copy to create a copy of the argument."); } argument.setArgumentRegistered(); final Map, Description> commandArgumentMap = new LinkedHashMap<>(this.commandArguments); commandArgumentMap.put(argument, description); - return new Builder<>(this.commandManager, - this.commandMeta, - this.senderType, - commandArgumentMap, - this.commandExecutionHandler, - this.commandPermission, - this.flags); + return new Builder<>( + this.commandManager, + this.commandMeta, + this.senderType, + commandArgumentMap, + this.commandExecutionHandler, + this.commandPermission, + this.flags + ); } /** @@ -409,17 +439,21 @@ public class Command { * @param Argument type * @return New builder instance with the command argument inserted into the argument list */ - public @NonNull Builder argument(final CommandArgument.@NonNull Builder builder, - final @NonNull Description description) { + public @NonNull Builder argument( + final CommandArgument.@NonNull Builder builder, + final @NonNull Description description + ) { final Map, Description> commandArgumentMap = new LinkedHashMap<>(this.commandArguments); commandArgumentMap.put(builder.build(), description); - return new Builder<>(this.commandManager, - this.commandMeta, - this.senderType, - commandArgumentMap, - this.commandExecutionHandler, - this.commandPermission, - this.flags); + return new Builder<>( + this.commandManager, + this.commandMeta, + this.senderType, + commandArgumentMap, + this.commandExecutionHandler, + this.commandPermission, + this.flags + ); } /** @@ -431,9 +465,11 @@ public class Command { * @param Argument type * @return New builder instance with the command argument inserted into the argument list */ - public @NonNull Builder argument(final @NonNull Class clazz, - final @NonNull String name, - final @NonNull Consumer> builderConsumer) { + public @NonNull Builder argument( + final @NonNull Class clazz, + final @NonNull String name, + final @NonNull Consumer> builderConsumer + ) { final CommandArgument.Builder builder = CommandArgument.ofType(clazz, name); if (this.commandManager != null) { builder.manager(this.commandManager); @@ -461,10 +497,12 @@ public class Command { * @param Second type * @return Builder instance with the argument inserted */ - public @NonNull Builder argumentPair(final @NonNull String name, - final @NonNull Pair<@NonNull String, @NonNull String> names, - final @NonNull Pair<@NonNull Class, @NonNull Class> parserPair, - final @NonNull Description description) { + public @NonNull Builder argumentPair( + final @NonNull String name, + final @NonNull Pair<@NonNull String, @NonNull String> names, + final @NonNull Pair<@NonNull Class, @NonNull Class> parserPair, + final @NonNull Description description + ) { if (this.commandManager == null) { throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); } @@ -491,18 +529,21 @@ public class Command { * @param Output type * @return Builder instance with the argument inserted */ - public @NonNull Builder argumentPair(final @NonNull String name, - final @NonNull TypeToken outputType, - final @NonNull Pair names, - final @NonNull Pair, Class> parserPair, - final @NonNull BiFunction, O> mapper, - final @NonNull Description description) { + public @NonNull Builder argumentPair( + final @NonNull String name, + final @NonNull TypeToken outputType, + final @NonNull Pair names, + final @NonNull Pair, Class> parserPair, + final @NonNull BiFunction, O> mapper, + final @NonNull Description description + ) { if (this.commandManager == null) { throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); } return this.argument( ArgumentPair.of(this.commandManager, name, names, parserPair).withMapper(outputType, mapper), - description); + description + ); } /** @@ -523,10 +564,12 @@ public class Command { * @param Third type * @return Builder instance with the argument inserted */ - public @NonNull Builder argumentTriplet(final @NonNull String name, - final @NonNull Triplet names, - final @NonNull Triplet, Class, Class> parserTriplet, - final @NonNull Description description) { + public @NonNull Builder argumentTriplet( + final @NonNull String name, + final @NonNull Triplet names, + final @NonNull Triplet, Class, Class> parserTriplet, + final @NonNull Description description + ) { if (this.commandManager == null) { throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); } @@ -554,19 +597,22 @@ public class Command { * @param Output type * @return Builder instance with the argument inserted */ - public @NonNull Builder argumentTriplet(final @NonNull String name, - final @NonNull TypeToken outputType, - final @NonNull Triplet names, - final @NonNull Triplet, Class, - Class> parserTriplet, - final @NonNull BiFunction, O> mapper, - final @NonNull Description description) { + public @NonNull Builder argumentTriplet( + final @NonNull String name, + final @NonNull TypeToken outputType, + final @NonNull Triplet names, + final @NonNull Triplet, Class, + Class> parserTriplet, + final @NonNull BiFunction, O> mapper, + final @NonNull Description description + ) { if (this.commandManager == null) { throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); } return this.argument( ArgumentTriplet.of(this.commandManager, name, names, parserTriplet).withMapper(outputType, mapper), - description); + description + ); } // End of compound helper methods @@ -578,13 +624,15 @@ public class Command { * @return New builder instance using the command execution handler */ public @NonNull Builder handler(final @NonNull CommandExecutionHandler commandExecutionHandler) { - return new Builder<>(this.commandManager, - this.commandMeta, - this.senderType, - this.commandArguments, - commandExecutionHandler, - this.commandPermission, - this.flags); + return new Builder<>( + this.commandManager, + this.commandMeta, + this.senderType, + this.commandArguments, + commandExecutionHandler, + this.commandPermission, + this.flags + ); } /** @@ -593,14 +641,16 @@ public class Command { * @param senderType Required sender type * @return New builder instance using the command execution handler */ - public @NonNull Builder withSenderType(final @NonNull Class senderType) { - return new Builder<>(this.commandManager, - this.commandMeta, - senderType, - this.commandArguments, - this.commandExecutionHandler, - this.commandPermission, - this.flags); + public @NonNull Builder senderType(final @NonNull Class senderType) { + return new Builder<>( + this.commandManager, + this.commandMeta, + senderType, + this.commandArguments, + this.commandExecutionHandler, + this.commandPermission, + this.flags + ); } /** @@ -610,13 +660,15 @@ public class Command { * @return New builder instance using the command permission */ public @NonNull Builder withPermission(final @NonNull CommandPermission permission) { - return new Builder<>(this.commandManager, - this.commandMeta, - this.senderType, - this.commandArguments, - this.commandExecutionHandler, - permission, - this.flags); + return new Builder<>( + this.commandManager, + this.commandMeta, + this.senderType, + this.commandArguments, + this.commandExecutionHandler, + permission, + this.flags + ); } /** @@ -626,13 +678,15 @@ public class Command { * @return New builder instance using the command permission */ public @NonNull Builder withPermission(final @NonNull String permission) { - return new Builder<>(this.commandManager, - this.commandMeta, - this.senderType, - this.commandArguments, - this.commandExecutionHandler, - Permission.of(permission), - this.flags); + return new Builder<>( + this.commandManager, + this.commandMeta, + this.senderType, + this.commandArguments, + this.commandExecutionHandler, + Permission.of(permission), + this.flags + ); } /** @@ -681,13 +735,15 @@ public class Command { public @NonNull Builder flag(final @NonNull CommandFlag flag) { final List> flags = new ArrayList<>(this.flags); flags.add(flag); - return new Builder<>(this.commandManager, - this.commandMeta, - this.senderType, - this.commandArguments, - this.commandExecutionHandler, - this.commandPermission, - Collections.unmodifiableList(flags)); + return new Builder<>( + this.commandManager, + this.commandMeta, + this.senderType, + this.commandArguments, + this.commandExecutionHandler, + this.commandPermission, + Collections.unmodifiableList(flags) + ); } /** @@ -713,11 +769,13 @@ public class Command { final FlagArgument flagArgument = new FlagArgument<>(this.flags); commandArguments.put(flagArgument, Description.of("Command flags")); } - return new Command<>(Collections.unmodifiableMap(commandArguments), - this.commandExecutionHandler, - this.senderType, - this.commandPermission, - this.commandMeta); + return new Command<>( + Collections.unmodifiableMap(commandArguments), + this.commandExecutionHandler, + this.senderType, + this.commandPermission, + this.commandMeta + ); } } diff --git a/cloud-core/src/main/java/cloud/commandframework/CommandHelpHandler.java b/cloud-core/src/main/java/cloud/commandframework/CommandHelpHandler.java index e892d9e3..9530c629 100644 --- a/cloud-core/src/main/java/cloud/commandframework/CommandHelpHandler.java +++ b/cloud-core/src/main/java/cloud/commandframework/CommandHelpHandler.java @@ -56,10 +56,12 @@ public final class CommandHelpHandler { for (final Command command : this.commandManager.getCommands()) { final List> arguments = command.getArguments(); final String description = command.getCommandMeta().getOrDefault("description", ""); - syntaxHints.add(new VerboseHelpEntry<>(command, - this.commandManager.getCommandSyntaxFormatter() - .apply(arguments, null), - description)); + syntaxHints.add(new VerboseHelpEntry<>( + command, + this.commandManager.getCommandSyntaxFormatter() + .apply(arguments, null), + description + )); } syntaxHints.sort(Comparator.comparing(VerboseHelpEntry::getSyntaxString)); return syntaxHints; @@ -75,58 +77,18 @@ public final class CommandHelpHandler { public @NonNull List<@NonNull String> getLongestSharedChains() { final List chains = new ArrayList<>(); this.commandManager.getCommandTree().getRootNodes().forEach(node -> - chains.add(Objects.requireNonNull(node.getValue()) - .getName() + this.commandManager.getCommandSyntaxFormatter() - .apply(Collections - .emptyList(), - node))); + chains.add(Objects.requireNonNull(node.getValue()) + .getName() + this.commandManager + .getCommandSyntaxFormatter() + .apply( + Collections + .emptyList(), + node + ))); chains.sort(String::compareTo); return chains; } - - public static final class VerboseHelpEntry { - - private final Command command; - private final String syntaxString; - private final String description; - - private VerboseHelpEntry(final @NonNull Command command, - final @NonNull String syntaxString, - final @NonNull String description) { - this.command = command; - this.syntaxString = syntaxString; - this.description = description; - } - - /** - * Get the command - * - * @return Command - */ - public @NonNull Command getCommand() { - return this.command; - } - - /** - * Get the syntax string - * - * @return Syntax string - */ - public @NonNull String getSyntaxString() { - return this.syntaxString; - } - - /** - * Get the command description - * - * @return Command description - */ - public @NonNull String getDescription() { - return this.description; - } - } - /** * Query for help * @@ -144,12 +106,15 @@ public final class CommandHelpHandler { * @param query Query string * @return Help topic, will return an empty {@link IndexHelpTopic} if no results were found */ - public @NonNull HelpTopic queryHelp(final @Nullable C recipient, - final @NonNull String query) { + public @NonNull HelpTopic queryHelp( + final @Nullable C recipient, + final @NonNull String query + ) { final List> commands = this.getAllCommands(); - commands.removeIf(command -> recipient != null && !this.commandManager.hasPermission(recipient, - command.getCommand() - .getCommandPermission())); + commands.removeIf(command -> recipient != null && !this.commandManager.hasPermission( + recipient, + command.getCommand().getCommandPermission() + )); if (query.replace(" ", "").isEmpty()) { return new IndexHelpTopic<>(commands); } @@ -166,7 +131,7 @@ public final class CommandHelpHandler { for (final VerboseHelpEntry entry : commands) { final Command command = entry.getCommand(); @SuppressWarnings("unchecked") final StaticArgument staticArgument = (StaticArgument) command.getArguments() - .get(0); + .get(0); for (final String alias : staticArgument.getAliases()) { if (alias.toLowerCase(Locale.ENGLISH).startsWith(rootFragment.toLowerCase(Locale.ENGLISH))) { availableCommands.add(command); @@ -199,10 +164,12 @@ public final class CommandHelpHandler { for (final Command command : availableCommands) { final List> arguments = command.getArguments(); final String description = command.getCommandMeta().getOrDefault("description", ""); - syntaxHints.add(new VerboseHelpEntry<>(command, - this.commandManager.getCommandSyntaxFormatter() - .apply(arguments, null), - description)); + syntaxHints.add(new VerboseHelpEntry<>( + command, + this.commandManager.getCommandSyntaxFormatter() + .apply(arguments, null), + description + )); } syntaxHints.sort(Comparator.comparing(VerboseHelpEntry::getSyntaxString)); syntaxHints.removeIf(command -> recipient != null @@ -212,22 +179,23 @@ public final class CommandHelpHandler { /* Traverse command to find the most specific help topic */ final CommandTree.Node> node = this.commandManager.getCommandTree() - .getNamedNode(availableCommandLabels.iterator() - .next()); + .getNamedNode(availableCommandLabels.iterator() + .next()); final List> traversedNodes = new LinkedList<>(); CommandTree.Node> head = node; int index = 0; - outer: while (head != null) { + outer: + while (head != null) { ++index; traversedNodes.add(head.getValue()); if (head.getValue() != null && head.getValue().getOwningCommand() != null) { if (head.isLeaf() || index == queryFragments.length) { if (recipient == null || this.commandManager.hasPermission(recipient, head.getValue() - .getOwningCommand() - .getCommandPermission())) { + .getOwningCommand() + .getCommandPermission())) { return new VerboseHelpTopic<>(head.getValue().getOwningCommand()); } } @@ -239,8 +207,8 @@ public final class CommandHelpHandler { if (index < queryFragments.length) { /* We might still be able to match an argument */ for (final CommandTree.Node> child : head.getChildren()) { - @SuppressWarnings("unchecked") - final StaticArgument childArgument = (StaticArgument) child.getValue(); + @SuppressWarnings("unchecked") final StaticArgument childArgument = (StaticArgument) child + .getValue(); if (childArgument == null) { continue; } @@ -260,8 +228,10 @@ public final class CommandHelpHandler { if (recipient == null || child.getValue() == null || child.getValue().getOwningCommand() == null - || this.commandManager.hasPermission(recipient, - child.getValue().getOwningCommand().getCommandPermission())) { + || this.commandManager.hasPermission( + recipient, + child.getValue().getOwningCommand().getCommandPermission() + )) { traversedNodesSub.add(child.getValue()); childSuggestions.add(this.commandManager.getCommandSyntaxFormatter().apply(traversedNodesSub, child)); } @@ -273,7 +243,6 @@ public final class CommandHelpHandler { return new IndexHelpTopic<>(Collections.emptyList()); } - /** * Something that can be returned as the result of a help query *

@@ -287,8 +256,53 @@ public final class CommandHelpHandler { * @param Command sender type */ public interface HelpTopic { + } + public static final class VerboseHelpEntry { + + private final Command command; + private final String syntaxString; + private final String description; + + private VerboseHelpEntry( + final @NonNull Command command, + final @NonNull String syntaxString, + final @NonNull String description + ) { + this.command = command; + this.syntaxString = syntaxString; + this.description = description; + } + + /** + * Get the command + * + * @return Command + */ + public @NonNull Command getCommand() { + return this.command; + } + + /** + * Get the syntax string + * + * @return Syntax string + */ + public @NonNull String getSyntaxString() { + return this.syntaxString; + } + + /** + * Get the command description + * + * @return Command description + */ + public @NonNull String getDescription() { + return this.description; + } + + } /** * Index of available commands @@ -371,8 +385,10 @@ public final class CommandHelpHandler { private final String longestPath; private final List childSuggestions; - private MultiHelpTopic(final @NonNull String longestPath, - final @NonNull List<@NonNull String> childSuggestions) { + private MultiHelpTopic( + final @NonNull String longestPath, + final @NonNull List<@NonNull String> childSuggestions + ) { this.longestPath = longestPath; this.childSuggestions = childSuggestions; } diff --git a/cloud-core/src/main/java/cloud/commandframework/CommandManager.java b/cloud-core/src/main/java/cloud/commandframework/CommandManager.java index 18dcbf0e..582c0307 100644 --- a/cloud-core/src/main/java/cloud/commandframework/CommandManager.java +++ b/cloud-core/src/main/java/cloud/commandframework/CommandManager.java @@ -45,13 +45,13 @@ import cloud.commandframework.execution.preprocessor.AcceptingCommandPreprocesso import cloud.commandframework.execution.preprocessor.CommandPreprocessingContext; import cloud.commandframework.execution.preprocessor.CommandPreprocessor; import cloud.commandframework.internal.CommandRegistrationHandler; -import io.leangen.geantyref.TypeToken; import cloud.commandframework.meta.CommandMeta; import cloud.commandframework.permission.CommandPermission; import cloud.commandframework.permission.OrPermission; import cloud.commandframework.permission.Permission; import cloud.commandframework.services.ServicePipeline; import cloud.commandframework.services.State; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -76,7 +76,8 @@ import java.util.function.Function; public abstract class CommandManager { private final Map, BiConsumer> exceptionHandlers = new HashMap<>(); - private final EnumSet managerSettings = EnumSet.of(ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS); + private final EnumSet managerSettings = EnumSet.of( + ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS); private final CommandContextFactory commandContextFactory = new StandardCommandContextFactory<>(); private final ServicePipeline servicePipeline = ServicePipeline.builder().build(); @@ -97,7 +98,8 @@ public abstract class CommandManager { */ public CommandManager( final @NonNull Function<@NonNull CommandTree, @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull CommandRegistrationHandler commandRegistrationHandler) { + final @NonNull CommandRegistrationHandler commandRegistrationHandler + ) { this.commandTree = CommandTree.newTree(this); this.commandExecutionCoordinator = commandExecutionCoordinator.apply(commandTree); this.commandRegistrationHandler = commandRegistrationHandler; @@ -132,8 +134,10 @@ public abstract class CommandManager { * @param input Input provided by the sender * @return Command result */ - public @NonNull CompletableFuture> executeCommand(final @NonNull C commandSender, - final @NonNull String input) { + public @NonNull CompletableFuture> executeCommand( + final @NonNull C commandSender, + final @NonNull String input + ) { final CommandContext context = this.commandContextFactory.create(false, commandSender); final LinkedList inputQueue = tokenize(input); try { @@ -157,14 +161,18 @@ public abstract class CommandManager { * @param input Input provided by the sender * @return List of suggestions */ - public @NonNull List<@NonNull String> suggest(final @NonNull C commandSender, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggest( + final @NonNull C commandSender, + final @NonNull String input + ) { final CommandContext context = this.commandContextFactory.create(true, commandSender); final LinkedList inputQueue = tokenize(input); if (this.preprocessContext(context, inputQueue) == State.ACCEPTED) { - return this.commandSuggestionProcessor.apply(new CommandPreprocessingContext<>(context, inputQueue), - this.commandTree.getSuggestions( - context, inputQueue)); + return this.commandSuggestionProcessor.apply( + new CommandPreprocessingContext<>(context, inputQueue), + this.commandTree.getSuggestions( + context, inputQueue) + ); } else { return Collections.emptyList(); } @@ -231,8 +239,10 @@ public abstract class CommandManager { * @param permission Permission node * @return {@code true} if the sender has the permission, else {@code false} */ - public boolean hasPermission(final @NonNull C sender, - final @NonNull CommandPermission permission) { + public boolean hasPermission( + final @NonNull C sender, + final @NonNull CommandPermission permission + ) { if (permission.toString().isEmpty()) { return true; } @@ -269,10 +279,12 @@ public abstract class CommandManager { * @param meta Command meta * @return Builder instance */ - public Command.@NonNull Builder commandBuilder(final @NonNull String name, - final @NonNull Collection aliases, - final @NonNull Description description, - final @NonNull CommandMeta meta) { + public Command.@NonNull Builder commandBuilder( + final @NonNull String name, + final @NonNull Collection aliases, + final @NonNull Description description, + final @NonNull CommandMeta meta + ) { return Command.newBuilder(name, meta, description, aliases.toArray(new String[0])); } @@ -284,9 +296,11 @@ public abstract class CommandManager { * @param meta Command meta * @return Builder instance */ - public Command.@NonNull Builder commandBuilder(final @NonNull String name, - final @NonNull Collection aliases, - final @NonNull CommandMeta meta) { + public Command.@NonNull Builder commandBuilder( + final @NonNull String name, + final @NonNull Collection aliases, + final @NonNull CommandMeta meta + ) { return Command.newBuilder(name, meta, Description.empty(), aliases.toArray(new String[0])); } @@ -299,10 +313,12 @@ public abstract class CommandManager { * @param aliases Command aliases * @return Builder instance */ - public Command.@NonNull Builder commandBuilder(final @NonNull String name, - final @NonNull CommandMeta meta, - final @NonNull Description description, - final @NonNull String... aliases) { + public Command.@NonNull Builder commandBuilder( + final @NonNull String name, + final @NonNull CommandMeta meta, + final @NonNull Description description, + final @NonNull String... aliases + ) { return Command.newBuilder(name, meta, description, aliases); } @@ -314,9 +330,11 @@ public abstract class CommandManager { * @param aliases Command aliases * @return Builder instance */ - public Command.@NonNull Builder commandBuilder(final @NonNull String name, - final @NonNull CommandMeta meta, - final @NonNull String... aliases) { + public Command.@NonNull Builder commandBuilder( + final @NonNull String name, + final @NonNull CommandMeta meta, + final @NonNull String... aliases + ) { return Command.newBuilder(name, meta, Description.empty(), aliases); } @@ -330,23 +348,27 @@ public abstract class CommandManager { * @throws UnsupportedOperationException If the command manager does not support default command meta creation * @see #createDefaultCommandMeta() Default command meta creation */ - public Command.@NonNull Builder commandBuilder(final @NonNull String name, - final @NonNull Description description, - final @NonNull String... aliases) { + public Command.@NonNull Builder commandBuilder( + final @NonNull String name, + final @NonNull Description description, + final @NonNull String... aliases + ) { return Command.newBuilder(name, this.createDefaultCommandMeta(), description, aliases).manager(this); } /** * Create a new command builder using a default command meta instance. * - * @param name Command name - * @param aliases Command aliases + * @param name Command name + * @param aliases Command aliases * @return Builder instance * @throws UnsupportedOperationException If the command manager does not support default command meta creation * @see #createDefaultCommandMeta() Default command meta creation */ - public Command.@NonNull Builder commandBuilder(final @NonNull String name, - final @NonNull String... aliases) { + public Command.@NonNull Builder commandBuilder( + final @NonNull String name, + final @NonNull String... aliases + ) { return Command.newBuilder(name, this.createDefaultCommandMeta(), Description.empty(), aliases).manager(this); } @@ -358,8 +380,10 @@ public abstract class CommandManager { * @param Generic argument name * @return Argument builder */ - public CommandArgument.@NonNull Builder argumentBuilder(final @NonNull Class type, - final @NonNull String name) { + public CommandArgument.@NonNull Builder argumentBuilder( + final @NonNull Class type, + final @NonNull String name + ) { return CommandArgument.ofType(type, name).manager(this); } @@ -401,7 +425,8 @@ public abstract class CommandManager { public void registerCommandPreProcessor(final @NonNull CommandPreprocessor processor) { this.servicePipeline.registerServiceImplementation(new TypeToken>() { }, processor, - Collections.emptyList()); + Collections.emptyList() + ); } /** @@ -414,7 +439,8 @@ public abstract class CommandManager { public void registerCommandPostProcessor(final @NonNull CommandPostprocessor processor) { this.servicePipeline.registerServiceImplementation(new TypeToken>() { }, processor, - Collections.emptyList()); + Collections.emptyList() + ); } /** @@ -425,15 +451,17 @@ public abstract class CommandManager { * @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED} * @see #registerCommandPreProcessor(CommandPreprocessor) Register a command preprocessor */ - public State preprocessContext(final @NonNull CommandContext context, - final @NonNull LinkedList<@NonNull String> inputQueue) { + public State preprocessContext( + final @NonNull CommandContext context, + final @NonNull LinkedList<@NonNull String> inputQueue + ) { this.servicePipeline.pump(new CommandPreprocessingContext<>(context, inputQueue)) - .through(new TypeToken>() { - }) - .getResult(); + .through(new TypeToken>() { + }) + .getResult(); return context.getOptional(AcceptingCommandPreprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty() - ? State.REJECTED - : State.ACCEPTED; + ? State.REJECTED + : State.ACCEPTED; } /** @@ -444,15 +472,17 @@ public abstract class CommandManager { * @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED} * @see #registerCommandPostProcessor(CommandPostprocessor) Register a command postprocessor */ - public State postprocessContext(final @NonNull CommandContext context, - final @NonNull Command command) { + public State postprocessContext( + final @NonNull CommandContext context, + final @NonNull Command command + ) { this.servicePipeline.pump(new CommandPostprocessingContext<>(context, command)) - .through(new TypeToken>() { - }) - .getResult(); + .through(new TypeToken>() { + }) + .getResult(); return context.getOptional(AcceptingCommandPostprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty() - ? State.REJECTED - : State.ACCEPTED; + ? State.REJECTED + : State.ACCEPTED; } /** @@ -520,8 +550,10 @@ public abstract class CommandManager { * @param handler Exception handler * @param Exception type */ - public final void registerExceptionHandler(final @NonNull Class clazz, - final @NonNull BiConsumer<@NonNull C, @NonNull E> handler) { + public final void registerExceptionHandler( + final @NonNull Class clazz, + final @NonNull BiConsumer<@NonNull C, @NonNull E> handler + ) { this.exceptionHandlers.put(clazz, handler); } @@ -536,10 +568,12 @@ public abstract class CommandManager { * handler stored for the exception type * @param Exception type */ - public final void handleException(final @NonNull C sender, - final @NonNull Class clazz, - final @NonNull E exception, - final @NonNull BiConsumer defaultHandler) { + public final void handleException( + final @NonNull C sender, + final @NonNull Class clazz, + final @NonNull E exception, + final @NonNull BiConsumer defaultHandler + ) { Optional.ofNullable(this.getExceptionHandler(clazz)).orElse(defaultHandler).accept(sender, exception); } @@ -557,7 +591,7 @@ public abstract class CommandManager { * of command help menus, etc. * * @return Command help handler. A new instance will be created - * each time this method is called. + * each time this method is called. */ public final @NonNull CommandHelpHandler getCommandHelpHandler() { return new CommandHelpHandler<>(this); @@ -580,8 +614,10 @@ public abstract class CommandManager { * @param value Value */ @SuppressWarnings("unused") - public void setSetting(final @NonNull ManagerSettings setting, - final boolean value) { + public void setSetting( + final @NonNull ManagerSettings setting, + final boolean value + ) { if (value) { this.managerSettings.add(setting); } else { diff --git a/cloud-core/src/main/java/cloud/commandframework/CommandTree.java b/cloud-core/src/main/java/cloud/commandframework/CommandTree.java index 458122c1..fe4632d3 100644 --- a/cloud-core/src/main/java/cloud/commandframework/CommandTree.java +++ b/cloud-core/src/main/java/cloud/commandframework/CommandTree.java @@ -112,45 +112,58 @@ public final class CommandTree { * @param args Input * @return Parsed command, if one could be found */ - public @NonNull Pair<@Nullable Command, @Nullable Exception> parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> args) { - final Pair<@Nullable Command, @Nullable Exception> pair = this.parseCommand(new ArrayList<>(), - commandContext, - args, - this.internalTree); + public @NonNull Pair<@Nullable Command, @Nullable Exception> parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> args + ) { + final Pair<@Nullable Command, @Nullable Exception> pair = this.parseCommand( + new ArrayList<>(), + commandContext, + args, + this.internalTree + ); if (pair.getFirst() != null) { final Command command = pair.getFirst(); if (command.getSenderType().isPresent() && !command.getSenderType().get() - .isAssignableFrom(commandContext.getSender().getClass())) { - return Pair.of(null, new InvalidCommandSenderException(commandContext.getSender(), - command.getSenderType().get(), - Collections.emptyList())); + .isAssignableFrom(commandContext + .getSender() + .getClass())) { + return Pair.of(null, new InvalidCommandSenderException( + commandContext.getSender(), + command.getSenderType().get(), + Collections.emptyList() + )); } } return pair; } - private @NonNull Pair<@Nullable Command, @Nullable Exception> - parseCommand(final @NonNull List<@NonNull CommandArgument> parsedArguments, - final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> commandQueue, - final @NonNull Node<@Nullable CommandArgument> root) { + private @NonNull Pair<@Nullable Command, @Nullable Exception> parseCommand( + final @NonNull List<@NonNull CommandArgument> parsedArguments, + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> commandQueue, + final @NonNull Node<@Nullable CommandArgument> root + ) { CommandPermission permission = this.isPermitted(commandContext.getSender(), root); if (permission != null) { - return Pair.of(null, new NoPermissionException(permission, - commandContext.getSender(), - this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + return Pair.of(null, new NoPermissionException( + permission, + commandContext.getSender(), + this.getChain(root) + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } - final Pair<@Nullable Command, @Nullable Exception> parsedChild = this.attemptParseUnambiguousChild(parsedArguments, - commandContext, - root, - commandQueue); + final Pair<@Nullable Command, @Nullable Exception> parsedChild = this.attemptParseUnambiguousChild( + parsedArguments, + commandContext, + root, + commandQueue + ); if (parsedChild.getFirst() != null || parsedChild.getSecond() != null) { return parsedChild; } @@ -165,23 +178,25 @@ public final class CommandTree { /* Too many arguments. We have a unique path, so we can send the entire context */ return Pair.of(null, new InvalidSyntaxException( this.commandManager.getCommandSyntaxFormatter() - .apply(parsedArguments, root), + .apply(parsedArguments, root), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } } else { /* Too many arguments. We have a unique path, so we can send the entire context */ return Pair.of(null, new InvalidSyntaxException( this.commandManager.getCommandSyntaxFormatter() - .apply(parsedArguments, root), + .apply(parsedArguments, root), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } } else { final Iterator>> childIterator = root.getChildren().iterator(); @@ -208,33 +223,38 @@ public final class CommandTree { return Pair.of(null, new NoSuchCommandException( commandContext.getSender(), getChain(root).stream().map(Node::getValue).collect(Collectors.toList()), - stringOrEmpty(commandQueue.peek()))); + stringOrEmpty(commandQueue.peek()) + )); } /* If we couldn't match a child, check if there's a command attached and execute it */ if (root.getValue() != null && root.getValue().getOwningCommand() != null && commandQueue.isEmpty()) { final Command command = root.getValue().getOwningCommand(); - if (!this.getCommandManager().hasPermission(commandContext.getSender(), - command.getCommandPermission())) { + if (!this.getCommandManager().hasPermission( + commandContext.getSender(), + command.getCommandPermission() + )) { return Pair.of(null, new NoPermissionException( command.getCommandPermission(), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } return Pair.of(root.getValue().getOwningCommand(), null); } /* We know that there's no command and we also cannot match any of the children */ return Pair.of(null, new InvalidSyntaxException( this.commandManager.getCommandSyntaxFormatter() - .apply(parsedArguments, root), + .apply(parsedArguments, root), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } } @@ -242,7 +262,8 @@ public final class CommandTree { final @NonNull List<@NonNull CommandArgument> parsedArguments, final @NonNull CommandContext commandContext, final @NonNull Node<@Nullable CommandArgument> root, - final @NonNull Queue commandQueue) { + final @NonNull Queue commandQueue + ) { CommandPermission permission; final List>> children = root.getChildren(); if (children.size() == 1 && !(children.get(0).getValue() instanceof StaticArgument)) { @@ -254,11 +275,11 @@ public final class CommandTree { permission, commandContext.getSender(), this.getChain(child) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect( - Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } if (child.getValue() != null) { if (commandQueue.isEmpty()) { @@ -270,58 +291,65 @@ public final class CommandTree { /* The child is not a leaf, but may have an intermediary executor, attempt to use it */ if (root.getValue() != null && root.getValue().getOwningCommand() != null) { final Command command = root.getValue().getOwningCommand(); - if (!this.getCommandManager().hasPermission(commandContext.getSender(), - command.getCommandPermission())) { + if (!this.getCommandManager().hasPermission( + commandContext.getSender(), + command.getCommandPermission() + )) { return Pair.of(null, new NoPermissionException( command.getCommandPermission(), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } return Pair.of(command, null); } /* Not enough arguments */ return Pair.of(null, new InvalidSyntaxException( this.commandManager.getCommandSyntaxFormatter() - .apply(Objects.requireNonNull( - child.getValue() - .getOwningCommand()) - .getArguments(), child), + .apply(Objects.requireNonNull( + child.getValue() + .getOwningCommand()) + .getArguments(), child), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect( - Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } else { /* The child is not a leaf, but may have an intermediary executor, attempt to use it */ if (root.getValue() != null && root.getValue().getOwningCommand() != null) { final Command command = root.getValue().getOwningCommand(); - if (!this.getCommandManager().hasPermission(commandContext.getSender(), - command.getCommandPermission())) { + if (!this.getCommandManager().hasPermission( + commandContext.getSender(), + command.getCommandPermission() + )) { return Pair.of(null, new NoPermissionException( command.getCommandPermission(), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } return Pair.of(command, null); } /* Child does not have a command and so we cannot proceed */ return Pair.of(null, new InvalidSyntaxException( this.commandManager.getCommandSyntaxFormatter() - .apply(parsedArguments, root), + .apply(parsedArguments, root), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } } @@ -341,13 +369,13 @@ public final class CommandTree { /* Too many arguments. We have a unique path, so we can send the entire context */ return Pair.of(null, new InvalidSyntaxException( this.commandManager.getCommandSyntaxFormatter() - .apply(parsedArguments, child), + .apply(parsedArguments, child), commandContext.getSender(), this.getChain(root) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect( - Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } } else { parsedArguments.add(child.getValue()); @@ -357,10 +385,11 @@ public final class CommandTree { return Pair.of(null, new ArgumentParseException( result.getFailure().get(), commandContext.getSender(), this.getChain(child) - .stream() - .filter(node -> node.getValue() != null) - .map(Node::getValue) - .collect(Collectors.toList()))); + .stream() + .filter(node -> node.getValue() != null) + .map(Node::getValue) + .collect(Collectors.toList()) + )); } } } @@ -374,14 +403,18 @@ public final class CommandTree { * @param commandQueue Input queue * @return String suggestions. These should be filtered based on {@link String#startsWith(String)} */ - public @NonNull List<@NonNull String> getSuggestions(final @NonNull CommandContext context, - final @NonNull Queue<@NonNull String> commandQueue) { + public @NonNull List<@NonNull String> getSuggestions( + final @NonNull CommandContext context, + final @NonNull Queue<@NonNull String> commandQueue + ) { return getSuggestions(context, commandQueue, this.internalTree); } - private @NonNull List<@NonNull String> getSuggestions(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> commandQueue, - final @NonNull Node<@Nullable CommandArgument> root) { + private @NonNull List<@NonNull String> getSuggestions( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> commandQueue, + final @NonNull Node<@Nullable CommandArgument> root + ) { /* If the sender isn't allowed to access the root node, no suggestions are needed */ if (this.isPermitted(commandContext.getSender(), root) != null) { @@ -395,8 +428,8 @@ public final class CommandTree { // START: Compound arguments /* When we get in here, we need to treat compound arguments a little differently */ if (child.getValue() instanceof CompoundArgument) { - @SuppressWarnings("unchecked") - final CompoundArgument compoundArgument = (CompoundArgument) child.getValue(); + @SuppressWarnings("unchecked") final CompoundArgument compoundArgument = (CompoundArgument) child + .getValue(); /* See how many arguments it requires */ final int requiredArguments = compoundArgument.getParserTuple().getSize(); /* Figure out whether we even need to care about this */ @@ -453,7 +486,10 @@ public final class CommandTree { while (childIterator.hasNext()) { final Node> child = childIterator.next(); if (child.getValue() != null) { - final ArgumentParseResult result = child.getValue().getParser().parse(commandContext, commandQueue); + final ArgumentParseResult result = child.getValue().getParser().parse( + commandContext, + commandQueue + ); if (result.getParsedValue().isPresent()) { return this.getSuggestions(commandContext, commandQueue, child); } @@ -466,7 +502,7 @@ public final class CommandTree { continue; } suggestions.addAll(argument.getValue().getSuggestionsProvider() - .apply(commandContext, stringOrEmpty(commandQueue.peek()))); + .apply(commandContext, stringOrEmpty(commandQueue.peek()))); } return suggestions; } @@ -517,19 +553,27 @@ public final class CommandTree { } } - private @Nullable CommandPermission isPermitted(final @NonNull C sender, - final @NonNull Node<@Nullable CommandArgument> node) { + private @Nullable CommandPermission isPermitted( + final @NonNull C sender, + final @NonNull Node<@Nullable CommandArgument> node + ) { final CommandPermission permission = (CommandPermission) node.nodeMeta.get("permission"); if (permission != null) { return this.commandManager.hasPermission(sender, permission) ? null : permission; } if (node.isLeaf()) { - return this.commandManager.hasPermission(sender, - Objects.requireNonNull( - Objects.requireNonNull(node.value, "node.value").getOwningCommand(), - "owning command").getCommandPermission()) - ? null : Objects.requireNonNull(node.value.getOwningCommand(), "owning command") - .getCommandPermission(); + return this.commandManager.hasPermission( + sender, + Objects.requireNonNull( + Objects.requireNonNull( + node.value, + "node.value" + ).getOwningCommand(), + "owning command" + ).getCommandPermission() + ) + ? null : Objects.requireNonNull(node.value.getOwningCommand(), "owning command") + .getCommandPermission(); } /* if any of the children would permit the execution, then the sender has a valid @@ -584,7 +628,8 @@ public final class CommandTree { chain = chain.subList(1, chain.size()); // Go through all nodes from the tail upwards until a collision occurs for (final Node> commandArgumentNode : chain) { - final CommandPermission existingPermission = (CommandPermission) commandArgumentNode.nodeMeta.get("permission"); + final CommandPermission existingPermission = (CommandPermission) commandArgumentNode.nodeMeta + .get("permission"); CommandPermission permission; if (existingPermission != null) { @@ -594,9 +639,13 @@ public final class CommandTree { } /* Now also check if there's a command handler attached to an upper level node */ - if (commandArgumentNode.getValue() != null && commandArgumentNode.getValue().getOwningCommand() != null) { + if (commandArgumentNode.getValue() != null && commandArgumentNode + .getValue() + .getOwningCommand() != null) { final Command command = commandArgumentNode.getValue().getOwningCommand(); - if (this.getCommandManager().getSetting(CommandManager.ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS)) { + if (this + .getCommandManager() + .getSetting(CommandManager.ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS)) { permission = command.getCommandPermission(); } else { permission = OrPermission.of(Arrays.asList(permission, command.getCommandPermission())); @@ -608,26 +657,30 @@ public final class CommandTree { }); } - private void checkAmbiguity(final @NonNull Node<@Nullable CommandArgument> node) throws AmbiguousNodeException { + private void checkAmbiguity(final @NonNull Node<@Nullable CommandArgument> node) throws + AmbiguousNodeException { if (node.isLeaf()) { return; } final int size = node.children.size(); for (final Node> child : node.children) { if (child.getValue() != null && !child.getValue().isRequired() && size > 1) { - throw new AmbiguousNodeException(node.getValue(), - child.getValue(), - node.getChildren() - .stream() - .filter(n -> n.getValue() != null) - .map(Node::getValue).collect(Collectors.toList())); + throw new AmbiguousNodeException( + node.getValue(), + child.getValue(), + node.getChildren() + .stream() + .filter(n -> n.getValue() != null) + .map(Node::getValue).collect(Collectors.toList()) + ); } } node.children.forEach(this::checkAmbiguity); } - private @NonNull List<@NonNull Node<@Nullable CommandArgument>> - getLeavesRaw(final @NonNull Node<@Nullable CommandArgument> node) { + private @NonNull List<@NonNull Node<@Nullable CommandArgument>> getLeavesRaw( + final @NonNull Node<@Nullable CommandArgument> node + ) { final List>> leaves = new LinkedList<>(); if (node.isLeaf()) { if (node.getValue() != null) { @@ -639,7 +692,9 @@ public final class CommandTree { return leaves; } - private @NonNull List<@NonNull CommandArgument> getLeaves(final @NonNull Node<@NonNull CommandArgument> node) { + private @NonNull List<@NonNull CommandArgument> getLeaves( + final @NonNull Node<@NonNull CommandArgument> node + ) { final List> leaves = new LinkedList<>(); if (node.isLeaf()) { if (node.getValue() != null) { @@ -651,8 +706,9 @@ public final class CommandTree { return leaves; } - private @NonNull List<@NonNull Node<@Nullable CommandArgument>> - getChain(final @Nullable Node<@Nullable CommandArgument> end) { + private @NonNull List<@NonNull Node<@Nullable CommandArgument>> getChain( + final @Nullable Node<@Nullable CommandArgument> end + ) { final List>> chain = new LinkedList<>(); Node> tail = end; while (tail != null) { @@ -812,6 +868,7 @@ public final class CommandTree { public String toString() { return "Node{value=" + value + '}'; } + } } diff --git a/cloud-core/src/main/java/cloud/commandframework/Description.java b/cloud-core/src/main/java/cloud/commandframework/Description.java index 3e2cc9cb..4df3b2c9 100644 --- a/cloud-core/src/main/java/cloud/commandframework/Description.java +++ b/cloud-core/src/main/java/cloud/commandframework/Description.java @@ -67,7 +67,7 @@ public final class Description { * @return Command description */ public @NonNull String getDescription() { - return this.description; + return this.description; } /** diff --git a/cloud-core/src/main/java/cloud/commandframework/annotations/specifier/Greedy.java b/cloud-core/src/main/java/cloud/commandframework/annotations/specifier/Greedy.java index 58d3f11b..b124fd16 100644 --- a/cloud-core/src/main/java/cloud/commandframework/annotations/specifier/Greedy.java +++ b/cloud-core/src/main/java/cloud/commandframework/annotations/specifier/Greedy.java @@ -34,4 +34,5 @@ import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface Greedy { + } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/CommandArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/CommandArgument.java index edebb486..81238e27 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/CommandArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/CommandArgument.java @@ -23,13 +23,13 @@ // package cloud.commandframework.arguments; -import cloud.commandframework.arguments.parser.ArgumentParser; -import io.leangen.geantyref.TypeToken; import cloud.commandframework.Command; import cloud.commandframework.CommandManager; import cloud.commandframework.arguments.parser.ArgumentParseResult; +import cloud.commandframework.arguments.parser.ArgumentParser; import cloud.commandframework.arguments.parser.ParserParameters; import cloud.commandframework.context.CommandContext; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -99,12 +99,14 @@ public class CommandArgument implements Comparable> * @param valueType Type produced by the parser * @param suggestionsProvider Suggestions provider */ - public CommandArgument(final boolean required, - final @NonNull String name, - final @NonNull ArgumentParser parser, - final @NonNull String defaultValue, - final @NonNull TypeToken valueType, - final @Nullable BiFunction, String, List> suggestionsProvider) { + public CommandArgument( + final boolean required, + final @NonNull String name, + final @NonNull ArgumentParser parser, + final @NonNull String defaultValue, + final @NonNull TypeToken valueType, + final @Nullable BiFunction, String, List> suggestionsProvider + ) { this.required = required; this.name = Objects.requireNonNull(name, "Name may not be null"); if (!NAME_PATTERN.asPredicate().test(name)) { @@ -114,8 +116,8 @@ public class CommandArgument implements Comparable> this.defaultValue = defaultValue; this.valueType = valueType; this.suggestionsProvider = suggestionsProvider == null - ? buildDefaultSuggestionsProvider(this) - : suggestionsProvider; + ? buildDefaultSuggestionsProvider(this) + : suggestionsProvider; } /** @@ -128,13 +130,15 @@ public class CommandArgument implements Comparable> * @param valueType Type produced by the parser * @param suggestionsProvider Suggestions provider */ - public CommandArgument(final boolean required, - final @NonNull String name, - final @NonNull ArgumentParser parser, - final @NonNull String defaultValue, - final @NonNull Class valueType, - final @Nullable BiFunction<@NonNull CommandContext, - @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { + public CommandArgument( + final boolean required, + final @NonNull String name, + final @NonNull ArgumentParser parser, + final @NonNull String defaultValue, + final @NonNull Class valueType, + final @Nullable BiFunction<@NonNull CommandContext, + @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider + ) { this(required, name, parser, defaultValue, TypeToken.get(valueType), suggestionsProvider); } @@ -146,10 +150,12 @@ public class CommandArgument implements Comparable> * @param parser The argument parser * @param valueType Type produced by the parser */ - public CommandArgument(final boolean required, - final @NonNull String name, - final @NonNull ArgumentParser parser, - final @NonNull Class valueType) { + public CommandArgument( + final boolean required, + final @NonNull String name, + final @NonNull ArgumentParser parser, + final @NonNull Class valueType + ) { this(required, name, parser, "", valueType, null); } @@ -167,8 +173,10 @@ public class CommandArgument implements Comparable> * @param Argument Type. Used to make the compiler happy. * @return Argument builder */ - public static CommandArgument.@NonNull Builder ofType(final @NonNull TypeToken clazz, - final @NonNull String name) { + public static CommandArgument.@NonNull Builder ofType( + final @NonNull TypeToken clazz, + final @NonNull String name + ) { return new Builder<>(clazz, name); } @@ -181,8 +189,10 @@ public class CommandArgument implements Comparable> * @param Argument Type. Used to make the compiler happy. * @return Argument builder */ - public static CommandArgument.@NonNull Builder<@NonNull C, @NonNull T> ofType(final @NonNull Class clazz, - final @NonNull String name) { + public static CommandArgument.@NonNull Builder<@NonNull C, @NonNull T> ofType( + final @NonNull Class clazz, + final @NonNull String name + ) { return new Builder<>(TypeToken.get(clazz), name); } @@ -366,14 +376,18 @@ public class CommandArgument implements Comparable> private String defaultValue = ""; private BiFunction<@NonNull CommandContext, @NonNull String, @NonNull List> suggestionsProvider; - protected Builder(final @NonNull TypeToken valueType, - final @NonNull String name) { + protected Builder( + final @NonNull TypeToken valueType, + final @NonNull String name + ) { this.valueType = valueType; this.name = name; } - protected Builder(final @NonNull Class valueType, - final @NonNull String name) { + protected Builder( + final @NonNull Class valueType, + final @NonNull String name + ) { this(TypeToken.get(valueType), name); } @@ -452,7 +466,8 @@ public class CommandArgument implements Comparable> */ public @NonNull Builder<@NonNull C, @NonNull T> withSuggestionsProvider( final @NonNull BiFunction<@NonNull CommandContext, - @NonNull String, @NonNull List> suggestionsProvider) { + @NonNull String, @NonNull List> suggestionsProvider + ) { this.suggestionsProvider = suggestionsProvider; return this; } @@ -465,7 +480,7 @@ public class CommandArgument implements Comparable> public @NonNull CommandArgument<@NonNull C, @NonNull T> build() { if (this.parser == null && this.manager != null) { this.parser = this.manager.getParserRegistry().createParser(valueType, ParserParameters.empty()) - .orElse(null); + .orElse(null); } if (this.parser == null) { this.parser = (c, i) -> ArgumentParseResult @@ -475,7 +490,8 @@ public class CommandArgument implements Comparable> this.suggestionsProvider = new DelegatingSuggestionsProvider<>(this.name, this.parser); } return new CommandArgument<>(this.required, this.name, this.parser, - this.defaultValue, this.valueType, this.suggestionsProvider); + this.defaultValue, this.valueType, this.suggestionsProvider + ); } protected final @NonNull String getName() { diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/CommandSyntaxFormatter.java b/cloud-core/src/main/java/cloud/commandframework/arguments/CommandSyntaxFormatter.java index 7113df7e..5255ade7 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/CommandSyntaxFormatter.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/CommandSyntaxFormatter.java @@ -44,7 +44,9 @@ public interface CommandSyntaxFormatter { * @param node Trailing node * @return Syntax string */ - @NonNull String apply(@NonNull List<@NonNull CommandArgument> commandArguments, - CommandTree.@Nullable Node<@Nullable CommandArgument> node); + @NonNull String apply( + @NonNull List<@NonNull CommandArgument> commandArguments, + CommandTree.@Nullable Node<@Nullable CommandArgument> node + ); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/DelegatingSuggestionsProvider.java b/cloud-core/src/main/java/cloud/commandframework/arguments/DelegatingSuggestionsProvider.java index 5fb79de5..34369f1c 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/DelegatingSuggestionsProvider.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/DelegatingSuggestionsProvider.java @@ -49,7 +49,8 @@ final class DelegatingSuggestionsProvider implements BiFunction<@NonNull Comm @Override public String toString() { return String.format("DelegatingSuggestionsProvider{name='%s',parser='%s'}", this.argumentName, - this.parser.getClass().getCanonicalName()); + this.parser.getClass().getCanonicalName() + ); } } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/StandardCommandSyntaxFormatter.java b/cloud-core/src/main/java/cloud/commandframework/arguments/StandardCommandSyntaxFormatter.java index 15386691..8d9f5d84 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/StandardCommandSyntaxFormatter.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/StandardCommandSyntaxFormatter.java @@ -46,8 +46,10 @@ import java.util.List; public class StandardCommandSyntaxFormatter implements CommandSyntaxFormatter { @Override - public final @NonNull String apply(final @NonNull List<@NonNull CommandArgument> commandArguments, - final CommandTree.@Nullable Node<@Nullable CommandArgument> node) { + public final @NonNull String apply( + final @NonNull List<@NonNull CommandArgument> commandArguments, + final CommandTree.@Nullable Node<@Nullable CommandArgument> node + ) { final StringBuilder stringBuilder = new StringBuilder(); final Iterator> iterator = commandArguments.iterator(); while (iterator.hasNext()) { @@ -73,8 +75,9 @@ public class StandardCommandSyntaxFormatter implements CommandSyntaxFormatter if (commandArgument instanceof FlagArgument) { final StringBuilder flagBuilder = new StringBuilder(); - @SuppressWarnings("unchecked") - final Iterator> flagIterator = ((FlagArgument) commandArgument).getFlags().iterator(); + @SuppressWarnings("unchecked") final Iterator> flagIterator = ((FlagArgument) commandArgument) + .getFlags() + .iterator(); while (flagIterator.hasNext()) { final CommandFlag flag = flagIterator.next(); flagBuilder.append("--").append(flag.getName()); @@ -140,8 +143,9 @@ public class StandardCommandSyntaxFormatter implements CommandSyntaxFormatter stringBuilder.append(suffix); } else if (argument instanceof FlagArgument) { final StringBuilder flagBuilder = new StringBuilder(); - @SuppressWarnings("unchecked") - final Iterator> flagIterator = ((FlagArgument) argument).getFlags().iterator(); + @SuppressWarnings("unchecked") final Iterator> flagIterator = ((FlagArgument) argument) + .getFlags() + .iterator(); while (flagIterator.hasNext()) { final CommandFlag flag = flagIterator.next(); flagBuilder.append("--").append(flag.getName()); @@ -153,14 +157,14 @@ public class StandardCommandSyntaxFormatter implements CommandSyntaxFormatter } } stringBuilder.append(" ") - .append(prefix) - .append(flagBuilder) - .append(suffix); + .append(prefix) + .append(flagBuilder) + .append(suffix); } else { stringBuilder.append(" ") - .append(prefix) - .append(argument.getName()) - .append(suffix); + .append(prefix) + .append(argument.getName()) + .append(suffix); } tail = tail.getChildren().get(0); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/StaticArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/StaticArgument.java index e8a2e666..f2d979a1 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/StaticArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/StaticArgument.java @@ -56,8 +56,10 @@ public final class StaticArgument extends CommandArgument { * @param Command sender type * @return Constructed argument */ - public static @NonNull StaticArgument of(final @NonNull String name, - final @NonNull String... aliases) { + public static @NonNull StaticArgument of( + final @NonNull String name, + final @NonNull String... aliases + ) { return new StaticArgument<>(true, name, aliases); } @@ -104,8 +106,10 @@ public final class StaticArgument extends CommandArgument { } @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String string = inputQueue.peek(); if (string == null) { return ArgumentParseResult.failure(new NullPointerException("No input provided")); @@ -118,8 +122,10 @@ public final class StaticArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return Collections.singletonList(this.name); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentPair.java b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentPair.java index c7f4b022..c22b43e3 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentPair.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentPair.java @@ -54,13 +54,15 @@ public class ArgumentPair extends CompoundArgument, C, O> * @param mapper Mapper that maps the sub-arguments to the output type * @param valueType The output type */ - protected ArgumentPair(final boolean required, - final @NonNull String name, - final @NonNull Pair<@NonNull String, @NonNull String> names, - final @NonNull Pair<@NonNull Class, @NonNull Class> types, - final @NonNull Pair<@NonNull ArgumentParser, @NonNull ArgumentParser> parserPair, - final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper, - final @NonNull TypeToken valueType) { + protected ArgumentPair( + final boolean required, + final @NonNull String name, + final @NonNull Pair<@NonNull String, @NonNull String> names, + final @NonNull Pair<@NonNull Class, @NonNull Class> types, + final @NonNull Pair<@NonNull ArgumentParser, @NonNull ArgumentParser> parserPair, + final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper, + final @NonNull TypeToken valueType + ) { super(required, name, names, parserPair, types, mapper, o -> Pair.of((U) o[0], (V) o[1]), valueType); } @@ -78,21 +80,27 @@ public class ArgumentPair extends CompoundArgument, C, O> * @param Second parsed type * @return Intermediary builder */ - public static @NonNull ArgumentPairIntermediaryBuilder of(final @NonNull CommandManager manager, - final @NonNull String name, - final @NonNull Pair<@NonNull String, - @NonNull String> names, - final @NonNull Pair<@NonNull Class, - @NonNull Class> types) { + public static @NonNull ArgumentPairIntermediaryBuilder of( + final @NonNull CommandManager manager, + final @NonNull String name, + final @NonNull Pair<@NonNull String, + @NonNull String> names, + final @NonNull Pair<@NonNull Class, + @NonNull Class> types + ) { final ParserRegistry parserRegistry = manager.getParserRegistry(); - final ArgumentParser firstParser = parserRegistry.createParser(TypeToken.get(types.getFirst()), - ParserParameters.empty()).orElseThrow(() -> - new IllegalArgumentException( - "Could not create parser for primary type")); - final ArgumentParser secondaryParser = parserRegistry.createParser(TypeToken.get(types.getSecond()), - ParserParameters.empty()).orElseThrow(() -> - new IllegalArgumentException( - "Could not create parser for secondary type")); + final ArgumentParser firstParser = parserRegistry.createParser( + TypeToken.get(types.getFirst()), + ParserParameters.empty() + ).orElseThrow(() -> + new IllegalArgumentException( + "Could not create parser for primary type")); + final ArgumentParser secondaryParser = parserRegistry.createParser( + TypeToken.get(types.getSecond()), + ParserParameters.empty() + ).orElseThrow(() -> + new IllegalArgumentException( + "Could not create parser for secondary type")); return new ArgumentPairIntermediaryBuilder<>(true, name, names, Pair.of(firstParser, secondaryParser), types); } @@ -105,12 +113,14 @@ public class ArgumentPair extends CompoundArgument, C, O> private final Pair names; private final Pair, Class> types; - private ArgumentPairIntermediaryBuilder(final boolean required, - final @NonNull String name, - final @NonNull Pair<@NonNull String, @NonNull String> names, - final @NonNull Pair<@NonNull ArgumentParser<@NonNull C, @NonNull U>, - @NonNull ArgumentParser<@NonNull C, @NonNull V>> parserPair, - final @NonNull Pair<@NonNull Class, @NonNull Class> types) { + private ArgumentPairIntermediaryBuilder( + final boolean required, + final @NonNull String name, + final @NonNull Pair<@NonNull String, @NonNull String> names, + final @NonNull Pair<@NonNull ArgumentParser<@NonNull C, @NonNull U>, + @NonNull ArgumentParser<@NonNull C, @NonNull V>> parserPair, + final @NonNull Pair<@NonNull Class, @NonNull Class> types + ) { this.required = required; this.name = name; this.names = names; @@ -124,14 +134,16 @@ public class ArgumentPair extends CompoundArgument, C, O> * @return Argument pair */ public @NonNull ArgumentPair<@NonNull C, @NonNull U, @NonNull V, @NonNull Pair<@NonNull U, @NonNull V>> simple() { - return new ArgumentPair>(this.required, - this.name, - this.names, - this.types, - this.parserPair, - (sender, pair) -> pair, - new TypeToken>() { - }); + return new ArgumentPair>( + this.required, + this.name, + this.names, + this.types, + this.parserPair, + (sender, pair) -> pair, + new TypeToken>() { + } + ); } /** @@ -142,9 +154,11 @@ public class ArgumentPair extends CompoundArgument, C, O> * @param Output type * @return Created pair */ - public @NonNull ArgumentPair withMapper(final @NonNull TypeToken clazz, - final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, - @NonNull V>, @NonNull O> mapper) { + public @NonNull ArgumentPair withMapper( + final @NonNull TypeToken clazz, + final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, + @NonNull V>, @NonNull O> mapper + ) { return new ArgumentPair(this.required, this.name, this.names, this.types, this.parserPair, mapper, clazz); } @@ -158,7 +172,8 @@ public class ArgumentPair extends CompoundArgument, C, O> */ public @NonNull ArgumentPair<@NonNull C, @NonNull U, @NonNull V, @NonNull O> withMapper( final @NonNull Class clazz, - final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper) { + final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper + ) { return this.withMapper(TypeToken.get(clazz), mapper); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentTriplet.java b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentTriplet.java index 25b13809..fbb6909a 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentTriplet.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/ArgumentTriplet.java @@ -55,15 +55,17 @@ public class ArgumentTriplet extends CompoundArgument names, - final @NonNull Triplet<@NonNull Class, @NonNull Class, @NonNull Class> types, - final @NonNull Triplet<@NonNull ArgumentParser, @NonNull ArgumentParser, - @NonNull ArgumentParser> parserTriplet, - final @NonNull BiFunction<@NonNull C, - @NonNull Triplet, @NonNull O> mapper, - final @NonNull TypeToken valueType) { + protected ArgumentTriplet( + final boolean required, + final @NonNull String name, + final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names, + final @NonNull Triplet<@NonNull Class, @NonNull Class, @NonNull Class> types, + final @NonNull Triplet<@NonNull ArgumentParser, @NonNull ArgumentParser, + @NonNull ArgumentParser> parserTriplet, + final @NonNull BiFunction<@NonNull C, + @NonNull Triplet, @NonNull O> mapper, + final @NonNull TypeToken valueType + ) { super(required, name, names, parserTriplet, types, mapper, o -> Triplet.of((U) o[0], (V) o[1], (W) o[2]), valueType); } @@ -83,25 +85,34 @@ public class ArgumentTriplet extends CompoundArgument @NonNull ArgumentTripletIntermediaryBuilder<@NonNull C, @NonNull U, @NonNull V, @NonNull W> - of(final @NonNull CommandManager manager, - final @NonNull String name, - final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names, - final @NonNull Triplet<@NonNull Class, @NonNull Class, @NonNull Class> types) { + of( + final @NonNull CommandManager manager, + final @NonNull String name, + final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names, + final @NonNull Triplet<@NonNull Class, @NonNull Class, @NonNull Class> types + ) { final ParserRegistry parserRegistry = manager.getParserRegistry(); - final ArgumentParser firstParser = parserRegistry.createParser(TypeToken.get(types.getFirst()), - ParserParameters.empty()).orElseThrow(() -> - new IllegalArgumentException( - "Could not create parser for primary type")); - final ArgumentParser secondaryParser = parserRegistry.createParser(TypeToken.get(types.getSecond()), - ParserParameters.empty()).orElseThrow(() -> - new IllegalArgumentException( - "Could not create parser for secondary type")); - final ArgumentParser tertiaryParser = parserRegistry.createParser(TypeToken.get(types.getThird()), - ParserParameters.empty()).orElseThrow(() -> - new IllegalArgumentException( - "Could not create parser for tertiary type")); + final ArgumentParser firstParser = parserRegistry.createParser( + TypeToken.get(types.getFirst()), + ParserParameters.empty() + ).orElseThrow(() -> + new IllegalArgumentException( + "Could not create parser for primary type")); + final ArgumentParser secondaryParser = parserRegistry.createParser( + TypeToken.get(types.getSecond()), + ParserParameters.empty() + ).orElseThrow(() -> + new IllegalArgumentException( + "Could not create parser for secondary type")); + final ArgumentParser tertiaryParser = parserRegistry.createParser( + TypeToken.get(types.getThird()), + ParserParameters.empty() + ).orElseThrow(() -> + new IllegalArgumentException( + "Could not create parser for tertiary type")); return new ArgumentTripletIntermediaryBuilder<>(true, name, names, - Triplet.of(firstParser, secondaryParser, tertiaryParser), types); + Triplet.of(firstParser, secondaryParser, tertiaryParser), types + ); } @SuppressWarnings("ALL") @@ -113,15 +124,17 @@ public class ArgumentTriplet extends CompoundArgument names; private final Triplet, Class, Class> types; - private ArgumentTripletIntermediaryBuilder(final boolean required, - final @NonNull String name, - final @NonNull Triplet<@NonNull String, @NonNull String, - @NonNull String> names, - final @NonNull Triplet<@NonNull ArgumentParser, - @NonNull ArgumentParser, - @NonNull ArgumentParser> parserTriplet, - final @NonNull Triplet<@NonNull Class, - @NonNull Class, @NonNull Class> types) { + private ArgumentTripletIntermediaryBuilder( + final boolean required, + final @NonNull String name, + final @NonNull Triplet<@NonNull String, @NonNull String, + @NonNull String> names, + final @NonNull Triplet<@NonNull ArgumentParser, + @NonNull ArgumentParser, + @NonNull ArgumentParser> parserTriplet, + final @NonNull Triplet<@NonNull Class, + @NonNull Class, @NonNull Class> types + ) { this.required = required; this.name = name; this.names = names; @@ -136,14 +149,16 @@ public class ArgumentTriplet extends CompoundArgument> simple() { - return new ArgumentTriplet<>(this.required, - this.name, - this.names, - this.types, - this.parserTriplet, - (sender, triplet) -> triplet, - new TypeToken>() { - }); + return new ArgumentTriplet<>( + this.required, + this.name, + this.names, + this.types, + this.parserTriplet, + (sender, triplet) -> triplet, + new TypeToken>() { + } + ); } /** @@ -155,9 +170,11 @@ public class ArgumentTriplet extends CompoundArgument @NonNull ArgumentTriplet<@NonNull C, @NonNull U, @NonNull V, - @NonNull W, @NonNull O> withMapper(final @NonNull TypeToken clazz, - final @NonNull BiFunction<@NonNull C, @NonNull Triplet<@NonNull U, - @NonNull V, @NonNull W>, @NonNull O> mapper) { + @NonNull W, @NonNull O> withMapper( + final @NonNull TypeToken clazz, + final @NonNull BiFunction<@NonNull C, @NonNull Triplet<@NonNull U, + @NonNull V, @NonNull W>, @NonNull O> mapper + ) { return new ArgumentTriplet<>(this.required, this.name, this.names, this.types, this.parserTriplet, mapper, clazz); } @@ -169,12 +186,15 @@ public class ArgumentTriplet extends CompoundArgument Output type * @return Created triplet */ - public @NonNull ArgumentTriplet withMapper(final @NonNull Class clazz, - final @NonNull BiFunction<@NonNull C, @NonNull Triplet< - @NonNull U, @NonNull V, @NonNull W>, - @NonNull O> mapper) { + public @NonNull ArgumentTriplet withMapper( + final @NonNull Class clazz, + final @NonNull BiFunction<@NonNull C, @NonNull Triplet< + @NonNull U, @NonNull V, @NonNull W>, + @NonNull O> mapper + ) { return new ArgumentTriplet<>(this.required, this.name, this.names, this.types, - this.parserTriplet, mapper, TypeToken.get(clazz)); + this.parserTriplet, mapper, TypeToken.get(clazz) + ); } } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/CompoundArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/CompoundArgument.java index 00c76002..ded2078a 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/CompoundArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/CompoundArgument.java @@ -61,20 +61,24 @@ public class CompoundArgument extends CommandArgument mapper, - final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory, - final @NonNull TypeToken valueType) { - super(required, - name, - new CompoundParser<>(parserTuple, mapper, tupleFactory), - "", - valueType, - null); + public CompoundArgument( + final boolean required, + final @NonNull String name, + final @NonNull Tuple names, + final @NonNull Tuple parserTuple, + final @NonNull Tuple types, + final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper, + final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory, + final @NonNull TypeToken valueType + ) { + super( + required, + name, + new CompoundParser<>(parserTuple, mapper, tupleFactory), + "", + valueType, + null + ); this.parserTuple = parserTuple; this.names = names; this.types = types; @@ -114,17 +118,21 @@ public class CompoundArgument extends CommandArgument mapper; private final Function tupleFactory; - private CompoundParser(final @NonNull Tuple parserTuple, - final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper, - final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory) { + private CompoundParser( + final @NonNull Tuple parserTuple, + final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper, + final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory + ) { this.parsers = parserTuple.toArray(); this.mapper = mapper; this.tupleFactory = tupleFactory; } @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final Object[] output = new Object[this.parsers.length]; for (int i = 0; i < this.parsers.length; i++) { @SuppressWarnings("unchecked") final ArgumentParser parser = (ArgumentParser) this.parsers[i]; @@ -141,16 +149,20 @@ public class CompoundArgument extends CommandArgument suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { /* This method will be called n times, each time for each of the internal types. The problem is that we need to then know which of the parsers to forward the @@ -163,6 +175,7 @@ public class CompoundArgument extends CommandArgument) this.parsers[argument]).suggestions(commandContext, input); } + } } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/FlagArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/FlagArgument.java index 6ea4aec9..8982c117 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/compound/FlagArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/compound/FlagArgument.java @@ -66,10 +66,12 @@ public final class FlagArgument extends CommandArgument { * @param flags Flags */ public FlagArgument(final Collection> flags) { - super(false, - FLAG_ARGUMENT_NAME, - new FlagArgumentParser<>(flags.toArray(new CommandFlag[0])), - Object.class); + super( + false, + FLAG_ARGUMENT_NAME, + new FlagArgumentParser<>(flags.toArray(new CommandFlag[0])), + Object.class + ); this.flags = flags; } @@ -92,8 +94,10 @@ public final class FlagArgument extends CommandArgument { } @Override - public @NonNull ArgumentParseResult<@NonNull Object> parse(final @NonNull CommandContext<@NonNull C> commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult<@NonNull Object> parse( + final @NonNull CommandContext<@NonNull C> commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { /* This argument must necessarily be the last so we can just consume all remaining input. This argument type is similar to a greedy string in that sense. But, we need to keep all flag logic contained to the parser @@ -144,13 +148,15 @@ public final class FlagArgument extends CommandArgument { if (currentFlag == null) { return ArgumentParseResult.failure( new IllegalArgumentException(String.format("No flag started. Don't" - + " know what to do with '%s'", string))); + + " know what to do with '%s'", string))); } else { final ArgumentParseResult result = ((CommandArgument) currentFlag.getCommandArgument()) .getParser() - .parse(commandContext, - new LinkedList<>(Collections.singletonList(string))); + .parse( + commandContext, + new LinkedList<>(Collections.singletonList(string)) + ); if (result.getFailure().isPresent()) { return ArgumentParseResult.failure(result.getFailure().get()); } else { @@ -167,8 +173,10 @@ public final class FlagArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { /* Check if we have a last flag stored */ final String lastArg = commandContext.getOrDefault(FLAG_META, ""); if (lastArg.isEmpty() || !lastArg.startsWith("-")) { diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/flags/CommandFlag.java b/cloud-core/src/main/java/cloud/commandframework/arguments/flags/CommandFlag.java index 8d2e9f65..bb7ba44d 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/flags/CommandFlag.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/flags/CommandFlag.java @@ -48,10 +48,12 @@ public final class CommandFlag { private final @Nullable CommandArgument commandArgument; - private CommandFlag(final @NonNull String name, - final @NonNull String @NonNull [] aliases, - final @NonNull Description description, - final @Nullable CommandArgument commandArgument) { + private CommandFlag( + final @NonNull String name, + final @NonNull String @NonNull [] aliases, + final @NonNull Description description, + final @Nullable CommandArgument commandArgument + ) { this.name = name; this.aliases = aliases; this.description = description; @@ -135,10 +137,12 @@ public final class CommandFlag { private final Description description; private final CommandArgument commandArgument; - private Builder(final @NonNull String name, - final @NonNull String[] aliases, - final @NonNull Description description, - final @Nullable CommandArgument commandArgument) { + private Builder( + final @NonNull String name, + final @NonNull String[] aliases, + final @NonNull Description description, + final @Nullable CommandArgument commandArgument + ) { this.name = name; this.aliases = aliases; this.description = description; diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/flags/FlagContext.java b/cloud-core/src/main/java/cloud/commandframework/arguments/flags/FlagContext.java index 5731d615..ecf6d942 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/flags/FlagContext.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/flags/FlagContext.java @@ -70,8 +70,10 @@ public final class FlagContext { * @param value Flag value * @param Value type */ - public void addValueFlag(final @NonNull CommandFlag flag, - final @NonNull T value) { + public void addValueFlag( + final @NonNull CommandFlag flag, + final @NonNull T value + ) { this.flagValues.put(flag.getName(), value); } @@ -81,7 +83,7 @@ public final class FlagContext { * * @param flag Flag name * @return {@code true} if the flag is presence and the flag is a presence flag, - * else {@code false} + * else {@code false} */ public boolean isPresent(final @NonNull String flag) { final Object value = this.flagValues.get(flag); @@ -96,8 +98,10 @@ public final class FlagContext { * @param Value type * @return Stored value, or the supplied default value */ - public @Nullable T getValue(final @NonNull String name, - final @Nullable T defaultValue) { + public @Nullable T getValue( + final @NonNull String name, + final @Nullable T defaultValue + ) { final Object value = this.flagValues.get(name); if (value == null) { return defaultValue; diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParseResult.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParseResult.java index 4d639d90..c1381e48 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParseResult.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParseResult.java @@ -118,6 +118,7 @@ public abstract class ArgumentParseResult { public @NonNull Optional getFailure() { return Optional.of(this.failure); } + } } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParser.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParser.java index fb5c1375..05a13b79 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParser.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ArgumentParser.java @@ -46,8 +46,10 @@ public interface ArgumentParser { * @param inputQueue The queue of arguments * @return Parsed command result */ - @NonNull ArgumentParseResult<@NonNull T> parse(@NonNull CommandContext<@NonNull C> commandContext, - @NonNull Queue<@NonNull String> inputQueue); + @NonNull ArgumentParseResult<@NonNull T> parse( + @NonNull CommandContext<@NonNull C> commandContext, + @NonNull Queue<@NonNull String> inputQueue + ); /** * Get a list of suggested arguments that would be correctly parsed by this parser @@ -56,8 +58,10 @@ public interface ArgumentParser { * @param input Input string * @return List of suggestions */ - default @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + default @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return Collections.emptyList(); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameter.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameter.java index 093c21ed..cb866d62 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameter.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameter.java @@ -44,8 +44,10 @@ public class ParserParameter { * @param key Parameter key * @param expectedType Type that is expected to be mapped to this parameter */ - public ParserParameter(final @NonNull String key, - final @NonNull TypeToken expectedType) { + public ParserParameter( + final @NonNull String key, + final @NonNull TypeToken expectedType + ) { this.key = key; this.expectedType = expectedType; } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameters.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameters.java index 694ee555..644b61bd 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameters.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserParameters.java @@ -53,8 +53,10 @@ public final class ParserParameters { * @param Value type * @return Constructed instance */ - public static @NonNull ParserParameters single(final @NonNull ParserParameter parameter, - final @NonNull T value) { + public static @NonNull ParserParameters single( + final @NonNull ParserParameter parameter, + final @NonNull T value + ) { final ParserParameters parameters = new ParserParameters(); parameters.store(parameter, value); return parameters; @@ -78,8 +80,10 @@ public final class ParserParameters { * @param value Object * @param Parameter type */ - public void store(final @NonNull ParserParameter parameter, - final @NonNull T value) { + public void store( + final @NonNull ParserParameter parameter, + final @NonNull T value + ) { this.internalMap.put(parameter, value); } @@ -92,8 +96,10 @@ public final class ParserParameters { * @return Parameter value */ @SuppressWarnings("unchecked") - public @NonNull T get(final @NonNull ParserParameter parameter, - final @NonNull T defaultValue) { + public @NonNull T get( + final @NonNull ParserParameter parameter, + final @NonNull T defaultValue + ) { return (T) this.internalMap.getOrDefault(parameter, defaultValue); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserRegistry.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserRegistry.java index 8354be34..74edfc69 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserRegistry.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/ParserRegistry.java @@ -49,8 +49,10 @@ public interface ParserRegistry { * to configure the parser, many of which are documented in {@link StandardParameters} * @param Generic type specifying what is produced by the parser */ - void registerParserSupplier(@NonNull TypeToken type, - @NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser> supplier); + void registerParserSupplier( + @NonNull TypeToken type, + @NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser> supplier + ); /** * Register a named parser supplier @@ -59,8 +61,10 @@ public interface ParserRegistry { * @param supplier The function that generates the parser. The map supplied my contain parameters used * to configure the parser, many of which are documented in {@link StandardParameters} */ - void registerNamedParserSupplier(@NonNull String name, - @NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser> supplier); + void registerNamedParserSupplier( + @NonNull String name, + @NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser> supplier + ); /** * Register a mapper that maps annotation instances to a map of parameter-object pairs @@ -71,9 +75,11 @@ public interface ParserRegistry { * @param Annotation type * @param Type of the object that the parser is retrieved for */ - void registerAnnotationMapper(@NonNull Class annotation, - @NonNull BiFunction<@NonNull A, @NonNull TypeToken, - @NonNull ParserParameters> mapper); + void registerAnnotationMapper( + @NonNull Class annotation, + @NonNull BiFunction<@NonNull A, @NonNull TypeToken, + @NonNull ParserParameters> mapper + ); /** * Parse annotations into {@link ParserParameters} @@ -82,8 +88,10 @@ public interface ParserRegistry { * @param annotations The annotations to be parsed * @return Parsed parameters */ - @NonNull ParserParameters parseAnnotations(@NonNull TypeToken parsingType, - @NonNull Collection annotations); + @NonNull ParserParameters parseAnnotations( + @NonNull TypeToken parsingType, + @NonNull Collection annotations + ); /** * Attempt to create a {@link ArgumentParser} for a specified type, using @@ -94,8 +102,10 @@ public interface ParserRegistry { * @param Generic type * @return Parser, if one can be created */ - @NonNull Optional> createParser(@NonNull TypeToken type, - @NonNull ParserParameters parserParameters); + @NonNull Optional> createParser( + @NonNull TypeToken type, + @NonNull ParserParameters parserParameters + ); /** * Attempt to create a {@link ArgumentParser} for a specified type, using @@ -106,7 +116,9 @@ public interface ParserRegistry { * @param Generic type * @return Parser, if one can be created */ - @NonNull Optional> createParser(@NonNull String name, - @NonNull ParserParameters parserParameters); + @NonNull Optional> createParser( + @NonNull String name, + @NonNull ParserParameters parserParameters + ); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParameters.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParameters.java index 4e365086..f288ee3a 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParameters.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParameters.java @@ -63,8 +63,10 @@ public final class StandardParameters { private StandardParameters() { } - private static @NonNull ParserParameter create(final @NonNull String key, - final @NonNull TypeToken expectedType) { + private static @NonNull ParserParameter create( + final @NonNull String key, + final @NonNull TypeToken expectedType + ) { return new ParserParameter<>(key, expectedType); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParserRegistry.java b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParserRegistry.java index 98c53c30..bdbd171c 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParserRegistry.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/parser/StandardParserRegistry.java @@ -23,9 +23,8 @@ // package cloud.commandframework.arguments.parser; -import cloud.commandframework.annotations.specifier.Greedy; -import cloud.commandframework.arguments.standard.UUIDArgument; import cloud.commandframework.annotations.specifier.Completions; +import cloud.commandframework.annotations.specifier.Greedy; import cloud.commandframework.annotations.specifier.Range; import cloud.commandframework.arguments.standard.BooleanArgument; import cloud.commandframework.arguments.standard.ByteArgument; @@ -36,6 +35,7 @@ import cloud.commandframework.arguments.standard.FloatArgument; import cloud.commandframework.arguments.standard.IntegerArgument; import cloud.commandframework.arguments.standard.ShortArgument; import cloud.commandframework.arguments.standard.StringArgument; +import cloud.commandframework.arguments.standard.UUIDArgument; import io.leangen.geantyref.GenericTypeReflector; import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; @@ -86,60 +86,83 @@ public final class StandardParserRegistry implements ParserRegistry { /* Register standard types */ this.registerParserSupplier(TypeToken.get(Byte.class), options -> - new ByteArgument.ByteParser((byte) options.get(StandardParameters.RANGE_MIN, Byte.MIN_VALUE), - (byte) options.get(StandardParameters.RANGE_MAX, Byte.MAX_VALUE))); + new ByteArgument.ByteParser( + (byte) options.get(StandardParameters.RANGE_MIN, Byte.MIN_VALUE), + (byte) options.get(StandardParameters.RANGE_MAX, Byte.MAX_VALUE) + )); this.registerParserSupplier(TypeToken.get(Short.class), options -> - new ShortArgument.ShortParser((short) options.get(StandardParameters.RANGE_MIN, Short.MIN_VALUE), - (short) options.get(StandardParameters.RANGE_MAX, Short.MAX_VALUE))); + new ShortArgument.ShortParser( + (short) options.get(StandardParameters.RANGE_MIN, Short.MIN_VALUE), + (short) options.get(StandardParameters.RANGE_MAX, Short.MAX_VALUE) + )); this.registerParserSupplier(TypeToken.get(Integer.class), options -> - new IntegerArgument.IntegerParser((int) options.get(StandardParameters.RANGE_MIN, Integer.MIN_VALUE), - (int) options.get(StandardParameters.RANGE_MAX, Integer.MAX_VALUE))); + new IntegerArgument.IntegerParser( + (int) options.get(StandardParameters.RANGE_MIN, Integer.MIN_VALUE), + (int) options.get(StandardParameters.RANGE_MAX, Integer.MAX_VALUE) + )); this.registerParserSupplier(TypeToken.get(Float.class), options -> - new FloatArgument.FloatParser((float) options.get(StandardParameters.RANGE_MIN, Float.MIN_VALUE), - (float) options.get(StandardParameters.RANGE_MAX, Float.MAX_VALUE))); + new FloatArgument.FloatParser( + (float) options.get(StandardParameters.RANGE_MIN, Float.MIN_VALUE), + (float) options.get(StandardParameters.RANGE_MAX, Float.MAX_VALUE) + )); this.registerParserSupplier(TypeToken.get(Double.class), options -> - new DoubleArgument.DoubleParser((double) options.get(StandardParameters.RANGE_MIN, Double.MIN_VALUE), - (double) options.get(StandardParameters.RANGE_MAX, Double.MAX_VALUE))); + new DoubleArgument.DoubleParser( + (double) options.get(StandardParameters.RANGE_MIN, Double.MIN_VALUE), + (double) options.get(StandardParameters.RANGE_MAX, Double.MAX_VALUE) + )); this.registerParserSupplier(TypeToken.get(Character.class), options -> new CharArgument.CharacterParser()); /* Make this one less awful */ this.registerParserSupplier(TypeToken.get(String.class), options -> { final boolean greedy = options.get(StandardParameters.GREEDY, false); final StringArgument.StringMode stringMode = greedy - ? StringArgument.StringMode.GREEDY - : StringArgument.StringMode.SINGLE; + ? StringArgument.StringMode.GREEDY + : StringArgument.StringMode.SINGLE; return new StringArgument.StringParser( stringMode, - (context, s) -> Arrays.asList(options.get(StandardParameters.COMPLETIONS, new String[0]))); + (context, s) -> Arrays.asList(options.get(StandardParameters.COMPLETIONS, new String[0])) + ); }); /* Add options to this */ this.registerParserSupplier(TypeToken.get(Boolean.class), options -> new BooleanArgument.BooleanParser<>(false)); this.registerParserSupplier(TypeToken.get(UUID.class), options -> new UUIDArgument.UUIDParser<>()); } + private static boolean isPrimitive(final @NonNull TypeToken type) { + return GenericTypeReflector.erase(type.getType()).isPrimitive(); + } + @Override - public void registerParserSupplier(final @NonNull TypeToken type, - final @NonNull Function<@NonNull ParserParameters, - @NonNull ArgumentParser> supplier) { + public void registerParserSupplier( + final @NonNull TypeToken type, + final @NonNull Function<@NonNull ParserParameters, + @NonNull ArgumentParser> supplier + ) { this.parserSuppliers.put(type, supplier); } @Override - public void registerNamedParserSupplier(final @NonNull String name, - final @NonNull Function<@NonNull ParserParameters, - @NonNull ArgumentParser> supplier) { + public void registerNamedParserSupplier( + final @NonNull String name, + final @NonNull Function<@NonNull ParserParameters, + @NonNull ArgumentParser> supplier + ) { this.namedParsers.put(name, supplier); } @Override - public void registerAnnotationMapper(final @NonNull Class annotation, - final @NonNull BiFunction<@NonNull A, @NonNull TypeToken, - @NonNull ParserParameters> mapper) { + public void registerAnnotationMapper( + final @NonNull Class annotation, + final @NonNull BiFunction<@NonNull A, @NonNull TypeToken, + @NonNull ParserParameters> mapper + ) { this.annotationMappers.put(annotation, mapper); } @Override - public @NonNull ParserParameters parseAnnotations(final @NonNull TypeToken parsingType, - final @NonNull Collection<@NonNull ? extends Annotation> annotations) { + public @NonNull ParserParameters parseAnnotations( + final @NonNull TypeToken parsingType, + final @NonNull Collection<@NonNull ? extends Annotation> annotations + ) { final ParserParameters parserParameters = new ParserParameters(); annotations.forEach(annotation -> { // noinspection all @@ -155,8 +178,10 @@ public final class StandardParserRegistry implements ParserRegistry { } @Override - public @NonNull Optional> createParser(final @NonNull TypeToken type, - final @NonNull ParserParameters parserParameters) { + public @NonNull Optional> createParser( + final @NonNull TypeToken type, + final @NonNull ParserParameters parserParameters + ) { final TypeToken actualType; if (GenericTypeReflector.erase(type.getType()).isPrimitive()) { actualType = TypeToken.get(PRIMITIVE_MAPPINGS.get(GenericTypeReflector.erase(type.getType()))); @@ -180,8 +205,10 @@ public final class StandardParserRegistry implements ParserRegistry { } @Override - public @NonNull Optional> createParser(final @NonNull String name, - final @NonNull ParserParameters parserParameters) { + public @NonNull Optional> createParser( + final @NonNull String name, + final @NonNull ParserParameters parserParameters + ) { final Function> producer = this.namedParsers.get(name); if (producer == null) { return Optional.empty(); @@ -191,12 +218,6 @@ public final class StandardParserRegistry implements ParserRegistry { return Optional.of(parser); } - - private static boolean isPrimitive(final @NonNull TypeToken type) { - return GenericTypeReflector.erase(type.getType()).isPrimitive(); - } - - private static final class RangeMapper implements BiFunction<@NonNull Range, @NonNull TypeToken, @NonNull ParserParameters> { diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/BooleanArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/BooleanArgument.java index a9dadf88..95596d4a 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/BooleanArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/BooleanArgument.java @@ -37,14 +37,17 @@ import java.util.function.BiFunction; @SuppressWarnings("unused") public final class BooleanArgument extends CommandArgument { + private final boolean liberal; - private BooleanArgument(final boolean required, - final @NonNull String name, - final boolean liberal, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private BooleanArgument( + final boolean required, + final @NonNull String name, + final boolean liberal, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new BooleanParser<>(liberal), defaultValue, Boolean.class, suggestionsProvider); this.liberal = liberal; } @@ -90,8 +93,10 @@ public final class BooleanArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final boolean defaultBoolean) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final boolean defaultBoolean + ) { return BooleanArgument.newBuilder(name).asOptionalWithDefault(Boolean.toString(defaultBoolean)).build(); } @@ -131,7 +136,8 @@ public final class BooleanArgument extends CommandArgument { @Override public @NonNull BooleanArgument build() { return new BooleanArgument<>(this.isRequired(), this.getName(), this.liberal, - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -154,8 +160,10 @@ public final class BooleanArgument extends CommandArgument { } @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -188,8 +196,10 @@ public final class BooleanArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { if (!liberal) { return Arrays.asList("TRUE", "FALSE"); } @@ -201,6 +211,7 @@ public final class BooleanArgument extends CommandArgument { public boolean isContextFree() { return true; } + } @@ -218,8 +229,10 @@ public final class BooleanArgument extends CommandArgument { * @param input String input * @param liberal Liberal value */ - public BooleanParseException(final @NonNull String input, - final boolean liberal) { + public BooleanParseException( + final @NonNull String input, + final boolean liberal + ) { this.input = input; this.liberal = liberal; } @@ -246,5 +259,7 @@ public final class BooleanArgument extends CommandArgument { public String getMessage() { return String.format("Could not parse boolean from '%s'.", input); } + } + } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ByteArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ByteArgument.java index ebbfc0ae..1104abbf 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ByteArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ByteArgument.java @@ -41,13 +41,15 @@ public final class ByteArgument extends CommandArgument { private final byte min; private final byte max; - private ByteArgument(final boolean required, - final @NonNull String name, - final byte min, - final byte max, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private ByteArgument( + final boolean required, + final @NonNull String name, + final byte min, + final byte max, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new ByteParser<>(min, max), defaultValue, Byte.class, suggestionsProvider); this.min = min; this.max = max; @@ -94,8 +96,10 @@ public final class ByteArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final byte defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final byte defaultNum + ) { return ByteArgument.newBuilder(name).asOptionalWithDefault(Byte.toString(defaultNum)).build(); } @@ -156,7 +160,8 @@ public final class ByteArgument extends CommandArgument { @Override public @NonNull ByteArgument build() { return new ByteArgument<>(this.isRequired(), this.getName(), this.min, this.max, - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -180,7 +185,8 @@ public final class ByteArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -189,16 +195,19 @@ public final class ByteArgument extends CommandArgument { final byte value = Byte.parseByte(input); if (value < this.min || value > this.max) { return ArgumentParseResult.failure( - new ByteParseException(input, - this.min, - this.max)); + new ByteParseException( + input, + this.min, + this.max + )); } inputQueue.remove(); return ArgumentParseResult.success(value); } catch (final Exception e) { return ArgumentParseResult.failure( new ByteParseException(input, this.min, - this.max)); + this.max + )); } } @@ -208,8 +217,10 @@ public final class ByteArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/CharArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/CharArgument.java index 00815097..d2df467f 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/CharArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/CharArgument.java @@ -37,11 +37,13 @@ import java.util.function.BiFunction; @SuppressWarnings("unused") public final class CharArgument extends CommandArgument { - private CharArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, - @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { + private CharArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, + @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new CharacterParser<>(), defaultValue, Character.class, suggestionsProvider); } @@ -86,8 +88,10 @@ public final class CharArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultNum + ) { return CharArgument.newBuilder(name).asOptionalWithDefault(defaultNum).build(); } @@ -106,7 +110,8 @@ public final class CharArgument extends CommandArgument { @Override public @NonNull CharArgument build() { return new CharArgument<>(this.isRequired(), this.getName(), - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -115,8 +120,10 @@ public final class CharArgument extends CommandArgument { public static final class CharacterParser implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -166,5 +173,7 @@ public final class CharArgument extends CommandArgument { public String getMessage() { return String.format("'%s' is not a valid character.", input); } + } + } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/DoubleArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/DoubleArgument.java index 2207cc60..5b73b2ee 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/DoubleArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/DoubleArgument.java @@ -41,13 +41,15 @@ public final class DoubleArgument extends CommandArgument { private final double min; private final double max; - private DoubleArgument(final boolean required, - final @NonNull String name, - final double min, - final double max, - final String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private DoubleArgument( + final boolean required, + final @NonNull String name, + final double min, + final double max, + final String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new DoubleParser<>(min, max), defaultValue, Double.class, suggestionsProvider); this.min = min; this.max = max; @@ -94,8 +96,10 @@ public final class DoubleArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final double defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final double defaultNum + ) { return DoubleArgument.newBuilder(name).asOptionalWithDefault(Double.toString(defaultNum)).build(); } @@ -156,7 +160,8 @@ public final class DoubleArgument extends CommandArgument { @Override public @NonNull DoubleArgument build() { return new DoubleArgument<>(this.isRequired(), this.getName(), this.min, this.max, - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -180,7 +185,8 @@ public final class DoubleArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/EnumArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/EnumArgument.java index 20671e54..c974b9da 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/EnumArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/EnumArgument.java @@ -45,12 +45,14 @@ import java.util.stream.Collectors; @SuppressWarnings("unused") public class EnumArgument> extends CommandArgument { - protected EnumArgument(final @NonNull Class enumClass, - final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + protected EnumArgument( + final @NonNull Class enumClass, + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new EnumParser<>(enumClass), defaultValue, enumClass, suggestionsProvider); } @@ -64,8 +66,9 @@ public class EnumArgument> extends CommandArgument { * @return Created builder */ public static > EnumArgument.@NonNull Builder newBuilder( - @NonNull final Class enumClass, - final @NonNull String name) { + @NonNull final Class enumClass, + final @NonNull String name + ) { return new EnumArgument.Builder<>(name, enumClass); } @@ -80,7 +83,8 @@ public class EnumArgument> extends CommandArgument { */ public static > @NonNull CommandArgument of( final @NonNull Class enumClass, - final @NonNull String name) { + final @NonNull String name + ) { return EnumArgument.newBuilder(enumClass, name).asRequired().build(); } @@ -95,7 +99,8 @@ public class EnumArgument> extends CommandArgument { */ public static > @NonNull CommandArgument optional( final @NonNull Class enumClass, - final @NonNull String name) { + final @NonNull String name + ) { return EnumArgument.newBuilder(enumClass, name).asOptional().build(); } @@ -112,7 +117,8 @@ public class EnumArgument> extends CommandArgument { public static > @NonNull CommandArgument optional( final @NonNull Class enumClass, final @NonNull String name, - final @NonNull E defaultValue) { + final @NonNull E defaultValue + ) { return EnumArgument.newBuilder(enumClass, name).asOptionalWithDefault(defaultValue.name().toLowerCase()).build(); } @@ -129,8 +135,10 @@ public class EnumArgument> extends CommandArgument { @Override public @NonNull CommandArgument build() { return new EnumArgument<>(this.enumClass, this.isRequired(), this.getName(), - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } + } @@ -150,8 +158,10 @@ public class EnumArgument> extends CommandArgument { } @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -168,8 +178,10 @@ public class EnumArgument> extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return EnumSet.allOf(this.enumClass).stream().map(e -> e.name().toLowerCase()).collect(Collectors.toList()); } @@ -177,6 +189,7 @@ public class EnumArgument> extends CommandArgument { public boolean isContextFree() { return true; } + } @@ -191,8 +204,10 @@ public class EnumArgument> extends CommandArgument { * @param input Input * @param enumClass Enum class */ - public EnumParseException(final @NonNull String input, - final @NonNull Class> enumClass) { + public EnumParseException( + final @NonNull String input, + final @NonNull Class> enumClass + ) { this.input = input; this.enumClass = enumClass; } @@ -201,8 +216,8 @@ public class EnumArgument> extends CommandArgument { private static @NonNull String join(final @NonNull Class clazz) { final EnumSet enumSet = EnumSet.allOf(clazz); return enumSet.stream() - .map(e -> e.toString().toLowerCase()) - .collect(Collectors.joining(", ")); + .map(e -> e.toString().toLowerCase()) + .collect(Collectors.joining(", ")); } /** diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/FloatArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/FloatArgument.java index 296f5c74..1d039b2f 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/FloatArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/FloatArgument.java @@ -41,13 +41,15 @@ public final class FloatArgument extends CommandArgument { private final float min; private final float max; - private FloatArgument(final boolean required, - final @NonNull String name, - final float min, - final float max, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, - @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { + private FloatArgument( + final boolean required, + final @NonNull String name, + final float min, + final float max, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, + @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new FloatParser<>(min, max), defaultValue, Float.class, suggestionsProvider); this.min = min; this.max = max; @@ -94,8 +96,10 @@ public final class FloatArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final float defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final float defaultNum + ) { return FloatArgument.newBuilder(name).asOptionalWithDefault(Float.toString(defaultNum)).build(); } @@ -156,7 +160,8 @@ public final class FloatArgument extends CommandArgument { @Override public @NonNull FloatArgument build() { return new FloatArgument<>(this.isRequired(), this.getName(), this.min, this.max, - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -180,7 +185,8 @@ public final class FloatArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue inputQueue) { + final @NonNull Queue inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/IntegerArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/IntegerArgument.java index 0e21f0fc..615383c5 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/IntegerArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/IntegerArgument.java @@ -48,13 +48,15 @@ public final class IntegerArgument extends CommandArgument { private final int min; private final int max; - private IntegerArgument(final boolean required, - final @NonNull String name, - final int min, - final int max, - final String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private IntegerArgument( + final boolean required, + final @NonNull String name, + final int min, + final int max, + final String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new IntegerParser<>(min, max), defaultValue, Integer.class, suggestionsProvider); this.min = min; this.max = max; @@ -101,8 +103,10 @@ public final class IntegerArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final int defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final int defaultNum + ) { return IntegerArgument.newBuilder(name).asOptionalWithDefault(Integer.toString(defaultNum)).build(); } @@ -163,7 +167,8 @@ public final class IntegerArgument extends CommandArgument { @Override public @NonNull IntegerArgument build() { return new IntegerArgument<>(this.isRequired(), this.getName(), this.min, this.max, - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -209,7 +214,8 @@ public final class IntegerArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -250,8 +256,10 @@ public final class IntegerArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return getSuggestions(this.min, this.max, input); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/LongArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/LongArgument.java index 3763ec5c..30831588 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/LongArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/LongArgument.java @@ -41,13 +41,15 @@ public final class LongArgument extends CommandArgument { private final long min; private final long max; - private LongArgument(final boolean required, - final @NonNull String name, - final long min, - final long max, - final String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private LongArgument( + final boolean required, + final @NonNull String name, + final long min, + final long max, + final String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new LongParser<>(min, max), defaultValue, Long.class, suggestionsProvider); this.min = min; this.max = max; @@ -94,8 +96,10 @@ public final class LongArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final long defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final long defaultNum + ) { return LongArgument.newBuilder(name).asOptionalWithDefault(Long.toString(defaultNum)).build(); } @@ -156,7 +160,8 @@ public final class LongArgument extends CommandArgument { @Override public @NonNull LongArgument build() { return new LongArgument<>(this.isRequired(), this.getName(), this.min, - this.max, this.getDefaultValue(), this.getSuggestionsProvider()); + this.max, this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -174,7 +179,8 @@ public final class LongArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -197,8 +203,10 @@ public final class LongArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ShortArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ShortArgument.java index 657bbe3f..238c7973 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ShortArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/ShortArgument.java @@ -41,13 +41,15 @@ public final class ShortArgument extends CommandArgument { private final short min; private final short max; - private ShortArgument(final boolean required, - final @NonNull String name, - final short min, - final short max, - final String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List> suggestionsProvider) { + private ShortArgument( + final boolean required, + final @NonNull String name, + final short min, + final short max, + final String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List> suggestionsProvider + ) { super(required, name, new ShortParser<>(min, max), defaultValue, Short.class, suggestionsProvider); this.min = min; this.max = max; @@ -94,8 +96,10 @@ public final class ShortArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final short defaultNum) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final short defaultNum + ) { return ShortArgument.newBuilder(name).asOptionalWithDefault(Short.toString(defaultNum)).build(); } @@ -156,7 +160,8 @@ public final class ShortArgument extends CommandArgument { @Override public @NonNull ShortArgument build() { return new ShortArgument<>(this.isRequired(), this.getName(), this.min, this.max, - this.getDefaultValue(), this.getSuggestionsProvider()); + this.getDefaultValue(), this.getSuggestionsProvider() + ); } } @@ -180,7 +185,8 @@ public final class ShortArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -203,8 +209,10 @@ public final class ShortArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input); } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/StringArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/StringArgument.java index b3568847..b1a3a5b1 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/StringArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/StringArgument.java @@ -40,14 +40,17 @@ public final class StringArgument extends CommandArgument { private final StringMode stringMode; - private StringArgument(final boolean required, - final @NonNull String name, - final @NonNull StringMode stringMode, - final @NonNull String defaultValue, - final @NonNull BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private StringArgument( + final boolean required, + final @NonNull String name, + final @NonNull StringMode stringMode, + final @NonNull String defaultValue, + final @NonNull BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new StringParser<>(stringMode, suggestionsProvider), - defaultValue, String.class, suggestionsProvider); + defaultValue, String.class, suggestionsProvider + ); this.stringMode = stringMode; } @@ -81,8 +84,10 @@ public final class StringArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument of(final @NonNull String name, - final @NonNull StringMode stringMode) { + public static @NonNull CommandArgument of( + final @NonNull String name, + final @NonNull StringMode stringMode + ) { return StringArgument.newBuilder(name).withMode(stringMode).asRequired().build(); } @@ -105,8 +110,10 @@ public final class StringArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull StringMode stringMode) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull StringMode stringMode + ) { return StringArgument.newBuilder(name).withMode(stringMode).asOptional().build(); } @@ -118,8 +125,10 @@ public final class StringArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultString) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultString + ) { return StringArgument.newBuilder(name).asOptionalWithDefault(defaultString).build(); } @@ -190,8 +199,10 @@ public final class StringArgument extends CommandArgument { * @param suggestionsProvider Suggestions provider * @return Builder instance */ - public @NonNull Builder withSuggestionsProvider(final @NonNull BiFunction<@NonNull CommandContext, - @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { + public @NonNull Builder withSuggestionsProvider( + final @NonNull BiFunction<@NonNull CommandContext, + @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider + ) { this.suggestionsProvider = suggestionsProvider; return this; } @@ -204,7 +215,8 @@ public final class StringArgument extends CommandArgument { @Override public @NonNull StringArgument build() { return new StringArgument<>(this.isRequired(), this.getName(), this.stringMode, - this.getDefaultValue(), this.suggestionsProvider); + this.getDefaultValue(), this.suggestionsProvider + ); } } @@ -221,16 +233,20 @@ public final class StringArgument extends CommandArgument { * @param stringMode String parsing mode * @param suggestionsProvider Suggestions provider */ - public StringParser(final @NonNull StringMode stringMode, - final @NonNull BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + public StringParser( + final @NonNull StringMode stringMode, + final @NonNull BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { this.stringMode = stringMode; this.suggestionsProvider = suggestionsProvider; } @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -294,8 +310,10 @@ public final class StringArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { return this.suggestionsProvider.apply(commandContext, input); } @@ -312,6 +330,7 @@ public final class StringArgument extends CommandArgument { public @NonNull StringMode getStringMode() { return this.stringMode; } + } diff --git a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/UUIDArgument.java b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/UUIDArgument.java index 2504adf6..ccc975cb 100644 --- a/cloud-core/src/main/java/cloud/commandframework/arguments/standard/UUIDArgument.java +++ b/cloud-core/src/main/java/cloud/commandframework/arguments/standard/UUIDArgument.java @@ -38,11 +38,13 @@ import java.util.function.BiFunction; @SuppressWarnings("unused") public final class UUIDArgument extends CommandArgument { - private UUIDArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, - @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { + private UUIDArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, + @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new UUIDParser<>(), defaultValue, UUID.class, suggestionsProvider); } @@ -87,8 +89,10 @@ public final class UUIDArgument extends CommandArgument { * @param Command sender type * @return Created component */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull UUID defaultUUID) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull UUID defaultUUID + ) { return UUIDArgument.newBuilder(name).asOptionalWithDefault(defaultUUID.toString()).build(); } @@ -117,7 +121,8 @@ public final class UUIDArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -136,6 +141,7 @@ public final class UUIDArgument extends CommandArgument { public boolean isContextFree() { return true; } + } @@ -156,5 +162,7 @@ public final class UUIDArgument extends CommandArgument { public String getMessage() { return String.format("Could not parse UUID from '%s'.", input); } + } + } diff --git a/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java b/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java index df72b0c2..5af60e73 100644 --- a/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java +++ b/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java @@ -61,8 +61,10 @@ public final class CommandContext { * @param suggestions Whether or not the context is created for command suggestions * @param commandSender Sender of the command */ - public CommandContext(final boolean suggestions, - final @NonNull C commandSender) { + public CommandContext( + final boolean suggestions, + final @NonNull C commandSender + ) { this.commandSender = commandSender; this.suggestions = suggestions; } @@ -181,8 +183,10 @@ public final class CommandContext { * @param Argument type * @return Stored value, or supplied default value */ - public @Nullable T getOrDefault(final @NonNull CommandArgument argument, - final @Nullable T defaultValue) { + public @Nullable T getOrDefault( + final @NonNull CommandArgument argument, + final @Nullable T defaultValue + ) { return this.getOptional(argument.getName()).orElse(defaultValue); } @@ -194,8 +198,10 @@ public final class CommandContext { * @param Argument type * @return Argument, or supplied default value */ - public @Nullable T getOrDefault(final @NonNull String key, - final @Nullable T defaultValue) { + public @Nullable T getOrDefault( + final @NonNull String key, + final @Nullable T defaultValue + ) { return this.getOptional(key).orElse(defaultValue); } diff --git a/cloud-core/src/main/java/cloud/commandframework/context/CommandContextFactory.java b/cloud-core/src/main/java/cloud/commandframework/context/CommandContextFactory.java index c51b8bae..0b9dadb5 100644 --- a/cloud-core/src/main/java/cloud/commandframework/context/CommandContextFactory.java +++ b/cloud-core/src/main/java/cloud/commandframework/context/CommandContextFactory.java @@ -36,7 +36,7 @@ public interface CommandContextFactory { * Create a new command context * * @param suggestions Whether or not the sender is requesting suggestions - * @param sender Command sender + * @param sender Command sender * @return Command context */ @NonNull CommandContext create(boolean suggestions, @NonNull C sender); diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/AmbiguousNodeException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/AmbiguousNodeException.java index 3903232a..99a67faa 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/AmbiguousNodeException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/AmbiguousNodeException.java @@ -51,9 +51,11 @@ public final class AmbiguousNodeException extends IllegalStateException { * @param ambiguousNode Node that caused exception * @param children All children of the parent */ - public AmbiguousNodeException(final @Nullable CommandArgument parentNode, - final @NonNull CommandArgument ambiguousNode, - final @NonNull List<@NonNull CommandArgument> children) { + public AmbiguousNodeException( + final @Nullable CommandArgument parentNode, + final @NonNull CommandArgument ambiguousNode, + final @NonNull List<@NonNull CommandArgument> children + ) { this.parentNode = parentNode; this.ambiguousNode = ambiguousNode; this.children = children; @@ -101,7 +103,7 @@ public final class AmbiguousNodeException extends IllegalStateException { } } return stringBuilder.append(")") - .toString(); + .toString(); } } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/ArgumentParseException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/ArgumentParseException.java index 15541aaa..34dec779 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/ArgumentParseException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/ArgumentParseException.java @@ -39,9 +39,11 @@ public class ArgumentParseException extends CommandParseException { * @param commandSender Command sender * @param currentChain Chain leading up to the exception */ - public ArgumentParseException(final @NonNull Throwable throwable, - final @NonNull Object commandSender, - final @NonNull List<@NonNull CommandArgument> currentChain) { + public ArgumentParseException( + final @NonNull Throwable throwable, + final @NonNull Object commandSender, + final @NonNull List<@NonNull CommandArgument> currentChain + ) { super(commandSender, currentChain); this.cause = throwable; } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/CommandParseException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/CommandParseException.java index b217de10..d1a0a16e 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/CommandParseException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/CommandParseException.java @@ -44,8 +44,10 @@ public class CommandParseException extends IllegalArgumentException { * @param commandSender Sender who executed the command * @param currentChain Chain leading up to the exception */ - protected CommandParseException(final @NonNull Object commandSender, - final @NonNull List> currentChain) { + protected CommandParseException( + final @NonNull Object commandSender, + final @NonNull List> currentChain + ) { this.commandSender = commandSender; this.currentChain = currentChain; } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidCommandSenderException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidCommandSenderException.java index 3a60534d..7e2c0ef1 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidCommandSenderException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidCommandSenderException.java @@ -42,9 +42,11 @@ public final class InvalidCommandSenderException extends CommandParseException { * @param requiredSender The sender type that is required * @param currentChain Chain leading up to the exception */ - public InvalidCommandSenderException(final @NonNull Object commandSender, - final @NonNull Class requiredSender, - final @NonNull List<@NonNull CommandArgument> currentChain) { + public InvalidCommandSenderException( + final @NonNull Object commandSender, + final @NonNull Class requiredSender, + final @NonNull List<@NonNull CommandArgument> currentChain + ) { super(commandSender, currentChain); this.requiredSender = requiredSender; } @@ -60,8 +62,11 @@ public final class InvalidCommandSenderException extends CommandParseException { @Override public String getMessage() { - return String.format("%s is not allowed to execute that command. Must be of type %s", - getCommandSender().getClass().getSimpleName(), - requiredSender.getSimpleName()); + return String.format( + "%s is not allowed to execute that command. Must be of type %s", + getCommandSender().getClass().getSimpleName(), + requiredSender.getSimpleName() + ); } + } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidSyntaxException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidSyntaxException.java index 3021054d..679e473b 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidSyntaxException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/InvalidSyntaxException.java @@ -43,9 +43,11 @@ public class InvalidSyntaxException extends CommandParseException { * @param commandSender Sender that sent the command * @param currentChain Chain leading up to issue */ - public InvalidSyntaxException(final @NonNull String correctSyntax, - final @NonNull Object commandSender, - final @NonNull List<@NonNull CommandArgument> currentChain) { + public InvalidSyntaxException( + final @NonNull String correctSyntax, + final @NonNull Object commandSender, + final @NonNull List<@NonNull CommandArgument> currentChain + ) { super(commandSender, currentChain); this.correctSyntax = correctSyntax; } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/NoPermissionException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/NoPermissionException.java index a2497355..dcaf8edf 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/NoPermissionException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/NoPermissionException.java @@ -46,9 +46,11 @@ public class NoPermissionException extends CommandParseException { * @param commandSender Command sender * @param currentChain Chain leading up to the exception */ - public NoPermissionException(final @NonNull CommandPermission missingPermission, - final @NonNull Object commandSender, - final @NonNull List<@NonNull CommandArgument> currentChain) { + public NoPermissionException( + final @NonNull CommandPermission missingPermission, + final @NonNull Object commandSender, + final @NonNull List<@NonNull CommandArgument> currentChain + ) { super(commandSender, currentChain); this.missingPermission = missingPermission; } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/NoSuchCommandException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/NoSuchCommandException.java index 2f28a5dc..158f014c 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/NoSuchCommandException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/NoSuchCommandException.java @@ -44,9 +44,11 @@ public final class NoSuchCommandException extends CommandParseException { * @param currentChain Chain leading up to the exception * @param command Entered command (following the command chain) */ - public NoSuchCommandException(final @NonNull Object commandSender, - final @NonNull List> currentChain, - final @NonNull String command) { + public NoSuchCommandException( + final @NonNull Object commandSender, + final @NonNull List> currentChain, + final @NonNull String command + ) { super(commandSender, currentChain); this.suppliedCommand = command; } diff --git a/cloud-core/src/main/java/cloud/commandframework/exceptions/parsing/NumberParseException.java b/cloud-core/src/main/java/cloud/commandframework/exceptions/parsing/NumberParseException.java index 249bdbda..24412e2f 100644 --- a/cloud-core/src/main/java/cloud/commandframework/exceptions/parsing/NumberParseException.java +++ b/cloud-core/src/main/java/cloud/commandframework/exceptions/parsing/NumberParseException.java @@ -38,9 +38,11 @@ public abstract class NumberParseException extends IllegalArgumentException { * @param min Maximum value * @param max Minimum value */ - public NumberParseException(final @NonNull String input, - final @NonNull Number min, - final @NonNull Number max) { + public NumberParseException( + final @NonNull String input, + final @NonNull Number min, + final @NonNull Number max + ) { this.input = input; this.min = min; this.max = max; diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/AsynchronousCommandExecutionCoordinator.java b/cloud-core/src/main/java/cloud/commandframework/execution/AsynchronousCommandExecutionCoordinator.java index b78ef70a..ae30bfff 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/AsynchronousCommandExecutionCoordinator.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/AsynchronousCommandExecutionCoordinator.java @@ -50,9 +50,11 @@ public final class AsynchronousCommandExecutionCoordinator extends CommandExe private final Executor executor; private final boolean synchronizeParsing; - private AsynchronousCommandExecutionCoordinator(final @Nullable Executor executor, - final boolean synchronizeParsing, - final @NonNull CommandTree commandTree) { + private AsynchronousCommandExecutionCoordinator( + final @Nullable Executor executor, + final boolean synchronizeParsing, + final @NonNull CommandTree commandTree + ) { super(commandTree); this.executor = executor == null ? ForkJoinPool.commonPool() : executor; this.synchronizeParsing = synchronizeParsing; @@ -70,8 +72,10 @@ public final class AsynchronousCommandExecutionCoordinator extends CommandExe } @Override - public @NonNull CompletableFuture> coordinateExecution(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> input) { + public @NonNull CompletableFuture> coordinateExecution( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> input + ) { final Consumer> commandConsumer = command -> { if (this.commandManager.postprocessContext(commandContext, command) == State.ACCEPTED) { diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/CommandExecutionCoordinator.java b/cloud-core/src/main/java/cloud/commandframework/execution/CommandExecutionCoordinator.java index 8eddcfa7..d7b2f160 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/CommandExecutionCoordinator.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/CommandExecutionCoordinator.java @@ -74,8 +74,10 @@ public abstract class CommandExecutionCoordinator { * @param input Command input * @return Future that completes with the result */ - public abstract @NonNull CompletableFuture> coordinateExecution(@NonNull CommandContext commandContext, - @NonNull Queue<@NonNull String> input); + public abstract @NonNull CompletableFuture> coordinateExecution( + @NonNull CommandContext commandContext, + @NonNull Queue<@NonNull String> input + ); /** * Get the command tree @@ -100,8 +102,10 @@ public abstract class CommandExecutionCoordinator { } @Override - public CompletableFuture> coordinateExecution(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> input) { + public CompletableFuture> coordinateExecution( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> input + ) { final CompletableFuture> completableFuture = new CompletableFuture<>(); try { final @NonNull Pair<@Nullable Command, @Nullable Exception> pair = diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/FilteringCommandSuggestionProcessor.java b/cloud-core/src/main/java/cloud/commandframework/execution/FilteringCommandSuggestionProcessor.java index 2c45a9cb..b5944933 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/FilteringCommandSuggestionProcessor.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/FilteringCommandSuggestionProcessor.java @@ -37,8 +37,10 @@ import java.util.List; public final class FilteringCommandSuggestionProcessor implements CommandSuggestionProcessor { @Override - public @NonNull List<@NonNull String> apply(final @NonNull CommandPreprocessingContext context, - final @NonNull List<@NonNull String> strings) { + public @NonNull List<@NonNull String> apply( + final @NonNull CommandPreprocessingContext context, + final @NonNull List<@NonNull String> strings + ) { final String input; if (context.getInputQueue().isEmpty()) { input = ""; diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessingContext.java b/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessingContext.java index 8b411930..b2dc7209 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessingContext.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessingContext.java @@ -45,8 +45,10 @@ public final class CommandPostprocessingContext { * @param commandContext Command context * @param command Command instance */ - public CommandPostprocessingContext(final @NonNull CommandContext<@NonNull C> commandContext, - final @NonNull Command<@NonNull C> command) { + public CommandPostprocessingContext( + final @NonNull CommandContext<@NonNull C> commandContext, + final @NonNull Command<@NonNull C> command + ) { this.commandContext = commandContext; this.command = command; } diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessor.java b/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessor.java index 96a66b86..9763a856 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessor.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/postprocessor/CommandPostprocessor.java @@ -31,4 +31,5 @@ import cloud.commandframework.services.types.ConsumerService; * @param Command sender type */ public interface CommandPostprocessor extends ConsumerService> { + } diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessingContext.java b/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessingContext.java index 5732e0e1..897935fa 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessingContext.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessingContext.java @@ -45,8 +45,10 @@ public final class CommandPreprocessingContext { * @param commandContext Command context * @param inputQueue Command input as supplied by sender */ - public CommandPreprocessingContext(final @NonNull CommandContext commandContext, - final @NonNull LinkedList<@NonNull String> inputQueue) { + public CommandPreprocessingContext( + final @NonNull CommandContext commandContext, + final @NonNull LinkedList<@NonNull String> inputQueue + ) { this.commandContext = commandContext; this.inputQueue = inputQueue; } diff --git a/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessor.java b/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessor.java index 7f2f227a..9f800465 100644 --- a/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessor.java +++ b/cloud-core/src/main/java/cloud/commandframework/execution/preprocessor/CommandPreprocessor.java @@ -35,4 +35,5 @@ import cloud.commandframework.services.types.ConsumerService; * @param Command sender type */ public interface CommandPreprocessor extends ConsumerService> { + } diff --git a/cloud-core/src/main/java/cloud/commandframework/extra/confirmation/CommandConfirmationManager.java b/cloud-core/src/main/java/cloud/commandframework/extra/confirmation/CommandConfirmationManager.java index 057ff275..ec29f21b 100644 --- a/cloud-core/src/main/java/cloud/commandframework/extra/confirmation/CommandConfirmationManager.java +++ b/cloud-core/src/main/java/cloud/commandframework/extra/confirmation/CommandConfirmationManager.java @@ -72,10 +72,12 @@ public class CommandConfirmationManager { * @param notifier Notifier that gets called when a command gets added to the queue * @param errorNotifier Notifier that gets called when someone tries to confirm a command with nothing in the queue */ - public CommandConfirmationManager(final long timeout, - final @NonNull TimeUnit timeoutTimeUnit, - final @NonNull Consumer<@NonNull CommandPostprocessingContext> notifier, - final @NonNull Consumer<@NonNull C> errorNotifier) { + public CommandConfirmationManager( + final long timeout, + final @NonNull TimeUnit timeoutTimeUnit, + final @NonNull Consumer<@NonNull CommandPostprocessingContext> notifier, + final @NonNull Consumer<@NonNull C> errorNotifier + ) { this.notifier = notifier; this.errorNotifier = errorNotifier; this.pendingCommands = new LinkedHashMap, Long>>() { @@ -141,8 +143,8 @@ public class CommandConfirmationManager { if (pending.isPresent()) { final CommandPostprocessingContext postprocessingContext = pending.get(); postprocessingContext.getCommand() - .getCommandExecutionHandler() - .execute(postprocessingContext.getCommandContext()); + .getCommandExecutionHandler() + .execute(postprocessingContext.getCommandContext()); } else { this.errorNotifier.accept(context.getSender()); } @@ -155,9 +157,9 @@ public class CommandConfirmationManager { @Override public void accept(final @NonNull CommandPostprocessingContext context) { if (!context.getCommand() - .getCommandMeta() - .getOrDefault(CONFIRMATION_REQUIRED_META, "false") - .equals("true")) { + .getCommandMeta() + .getOrDefault(CONFIRMATION_REQUIRED_META, "false") + .equals("true")) { return; } /* Add it to the "queue" */ diff --git a/cloud-core/src/main/java/cloud/commandframework/internal/CommandRegistrationHandler.java b/cloud-core/src/main/java/cloud/commandframework/internal/CommandRegistrationHandler.java index d0abc518..d8dd0223 100644 --- a/cloud-core/src/main/java/cloud/commandframework/internal/CommandRegistrationHandler.java +++ b/cloud-core/src/main/java/cloud/commandframework/internal/CommandRegistrationHandler.java @@ -48,7 +48,7 @@ public interface CommandRegistrationHandler { * * @param command Command to register * @return {@code true} if the command was registered successfully, - * else {@code false} + * else {@code false} */ boolean registerCommand(@NonNull Command command); diff --git a/cloud-core/src/main/java/cloud/commandframework/meta/SimpleCommandMeta.java b/cloud-core/src/main/java/cloud/commandframework/meta/SimpleCommandMeta.java index a29d1fc9..3e4414f0 100644 --- a/cloud-core/src/main/java/cloud/commandframework/meta/SimpleCommandMeta.java +++ b/cloud-core/src/main/java/cloud/commandframework/meta/SimpleCommandMeta.java @@ -121,8 +121,10 @@ public class SimpleCommandMeta extends CommandMeta { * @param value Value * @return Builder instance */ - public @NonNull Builder with(final @NonNull String key, - final @NonNull String value) { + public @NonNull Builder with( + final @NonNull String key, + final @NonNull String value + ) { this.map.put(key, value); return this; } diff --git a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Pair.java b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Pair.java index a490dc5a..5273de57 100644 --- a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Pair.java +++ b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Pair.java @@ -38,8 +38,10 @@ public class Pair implements Tuple { private final U first; private final V second; - protected Pair(final U first, - final V second) { + protected Pair( + final U first, + final V second + ) { this.first = first; this.second = second; } @@ -53,8 +55,10 @@ public class Pair implements Tuple { * @param Second type * @return Created pair */ - public static @NonNull Pair of(final U first, - final V second) { + public static @NonNull Pair of( + final U first, + final V second + ) { return new Pair<>(first, second); } diff --git a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quartet.java b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quartet.java index 49244491..03d7f7fa 100644 --- a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quartet.java +++ b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quartet.java @@ -42,10 +42,12 @@ public class Quartet implements Tuple { private final W third; private final X fourth; - protected Quartet(final @NonNull U first, - final @NonNull V second, - final @NonNull W third, - final @NonNull X fourth) { + protected Quartet( + final @NonNull U first, + final @NonNull V second, + final @NonNull W third, + final @NonNull X fourth + ) { this.first = first; this.second = second; this.third = third; @@ -65,10 +67,12 @@ public class Quartet implements Tuple { * @param Fourth type * @return Created quartet */ - public static @NonNull Quartet<@NonNull U, @NonNull V, @NonNull W, @NonNull X> of(final @NonNull U first, - final @NonNull V second, - final @NonNull W third, - final @NonNull X fourth) { + public static @NonNull Quartet<@NonNull U, @NonNull V, @NonNull W, @NonNull X> of( + final @NonNull U first, + final @NonNull V second, + final @NonNull W third, + final @NonNull X fourth + ) { return new Quartet<>(first, second, third, fourth); } diff --git a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quintet.java b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quintet.java index 8004f202..a4958ec8 100644 --- a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quintet.java +++ b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Quintet.java @@ -44,11 +44,13 @@ public class Quintet implements Tuple { private final X fourth; private final Y fifth; - protected Quintet(final @NonNull U first, - final @NonNull V second, - final @NonNull W third, - final @NonNull X fourth, - final @NonNull Y fifth) { + protected Quintet( + final @NonNull U first, + final @NonNull V second, + final @NonNull W third, + final @NonNull X fourth, + final @NonNull Y fifth + ) { this.first = first; this.second = second; this.third = third; @@ -76,7 +78,8 @@ public class Quintet implements Tuple { final @NonNull V second, final @NonNull W third, final @NonNull X fourth, - final @NonNull Y fifth) { + final @NonNull Y fifth + ) { return new Quintet<>(first, second, third, fourth, fifth); } diff --git a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Sextet.java b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Sextet.java index 90687eeb..c8ae61a9 100644 --- a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Sextet.java +++ b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Sextet.java @@ -46,12 +46,14 @@ public class Sextet implements Tuple { private final Y fifth; private final Z sixth; - protected Sextet(final @NonNull U first, - final @NonNull V second, - final @NonNull W third, - final @NonNull X fourth, - final @NonNull Y fifth, - final @NonNull Z sixth) { + protected Sextet( + final @NonNull U first, + final @NonNull V second, + final @NonNull W third, + final @NonNull X fourth, + final @NonNull Y fifth, + final @NonNull Z sixth + ) { this.first = first; this.second = second; this.third = third; @@ -78,12 +80,13 @@ public class Sextet implements Tuple { * @return Created sextet */ public static @NonNull Sextet<@NonNull U, @NonNull V, @NonNull W, @NonNull X, @NonNull Y, @NonNull Z> of( - final @NonNull U first, - final @NonNull V second, - final @NonNull W third, - final @NonNull X fourth, - final @NonNull Y fifth, - final @NonNull Z sixth) { + final @NonNull U first, + final @NonNull V second, + final @NonNull W third, + final @NonNull X fourth, + final @NonNull Y fifth, + final @NonNull Z sixth + ) { return new Sextet<>(first, second, third, fourth, fifth, sixth); } @@ -166,7 +169,8 @@ public class Sextet implements Tuple { @Override public final String toString() { return String.format("(%s, %s, %s, %s, %s, %s)", this.first, this.second, this.third, - this.fourth, this.fifth, this.sixth); + this.fourth, this.fifth, this.sixth + ); } @Override diff --git a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Triplet.java b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Triplet.java index 98c39515..f4faff6b 100644 --- a/cloud-core/src/main/java/cloud/commandframework/types/tuples/Triplet.java +++ b/cloud-core/src/main/java/cloud/commandframework/types/tuples/Triplet.java @@ -40,9 +40,11 @@ public class Triplet implements Tuple { private final V second; private final W third; - protected Triplet(final @NonNull U first, - final @NonNull V second, - final @NonNull W third) { + protected Triplet( + final @NonNull U first, + final @NonNull V second, + final @NonNull W third + ) { this.first = first; this.second = second; this.third = third; @@ -59,9 +61,11 @@ public class Triplet implements Tuple { * @param Third type * @return Created triplet */ - public static @NonNull Triplet<@NonNull U, @NonNull V, @NonNull W> of(final @NonNull U first, - final @NonNull V second, - final @NonNull W third) { + public static @NonNull Triplet<@NonNull U, @NonNull V, @NonNull W> of( + final @NonNull U first, + final @NonNull V second, + final @NonNull W third + ) { return new Triplet<>(first, second, third); } diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandHelpHandlerTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandHelpHandlerTest.java index 14923258..8960887f 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandHelpHandlerTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandHelpHandlerTest.java @@ -50,10 +50,11 @@ class CommandHelpHandlerTest { argument(IntegerArgument.of("int"), Description.of("A number")).build()); manager.command(manager.commandBuilder("vec") - .meta("description", "Takes in a vector") - .argumentPair("vec", Pair.of("x", "y"), - Pair.of(Double.class, Double.class), Description.of("Vector")) - .build()); + .meta("description", "Takes in a vector") + .argumentPair("vec", Pair.of("x", "y"), + Pair.of(Double.class, Double.class), Description.of("Vector") + ) + .build()); } @Test @@ -88,8 +89,10 @@ class CommandHelpHandlerTest { this.printTopic("vec", query4); } - private void printTopic(final String query, - final CommandHelpHandler.HelpTopic helpTopic) { + private void printTopic( + final String query, + final CommandHelpHandler.HelpTopic helpTopic + ) { System.out.printf("Showing results for query: \"/%s\"\n", query); if (helpTopic instanceof CommandHelpHandler.IndexHelpTopic) { this.printIndexHelpTopic((CommandHelpHandler.IndexHelpTopic) helpTopic); @@ -135,7 +138,7 @@ class CommandHelpHandlerTest { private void printVerboseHelpTopic(final CommandHelpHandler.VerboseHelpTopic helpTopic) { System.out.printf("└── Command: /%s\n", manager.getCommandSyntaxFormatter() - .apply(helpTopic.getCommand().getArguments(), null)); + .apply(helpTopic.getCommand().getArguments(), null)); System.out.printf(" ├── Description: %s\n", helpTopic.getDescription()); System.out.println(" └── Args: "); final Iterator> iterator = helpTopic.getCommand().getArguments().iterator(); diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandPerformanceTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandPerformanceTest.java index cf5e4bb0..afc4988f 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandPerformanceTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandPerformanceTest.java @@ -23,8 +23,8 @@ // package cloud.commandframework; -import cloud.commandframework.execution.CommandResult; import cloud.commandframework.context.CommandContext; +import cloud.commandframework.execution.CommandResult; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -73,7 +73,8 @@ final class CommandPerformanceTest { double averageTime = elapsedTime / (double) amount; System.out.printf("Average literal parse time: %fns (%f ms) | %d samples & %d iterations\n", - averageTime, averageTime / 10e6, 101, 100000); + averageTime, averageTime / 10e6, 101, 100000 + ); } @Test @@ -84,7 +85,7 @@ final class CommandPerformanceTest { final Options options = new OptionsBuilder() .include(ExecutionBenchmark.class.getSimpleName()) .build(); - final Collection results = new Runner(options).run(); + final Collection results = new Runner(options).run(); Assertions.assertFalse(results.isEmpty()); } diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandPermissionTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandPermissionTest.java index 6005ba03..684c18d2 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandPermissionTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandPermissionTest.java @@ -57,8 +57,10 @@ class CommandPermissionTest { } @Override - public boolean hasPermission(final TestCommandSender sender, - final String permission) { + public boolean hasPermission( + final TestCommandSender sender, + final String permission + ) { return acceptOne && permission.equalsIgnoreCase("test.permission.four"); } @@ -66,6 +68,7 @@ class CommandPermissionTest { public CommandMeta createDefaultCommandMeta() { return SimpleCommandMeta.empty(); } + } } diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandPostProcessorTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandPostProcessorTest.java index 6ab82b72..e3b840a0 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandPostProcessorTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandPostProcessorTest.java @@ -33,21 +33,21 @@ import org.junit.jupiter.api.Test; public class CommandPostProcessorTest { + private static final boolean[] state = new boolean[]{false}; private static CommandManager manager; - private static final boolean[] state = new boolean[] {false}; @BeforeAll static void newTree() { manager = new TestCommandManager(); manager.command(manager.commandBuilder("test", SimpleCommandMeta.empty()) - .handler(c -> state[0] = true) - .build()); + .handler(c -> state[0] = true) + .build()); manager.registerCommandPostProcessor(new SamplePostprocessor()); } @Test void testPreprocessing() { - manager.executeCommand(new TestCommandSender(),"test").join(); + manager.executeCommand(new TestCommandSender(), "test").join(); Assertions.assertEquals(false, state[0]); } diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandPreProcessorTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandPreProcessorTest.java index 026be94a..1e43bd40 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandPreProcessorTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandPreProcessorTest.java @@ -40,24 +40,26 @@ public class CommandPreProcessorTest { static void newTree() { manager = new TestCommandManager(); manager.command(manager.commandBuilder("test", SimpleCommandMeta.empty()) - .argument(EnumArgument.of(SampleEnum.class, "enum")) - .handler( - commandContext -> System.out.printf("enum = %s | integer = %d\n", - commandContext.getOptional( - "enum").orElse( - SampleEnum.VALUE1), - commandContext.getOptional( - "int").orElseThrow( - () -> new NullPointerException( - "int")))) - .build()); + .argument(EnumArgument.of(SampleEnum.class, "enum")) + .handler( + commandContext -> System.out.printf( + "enum = %s | integer = %d\n", + commandContext.getOptional( + "enum").orElse( + SampleEnum.VALUE1), + commandContext.getOptional( + "int").orElseThrow( + () -> new NullPointerException( + "int")) + )) + .build()); manager.registerCommandPreProcessor(new SamplePreprocessor()); } @Test void testPreprocessing() { Assertions.assertEquals(10, manager.executeCommand(new TestCommandSender(), "10 test value1") - .join().getCommandContext().getOptional("int").orElse(0)); + .join().getCommandContext().getOptional("int").orElse(0)); manager.executeCommand(new TestCommandSender(), "aa test value1").join(); } diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandSuggestionsTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandSuggestionsTest.java index dc6c4c6b..19d8c4f1 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandSuggestionsTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandSuggestionsTest.java @@ -45,38 +45,40 @@ public class CommandSuggestionsTest { manager.command(manager.commandBuilder("test").literal("one").build()); manager.command(manager.commandBuilder("test").literal("two").build()); manager.command(manager.commandBuilder("test") - .literal("var") - .argument(StringArgument.newBuilder("str") - .withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))) - .argument(EnumArgument.of(TestEnum.class, "enum"))); + .literal("var") + .argument(StringArgument.newBuilder("str") + .withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))) + .argument(EnumArgument.of(TestEnum.class, "enum"))); manager.command(manager.commandBuilder("test") - .literal("comb") - .argument(StringArgument.newBuilder("str") - .withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))) - .argument(IntegerArgument.newBuilder("num") - .withMin(1).withMax(95).asOptional())); + .literal("comb") + .argument(StringArgument.newBuilder("str") + .withSuggestionsProvider((c, s) -> Arrays.asList("one", "two"))) + .argument(IntegerArgument.newBuilder("num") + .withMin(1).withMax(95).asOptional())); manager.command(manager.commandBuilder("test") - .literal("alt") - .argument(IntegerArgument.newBuilder("num") - .withSuggestionsProvider((c, s) -> Arrays.asList("3", "33", "333")))); + .literal("alt") + .argument(IntegerArgument.newBuilder("num") + .withSuggestionsProvider((c, s) -> Arrays.asList("3", "33", "333")))); manager.command(manager.commandBuilder("com") - .argumentPair("com", Pair.of("x", "y"), Pair.of(Integer.class, TestEnum.class), - Description.empty()) - .argument(IntegerArgument.of("int"))); + .argumentPair("com", Pair.of("x", "y"), Pair.of(Integer.class, TestEnum.class), + Description.empty() + ) + .argument(IntegerArgument.of("int"))); manager.command(manager.commandBuilder("com2") - .argumentPair("com", Pair.of("x", "enum"), - Pair.of(Integer.class, TestEnum.class), Description.empty())); + .argumentPair("com", Pair.of("x", "enum"), + Pair.of(Integer.class, TestEnum.class), Description.empty() + )); manager.command(manager.commandBuilder("flags") - .argument(IntegerArgument.of("num")) - .flag(manager.flagBuilder("enum") - .withArgument(EnumArgument.of(TestEnum.class, "enum")) - .build()) - .flag(manager.flagBuilder("static") - .build()) - .build()); + .argument(IntegerArgument.of("num")) + .flag(manager.flagBuilder("enum") + .withArgument(EnumArgument.of(TestEnum.class, "enum")) + .build()) + .flag(manager.flagBuilder("static") + .build()) + .build()); } @Test diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandTest.java index ac17d847..5a9da80b 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandTest.java @@ -40,7 +40,7 @@ class CommandTest { void ensureOrdering() { Assertions.assertThrows(IllegalArgumentException.class, () -> Command.newBuilder("test", SimpleCommandMeta.empty()).argument(StringArgument.optional("something")) - .argument(StaticArgument.of("somethingelse")).build()); + .argument(StaticArgument.of("somethingelse")).build()); } } diff --git a/cloud-core/src/test/java/cloud/commandframework/CommandTreeTest.java b/cloud-core/src/test/java/cloud/commandframework/CommandTreeTest.java index 6923c58c..b1e0088b 100644 --- a/cloud-core/src/test/java/cloud/commandframework/CommandTreeTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/CommandTreeTest.java @@ -51,102 +51,113 @@ class CommandTreeTest { /* Build general test commands */ manager.command(manager.commandBuilder("test", SimpleCommandMeta.empty()) - .literal("one").build()) - .command(manager.commandBuilder("test", SimpleCommandMeta.empty()) - .literal("two").withPermission("no").build()) - .command(manager.commandBuilder("test", Collections.singleton("other"), - SimpleCommandMeta.empty()) - .literal("opt", "öpt") - .argument(IntegerArgument - .optional("num", EXPECTED_INPUT_NUMBER)) - .build()) - .command(manager.commandBuilder("req").withSenderType(SpecificCommandSender.class).build()); + .literal("one").build()) + .command(manager.commandBuilder("test", SimpleCommandMeta.empty()) + .literal("two").withPermission("no").build()) + .command(manager.commandBuilder("test", Collections.singleton("other"), + SimpleCommandMeta.empty() + ) + .literal("opt", "öpt") + .argument(IntegerArgument + .optional("num", EXPECTED_INPUT_NUMBER)) + .build()) + .command(manager.commandBuilder("req").senderType(SpecificCommandSender.class).build()); /* Build command to test command proxying */ final Command toProxy = manager.commandBuilder("test") - .literal("unproxied") - .argument(StringArgument.of("string")) - .argument(IntegerArgument.of("int")) - .literal("anotherliteral") - .handler(c -> { - }) - .build(); + .literal("unproxied") + .argument(StringArgument.of("string")) + .argument(IntegerArgument.of("int")) + .literal("anotherliteral") + .handler(c -> { + }) + .build(); manager.command(toProxy); manager.command(manager.commandBuilder("proxy").proxies(toProxy).build()); /* Build command for testing intermediary and final executors */ manager.command(manager.commandBuilder("command") - .withPermission("command.inner") - .literal("inner") - .handler(c -> System.out.println("Using inner command"))); + .withPermission("command.inner") + .literal("inner") + .handler(c -> System.out.println("Using inner command"))); manager.command(manager.commandBuilder("command") - .withPermission("command.outer") - .handler(c -> System.out.println("Using outer command"))); + .withPermission("command.outer") + .handler(c -> System.out.println("Using outer command"))); /* Build command for testing compound types */ manager.command(manager.commandBuilder("pos") - .argument(ArgumentPair.of(manager, "pos", Pair.of("x", "y"), - Pair.of(Integer.class, Integer.class)) - .simple()) - .handler(c -> { - final Pair pair = c.get("pos"); - System.out.printf("X: %d | Y: %d\n", pair.getFirst(), pair.getSecond()); - })); + .argument(ArgumentPair.of(manager, "pos", Pair.of("x", "y"), + Pair.of(Integer.class, Integer.class) + ) + .simple()) + .handler(c -> { + final Pair pair = c.get("pos"); + System.out.printf("X: %d | Y: %d\n", pair.getFirst(), pair.getSecond()); + })); manager.command(manager.commandBuilder("vec") - .argument(ArgumentPair.of(manager, "vec", Pair.of("x", "y"), - Pair.of(Double.class, Double.class)) - .withMapper(Vector2.class, - (sender, pair) -> new Vector2(pair.getFirst(), pair.getSecond())) - ) - .handler(c -> { - final Vector2 vector2 = c.get("vec"); - System.out.printf("X: %f | Y: %f\n", vector2.getX(), vector2.getY()); - })); + .argument(ArgumentPair.of(manager, "vec", Pair.of("x", "y"), + Pair.of(Double.class, Double.class) + ) + .withMapper( + Vector2.class, + (sender, pair) -> new Vector2(pair.getFirst(), pair.getSecond()) + ) + ) + .handler(c -> { + final Vector2 vector2 = c.get("vec"); + System.out.printf("X: %f | Y: %f\n", vector2.getX(), vector2.getY()); + })); /* Build command for testing flags */ manager.command(manager.commandBuilder("flags") - .flag(manager.flagBuilder("test") - .withAliases("t") - .build()) - .flag(manager.flagBuilder("test2") - .build()) - .flag(manager.flagBuilder("num") - .withArgument(IntegerArgument.of("num")).build()) - .handler(c -> { - System.out.println("Flag present? " + c.flags().isPresent("test")); - System.out.println("Numerical flag: " + c.flags().getValue("num", -10)); - }) - .build()); + .flag(manager.flagBuilder("test") + .withAliases("t") + .build()) + .flag(manager.flagBuilder("test2") + .build()) + .flag(manager.flagBuilder("num") + .withArgument(IntegerArgument.of("num")).build()) + .handler(c -> { + System.out.println("Flag present? " + c.flags().isPresent("test")); + System.out.println("Numerical flag: " + c.flags().getValue("num", -10)); + }) + .build()); } @Test void parse() { final Pair, Exception> command = manager.getCommandTree() - .parse(new CommandContext<>( - new TestCommandSender()), - new LinkedList<>( - Arrays.asList("test", - "one"))); + .parse( + new CommandContext<>( + new TestCommandSender()), + new LinkedList<>( + Arrays.asList( + "test", + "one" + )) + ); Assertions.assertNotNull(command.getFirst()); Assertions.assertEquals(NoPermissionException.class, manager.getCommandTree() - .parse(new CommandContext<>( - new TestCommandSender()), - new LinkedList<>( - Arrays.asList("test", "two"))) - .getSecond().getClass()); + .parse( + new CommandContext<>( + new TestCommandSender()), + new LinkedList<>( + Arrays.asList("test", "two")) + ) + .getSecond().getClass()); manager.getCommandTree() - .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt"))) - .getFirst().getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())); + .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt"))) + .getFirst().getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())); manager.getCommandTree() - .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt", "12"))) - .getFirst().getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())); + .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt", "12"))) + .getFirst().getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())); } @Test void testAlias() { manager.getCommandTree() - .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("other", "öpt", "12"))) - .getFirst().getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())); + .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("other", "öpt", "12"))) + .getFirst().getCommandExecutionHandler().execute(new CommandContext<>(new TestCommandSender())); } @Test @@ -166,11 +177,11 @@ class CommandTreeTest { void testDefaultParser() { manager.command( manager.commandBuilder("default") - .argument(manager.argumentBuilder(Integer.class, "int")) - .handler(context -> { - final int number = context.get("int"); - System.out.printf("Supplied number is: %d\n", number); - }) + .argument(manager.argumentBuilder(Integer.class, "int")) + .handler(context -> { + final int number = context.get("int"); + System.out.printf("Supplied number is: %d\n", number); + }) ); manager.executeCommand(new TestCommandSender(), "default 5").join(); } @@ -224,6 +235,7 @@ class CommandTreeTest { public static final class SpecificCommandSender extends TestCommandSender { + } diff --git a/cloud-core/src/test/java/cloud/commandframework/ParserRegistryTest.java b/cloud-core/src/test/java/cloud/commandframework/ParserRegistryTest.java index 59cbeaf2..bc3989ce 100644 --- a/cloud-core/src/test/java/cloud/commandframework/ParserRegistryTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/ParserRegistryTest.java @@ -68,11 +68,13 @@ public class ParserRegistryTest { final ParserParameters parserParameters = parserRegistry.parseAnnotations(parsedType, Collections.singleton(range)); Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MIN)); Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MAX)); - final ArgumentParser parser = parserRegistry.createParser(parsedType, - parserParameters) - .orElseThrow( - () -> new NullPointerException( - "No parser found")); + final ArgumentParser parser = parserRegistry.createParser( + parsedType, + parserParameters + ) + .orElseThrow( + () -> new NullPointerException( + "No parser found")); Assertions.assertTrue(parser instanceof IntegerArgument.IntegerParser); @SuppressWarnings("unchecked") final IntegerArgument.IntegerParser integerParser = (IntegerArgument.IntegerParser) parser; @@ -81,11 +83,11 @@ public class ParserRegistryTest { /* Test integer */ parserRegistry.createParser(TypeToken.get(int.class), ParserParameters.empty()) - .orElseThrow(() -> new IllegalArgumentException("No parser found for int.class")); + .orElseThrow(() -> new IllegalArgumentException("No parser found for int.class")); /* Test Enum */ parserRegistry.createParser(TypeToken.get(CommandManager.ManagerSettings.class), ParserParameters.empty()) - .orElseThrow(() -> new IllegalArgumentException("No parser found for enum")); + .orElseThrow(() -> new IllegalArgumentException("No parser found for enum")); } } diff --git a/cloud-core/src/test/java/cloud/commandframework/arguments/standard/StringArgumentTest.java b/cloud-core/src/test/java/cloud/commandframework/arguments/standard/StringArgumentTest.java index 962b273f..3c5afd93 100644 --- a/cloud-core/src/test/java/cloud/commandframework/arguments/standard/StringArgumentTest.java +++ b/cloud-core/src/test/java/cloud/commandframework/arguments/standard/StringArgumentTest.java @@ -39,29 +39,29 @@ class StringArgumentTest { static void setup() { manager = new TestCommandManager(); manager.command(manager.commandBuilder("quoted") - .argument(StringArgument.of("message1", StringArgument.StringMode.QUOTED)) - .argument(StringArgument.of("message2")) - .handler(c -> { - final String message1 = c.get("message1"); - final String message2 = c.get("message2"); - storage[0] = message1; - storage[1] = message2; - }) - .build()); + .argument(StringArgument.of("message1", StringArgument.StringMode.QUOTED)) + .argument(StringArgument.of("message2")) + .handler(c -> { + final String message1 = c.get("message1"); + final String message2 = c.get("message2"); + storage[0] = message1; + storage[1] = message2; + }) + .build()); manager.command(manager.commandBuilder("single") - .argument(StringArgument.of("message")) - .handler(c -> { - final String message = c.get("message"); - storage[0] = message; - }) - .build()); + .argument(StringArgument.of("message")) + .handler(c -> { + final String message = c.get("message"); + storage[0] = message; + }) + .build()); manager.command(manager.commandBuilder("greedy") - .argument(StringArgument.of("message", StringArgument.StringMode.GREEDY)) - .handler(c -> { - final String message = c.get("message"); - storage[0] = message; - }) - .build()); + .argument(StringArgument.of("message", StringArgument.StringMode.GREEDY)) + .handler(c -> { + final String message = c.get("message"); + storage[0] = message; + }) + .build()); } private static void clear() { diff --git a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommand.java b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommand.java index 3c2da9b7..79db7e24 100644 --- a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommand.java +++ b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommand.java @@ -48,9 +48,11 @@ public class JavacordCommand implements MessageCreateListener { private final CommandArgument command; private final cloud.commandframework.Command cloudCommand; - JavacordCommand(final cloud.commandframework.@NonNull Command cloudCommand, - final @NonNull CommandArgument command, - final @NonNull JavacordCommandManager manager) { + JavacordCommand( + final cloud.commandframework.@NonNull Command cloudCommand, + final @NonNull CommandArgument command, + final @NonNull JavacordCommandManager manager + ) { this.command = command; this.manager = manager; this.cloudCommand = cloudCommand; @@ -85,70 +87,78 @@ public class JavacordCommand implements MessageCreateListener { final String finalContent = messageContent; //noinspection unchecked if (((StaticArgument) command).getAliases() - .stream() - .map(String::toLowerCase) - .noneMatch(commandAlias -> finalContent.toLowerCase().startsWith(commandAlias))) { + .stream() + .map(String::toLowerCase) + .noneMatch(commandAlias -> finalContent.toLowerCase().startsWith(commandAlias))) { return; } manager.executeCommand(sender, finalContent) - .whenComplete(((commandResult, throwable) -> { - if (throwable == null) { - return; - } + .whenComplete(((commandResult, throwable) -> { + if (throwable == null) { + return; + } - if (throwable instanceof CompletionException) { - throwable = throwable.getCause(); - } + if (throwable instanceof CompletionException) { + throwable = throwable.getCause(); + } - if (throwable instanceof NoSuchCommandException) { - //Ignore, should never happen - return; - } + if (throwable instanceof NoSuchCommandException) { + //Ignore, should never happen + return; + } - if (throwable instanceof InvalidSyntaxException) { - manager.handleException(sender, - InvalidSyntaxException.class, - (InvalidSyntaxException) throwable, - (c, e) -> commandSender.sendErrorMessage( - "Invalid Command Syntax. Correct command syntax is: `" - + e.getCorrectSyntax() - + "`") - ); + if (throwable instanceof InvalidSyntaxException) { + manager.handleException( + sender, + InvalidSyntaxException.class, + (InvalidSyntaxException) throwable, + (c, e) -> commandSender.sendErrorMessage( + "Invalid Command Syntax. Correct command syntax is: `" + + e.getCorrectSyntax() + + "`") + ); - return; - } + return; + } - if (throwable instanceof InvalidCommandSenderException) { - manager.handleException(sender, - InvalidCommandSenderException.class, - (InvalidCommandSenderException) throwable, - (c, e) -> commandSender.sendErrorMessage(e.getMessage())); + if (throwable instanceof InvalidCommandSenderException) { + manager.handleException( + sender, + InvalidCommandSenderException.class, + (InvalidCommandSenderException) throwable, + (c, e) -> commandSender.sendErrorMessage(e.getMessage()) + ); - return; - } + return; + } - if (throwable instanceof NoPermissionException) { - manager.handleException(sender, - NoPermissionException.class, - (NoPermissionException) throwable, - (c, e) -> commandSender.sendErrorMessage(MESSAGE_NO_PERMS)); + if (throwable instanceof NoPermissionException) { + manager.handleException( + sender, + NoPermissionException.class, + (NoPermissionException) throwable, + (c, e) -> commandSender.sendErrorMessage(MESSAGE_NO_PERMS) + ); - return; - } + return; + } - if (throwable instanceof ArgumentParseException) { - manager.handleException(sender, - ArgumentParseException.class, - (ArgumentParseException) throwable, - (c, e) -> commandSender.sendErrorMessage( - "Invalid Command Argument: `" + e.getCause().getMessage() + "`")); + if (throwable instanceof ArgumentParseException) { + manager.handleException( + sender, + ArgumentParseException.class, + (ArgumentParseException) throwable, + (c, e) -> commandSender.sendErrorMessage( + "Invalid Command Argument: `" + e.getCause().getMessage() + "`") + ); - return; - } + return; + } - commandSender.sendErrorMessage(throwable.getMessage()); - throwable.printStackTrace(); - })); + commandSender.sendErrorMessage(throwable.getMessage()); + throwable.printStackTrace(); + })); } + } diff --git a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommandManager.java b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommandManager.java index 66a06c0d..604b8964 100644 --- a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommandManager.java +++ b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordCommandManager.java @@ -59,15 +59,17 @@ public class JavacordCommandManager extends CommandManager { * @param commandPermissionMapper Function used to check if a command sender has the permission to execute a command * @throws Exception If the construction of the manager fails */ - public JavacordCommandManager(final @NonNull DiscordApi discordApi, - final @NonNull Function<@NonNull CommandTree, - @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull Function<@NonNull JavacordCommandSender, @NonNull C> commandSenderMapper, - final @NonNull Function<@NonNull C, - @NonNull JavacordCommandSender> backwardsCommandSenderMapper, - final @NonNull Function<@NonNull C, @NonNull String> commandPrefixMapper, - final @Nullable BiFunction<@NonNull C, - @NonNull String, @NonNull Boolean> commandPermissionMapper) + public JavacordCommandManager( + final @NonNull DiscordApi discordApi, + final @NonNull Function<@NonNull CommandTree, + @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, + final @NonNull Function<@NonNull JavacordCommandSender, @NonNull C> commandSenderMapper, + final @NonNull Function<@NonNull C, + @NonNull JavacordCommandSender> backwardsCommandSenderMapper, + final @NonNull Function<@NonNull C, @NonNull String> commandPrefixMapper, + final @Nullable BiFunction<@NonNull C, + @NonNull String, @NonNull Boolean> commandPermissionMapper + ) throws Exception { super(commandExecutionCoordinator, new JavacordRegistrationHandler<>()); ((JavacordRegistrationHandler) this.getCommandRegistrationHandler()).initialize(this); @@ -81,7 +83,8 @@ public class JavacordCommandManager extends CommandManager { @Override public final boolean hasPermission( - final @NonNull C sender, final @NonNull String permission) { + final @NonNull C sender, final @NonNull String permission + ) { if (permission.isEmpty()) { return true; } @@ -131,4 +134,5 @@ public class JavacordCommandManager extends CommandManager { public @NonNull DiscordApi getDiscordApi() { return this.discordApi; } + } diff --git a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordRegistrationHandler.java b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordRegistrationHandler.java index ec561975..f12011e0 100644 --- a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordRegistrationHandler.java +++ b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/JavacordRegistrationHandler.java @@ -26,38 +26,40 @@ package cloud.commandframework.javacord; import cloud.commandframework.Command; import cloud.commandframework.arguments.CommandArgument; import cloud.commandframework.internal.CommandRegistrationHandler; +import org.checkerframework.checker.nullness.qual.NonNull; + import java.util.HashMap; import java.util.Map; -import org.checkerframework.checker.nullness.qual.NonNull; final class JavacordRegistrationHandler implements CommandRegistrationHandler { - private final Map, JavacordCommand> registeredCommands = new HashMap<>(); + private final Map, JavacordCommand> registeredCommands = new HashMap<>(); - private JavacordCommandManager javacordCommandManager; + private JavacordCommandManager javacordCommandManager; - JavacordRegistrationHandler() { - } - - void initialize(final @NonNull JavacordCommandManager javacordCommandManager) { - this.javacordCommandManager = javacordCommandManager; - } - - @Override - public boolean registerCommand(final @NonNull Command command) { - /* We only care about the root command argument */ - final CommandArgument commandArgument = command.getArguments().get(0); - if (this.registeredCommands.containsKey(commandArgument)) { - return false; + JavacordRegistrationHandler() { + } + + void initialize(final @NonNull JavacordCommandManager javacordCommandManager) { + this.javacordCommandManager = javacordCommandManager; + } + + @Override + public boolean registerCommand(final @NonNull Command command) { + /* We only care about the root command argument */ + final CommandArgument commandArgument = command.getArguments().get(0); + if (this.registeredCommands.containsKey(commandArgument)) { + return false; + } + @SuppressWarnings("unchecked") final JavacordCommand javacordCommand = new JavacordCommand<>( + (Command) command, + (CommandArgument) commandArgument, + this.javacordCommandManager + ); + this.registeredCommands.put(commandArgument, javacordCommand); + this.javacordCommandManager.getDiscordApi().addMessageCreateListener(javacordCommand); + return true; } - @SuppressWarnings("unchecked") final JavacordCommand javacordCommand = new JavacordCommand<>( - (Command) command, - (CommandArgument) commandArgument, - this.javacordCommandManager); - this.registeredCommands.put(commandArgument, javacordCommand); - this.javacordCommandManager.getDiscordApi().addMessageCreateListener(javacordCommand); - return true; - } } diff --git a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordPrivateSender.java b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordPrivateSender.java index 6cd1f042..b33915bf 100644 --- a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordPrivateSender.java +++ b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordPrivateSender.java @@ -46,7 +46,8 @@ public class JavacordPrivateSender extends JavacordCommandSender { @NonNull public PrivateChannel getPrivateChannel() { return getEvent().getPrivateChannel() - .orElseThrow(() -> new UnsupportedOperationException( - "PrivateTextChannel not present even though message was sent in a private channel")); + .orElseThrow(() -> new UnsupportedOperationException( + "PrivateTextChannel not present even though message was sent in a private channel")); } + } diff --git a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordServerSender.java b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordServerSender.java index 7c9a1389..1fa22f49 100644 --- a/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordServerSender.java +++ b/cloud-discord/cloud-javacord/src/main/java/cloud/commandframework/javacord/sender/JavacordServerSender.java @@ -47,8 +47,8 @@ public class JavacordServerSender extends JavacordCommandSender { @NonNull public ServerChannel getServerChannel() { return getEvent().getServerTextChannel() - .orElseThrow(() -> new UnsupportedOperationException( - "ServerTextChannel not present even though message was sent in a server channel")); + .orElseThrow(() -> new UnsupportedOperationException( + "ServerTextChannel not present even though message was sent in a server channel")); } /** @@ -59,7 +59,8 @@ public class JavacordServerSender extends JavacordCommandSender { @NonNull public Server getServer() { return getEvent().getServer() - .orElseThrow(() -> new UnsupportedOperationException( - "Server not present even though message was sent on a server")); + .orElseThrow(() -> new UnsupportedOperationException( + "Server not present even though message was sent on a server")); } + } diff --git a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandListener.java b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandListener.java index fcb5de23..e3a2e6d4 100644 --- a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandListener.java +++ b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandListener.java @@ -75,51 +75,58 @@ public class JDACommandListener extends ListenerAdapter { content = content.substring(prefix.length()); commandManager.executeCommand(sender, content) - .whenComplete((commandResult, throwable) -> { - if (throwable == null) { - return; - } + .whenComplete((commandResult, throwable) -> { + if (throwable == null) { + return; + } - if (throwable instanceof InvalidSyntaxException) { - this.commandManager.handleException(sender, - InvalidSyntaxException.class, - (InvalidSyntaxException) throwable, (c, e) -> { - this.sendMessage(event, - MESSAGE_INVALID_SYNTAX + prefix + ((InvalidSyntaxException) throwable) - .getCorrectSyntax()); - }); - } else if (throwable instanceof InvalidCommandSenderException) { - this.commandManager.handleException(sender, - InvalidCommandSenderException.class, - (InvalidCommandSenderException) throwable, (c, e) -> - this.sendMessage(event, throwable.getMessage()) - ); - } else if (throwable instanceof NoPermissionException) { - this.commandManager.handleException(sender, - NoPermissionException.class, - (NoPermissionException) throwable, (c, e) -> - this.sendMessage(event, MESSAGE_NO_PERMS) - ); - } else if (throwable instanceof NoSuchCommandException) { - this.commandManager.handleException(sender, - NoSuchCommandException.class, - (NoSuchCommandException) throwable, (c, e) -> - this.sendMessage(event, MESSAGE_UNKNOWN_COMMAND) - ); - } else if (throwable instanceof ArgumentParseException) { - this.commandManager.handleException(sender, ArgumentParseException.class, - (ArgumentParseException) throwable, (c, e) -> { - this.sendMessage(event, - "Invalid Command Argument: " + throwable.getCause() - .getMessage()); - }); - } else { - this.sendMessage(event, throwable.getMessage()); - } - }); + if (throwable instanceof InvalidSyntaxException) { + this.commandManager.handleException(sender, + InvalidSyntaxException.class, + (InvalidSyntaxException) throwable, (c, e) -> { + this.sendMessage( + event, + MESSAGE_INVALID_SYNTAX + prefix + ((InvalidSyntaxException) throwable) + .getCorrectSyntax() + ); + } + ); + } else if (throwable instanceof InvalidCommandSenderException) { + this.commandManager.handleException(sender, + InvalidCommandSenderException.class, + (InvalidCommandSenderException) throwable, (c, e) -> + this.sendMessage(event, throwable.getMessage()) + ); + } else if (throwable instanceof NoPermissionException) { + this.commandManager.handleException(sender, + NoPermissionException.class, + (NoPermissionException) throwable, (c, e) -> + this.sendMessage(event, MESSAGE_NO_PERMS) + ); + } else if (throwable instanceof NoSuchCommandException) { + this.commandManager.handleException(sender, + NoSuchCommandException.class, + (NoSuchCommandException) throwable, (c, e) -> + this.sendMessage(event, MESSAGE_UNKNOWN_COMMAND) + ); + } else if (throwable instanceof ArgumentParseException) { + this.commandManager.handleException(sender, ArgumentParseException.class, + (ArgumentParseException) throwable, (c, e) -> { + this.sendMessage( + event, + "Invalid Command Argument: " + throwable.getCause() + .getMessage() + ); + } + ); + } else { + this.sendMessage(event, throwable.getMessage()); + } + }); } private void sendMessage(final @NonNull MessageReceivedEvent event, final @NonNull String message) { event.getChannel().sendMessage(message).queue(); } + } diff --git a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandManager.java b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandManager.java index 9cb96624..d73153c8 100644 --- a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandManager.java +++ b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandManager.java @@ -45,6 +45,7 @@ import java.util.function.Function; * @param Command sender type */ public class JDACommandManager extends CommandManager { + private final long botId; private final Function<@NonNull C, @NonNull String> prefixMapper; @@ -63,12 +64,14 @@ public class JDACommandManager extends CommandManager { * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link MessageReceivedEvent} * @throws InterruptedException If the jda instance does not ready correctly */ - public JDACommandManager(final @NonNull JDA jda, - final @NonNull Function<@NonNull C, @NonNull String> prefixMapper, - final @Nullable BiFunction<@NonNull C, @NonNull String, @NonNull Boolean> permissionMapper, - final @NonNull Function, CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull Function<@NonNull MessageReceivedEvent, @NonNull C> commandSenderMapper, - final @NonNull Function<@NonNull C, @NonNull MessageReceivedEvent> backwardsCommandSenderMapper) + public JDACommandManager( + final @NonNull JDA jda, + final @NonNull Function<@NonNull C, @NonNull String> prefixMapper, + final @Nullable BiFunction<@NonNull C, @NonNull String, @NonNull Boolean> permissionMapper, + final @NonNull Function, CommandExecutionCoordinator> commandExecutionCoordinator, + final @NonNull Function<@NonNull MessageReceivedEvent, @NonNull C> commandSenderMapper, + final @NonNull Function<@NonNull C, @NonNull MessageReceivedEvent> backwardsCommandSenderMapper + ) throws InterruptedException { super(commandExecutionCoordinator, CommandRegistrationHandler.nullCommandRegistrationHandler()); this.prefixMapper = prefixMapper; @@ -130,4 +133,5 @@ public class JDACommandManager extends CommandManager { public final @NonNull CommandMeta createDefaultCommandMeta() { return SimpleCommandMeta.empty(); } + } diff --git a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandSender.java b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandSender.java index 969acc6a..579370ac 100644 --- a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandSender.java +++ b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDACommandSender.java @@ -31,6 +31,7 @@ import org.checkerframework.checker.nullness.qual.NonNull; * Wrapper for {@link MessageReceivedEvent} */ public class JDACommandSender { + private final MessageReceivedEvent event; /** @@ -42,15 +43,6 @@ public class JDACommandSender { this.event = event; } - /** - * Get the {@link MessageReceivedEvent} - * - * @return Message Received Event - */ - public @NonNull MessageReceivedEvent getEvent() { - return event; - } - /** * Create a JDA Command Sender from a {@link MessageReceivedEvent} * @@ -64,4 +56,14 @@ public class JDACommandSender { return new JDAGuildSender(event); } + + /** + * Get the {@link MessageReceivedEvent} + * + * @return Message Received Event + */ + public @NonNull MessageReceivedEvent getEvent() { + return event; + } + } diff --git a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAGuildSender.java b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAGuildSender.java index 6c9bb691..ba40a14b 100644 --- a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAGuildSender.java +++ b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAGuildSender.java @@ -34,4 +34,5 @@ public class JDAGuildSender extends JDACommandSender { JDAGuildSender(final @NonNull MessageReceivedEvent event) { super(event); } + } diff --git a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAPrivateSender.java b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAPrivateSender.java index 5c793318..46b5f436 100644 --- a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAPrivateSender.java +++ b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/JDAPrivateSender.java @@ -34,4 +34,5 @@ public class JDAPrivateSender extends JDACommandSender { JDAPrivateSender(final @NonNull MessageReceivedEvent event) { super(event); } + } diff --git a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/parsers/UserArgument.java b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/parsers/UserArgument.java index 0727d54f..9d91b8ac 100644 --- a/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/parsers/UserArgument.java +++ b/cloud-discord/cloud-jda/src/main/java/cloud/commandframework/jda/parsers/UserArgument.java @@ -43,10 +43,13 @@ import java.util.Queue; */ @SuppressWarnings("unused") public final class UserArgument extends CommandArgument { + private final List modes; - private UserArgument(final boolean required, final @NonNull String name, - final @NonNull JDA jda, final @NonNull List modes) { + private UserArgument( + final boolean required, final @NonNull String name, + final @NonNull JDA jda, final @NonNull List modes + ) { super(required, name, new UserParser<>(jda, modes), User.class); this.modes = modes; } @@ -105,6 +108,7 @@ public final class UserArgument extends CommandArgument { public static final class Builder extends CommandArgument.Builder { + private final JDA jda; private List modes = new ArrayList<>(); @@ -138,6 +142,7 @@ public final class UserArgument extends CommandArgument { public static final class UserParser implements ArgumentParser { + private final JDA jda; private final List modes; @@ -149,7 +154,8 @@ public final class UserArgument extends CommandArgument { @Override public @NonNull ArgumentParseResult parse( final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -218,6 +224,7 @@ public final class UserArgument extends CommandArgument { return ArgumentParseResult.success(user); } } + } @@ -242,10 +249,12 @@ public final class UserArgument extends CommandArgument { public final @NonNull String getInput() { return input; } + } public static final class TooManyUsersFoundParseException extends UserParseException { + /** * Construct a new UUID parse exception * @@ -259,10 +268,12 @@ public final class UserArgument extends CommandArgument { public @NonNull String getMessage() { return String.format("Too many users found for '%s'.", getInput()); } + } public static final class UserNotFoundParseException extends UserParseException { + /** * Construct a new UUID parse exception * @@ -276,5 +287,7 @@ public final class UserArgument extends CommandArgument { public @NonNull String getMessage() { return String.format("User not found for '%s'.", getInput()); } + } + } diff --git a/cloud-jline/src/main/java/cloud/commandframework/jline/JLineCommandManager.java b/cloud-jline/src/main/java/cloud/commandframework/jline/JLineCommandManager.java index f062a1da..43940461 100644 --- a/cloud-jline/src/main/java/cloud/commandframework/jline/JLineCommandManager.java +++ b/cloud-jline/src/main/java/cloud/commandframework/jline/JLineCommandManager.java @@ -54,8 +54,10 @@ public class JLineCommandManager extends CommandManager impl * * @param executionCoordinatorFunction Function producing a new coordinator */ - public JLineCommandManager(final @NonNull Function, - CommandExecutionCoordinator> executionCoordinatorFunction) { + public JLineCommandManager( + final @NonNull Function, + CommandExecutionCoordinator> executionCoordinatorFunction + ) { super(executionCoordinatorFunction, CommandRegistrationHandler.nullCommandRegistrationHandler()); } @@ -69,44 +71,44 @@ public class JLineCommandManager extends CommandManager impl final JLineCommandManager jLineCommandManager = new JLineCommandManager(CommandExecutionCoordinator.simpleCoordinator()); final Terminal terminal = TerminalBuilder.builder().build(); LineReader lineReader = LineReaderBuilder.builder() - .completer(jLineCommandManager) - .option(LineReader.Option.INSERT_TAB, false) - .terminal(terminal) - .appName("Test") - .build(); + .completer(jLineCommandManager) + .option(LineReader.Option.INSERT_TAB, false) + .terminal(terminal) + .appName("Test") + .build(); boolean[] shouldStop = new boolean[]{false}; jLineCommandManager.command( jLineCommandManager.commandBuilder("stop", SimpleCommandMeta.empty()) - .handler(commandContext -> - shouldStop[0] = true) - .build()) - .command(jLineCommandManager.commandBuilder("echo", SimpleCommandMeta.empty()) - .argument(String.class, "string", builder -> - builder.asRequired() - .withParser(((commandContext, inputQueue) -> { - final StringBuilder stringBuilder = - new StringBuilder(); - while (!inputQueue.isEmpty()) { - stringBuilder.append(inputQueue.remove()); - if (!inputQueue.isEmpty()) { - stringBuilder.append(" "); - } - } - return ArgumentParseResult.success( - stringBuilder.toString()); - })).build()) - .handler(commandContext -> commandContext.getOptional("string") - .ifPresent( - System.out::println)) - .build()) - .command(jLineCommandManager.commandBuilder("test", SimpleCommandMeta.empty()) - .argument(StaticArgument.of("one")) - .handler(commandContext -> System.out.println("Test (1)")) - .build()) - .command(jLineCommandManager.commandBuilder("test", SimpleCommandMeta.empty()) - .argument(StaticArgument.of("two")) - .handler(commandContext -> System.out.println("Test (2)")) - .build()); + .handler(commandContext -> + shouldStop[0] = true) + .build()) + .command(jLineCommandManager.commandBuilder("echo", SimpleCommandMeta.empty()) + .argument(String.class, "string", builder -> + builder.asRequired() + .withParser(((commandContext, inputQueue) -> { + final StringBuilder stringBuilder = + new StringBuilder(); + while (!inputQueue.isEmpty()) { + stringBuilder.append(inputQueue.remove()); + if (!inputQueue.isEmpty()) { + stringBuilder.append(" "); + } + } + return ArgumentParseResult.success( + stringBuilder.toString()); + })).build()) + .handler(commandContext -> commandContext.getOptional("string") + .ifPresent( + System.out::println)) + .build()) + .command(jLineCommandManager.commandBuilder("test", SimpleCommandMeta.empty()) + .argument(StaticArgument.of("one")) + .handler(commandContext -> System.out.println("Test (1)")) + .build()) + .command(jLineCommandManager.commandBuilder("test", SimpleCommandMeta.empty()) + .argument(StaticArgument.of("two")) + .handler(commandContext -> System.out.println("Test (2)")) + .build()); System.out.println("Ready..."); while (!shouldStop[0]) { final String line = lineReader.readLine(); @@ -138,9 +140,11 @@ public class JLineCommandManager extends CommandManager impl } @Override - public final void complete(final @NonNull LineReader lineReader, - final @NonNull ParsedLine parsedLine, - final @NonNull List<@NonNull Candidate> list) { + public final void complete( + final @NonNull LineReader lineReader, + final @NonNull ParsedLine parsedLine, + final @NonNull List<@NonNull Candidate> list + ) { final String line = parsedLine.line(); if (line == null || line.isEmpty() || !line.startsWith("/")) { System.out.println("Cannot suggest: empty line"); @@ -155,8 +159,10 @@ public class JLineCommandManager extends CommandManager impl } @Override - public final boolean hasPermission(final @NonNull JLineCommandSender sender, - final @NonNull String permission) { + public final boolean hasPermission( + final @NonNull JLineCommandSender sender, + final @NonNull String permission + ) { return true; } diff --git a/cloud-minecraft/cloud-brigadier/src/main/java/cloud/commandframework/brigadier/CloudBrigadierManager.java b/cloud-minecraft/cloud-brigadier/src/main/java/cloud/commandframework/brigadier/CloudBrigadierManager.java index 963b279c..49d05c16 100644 --- a/cloud-minecraft/cloud-brigadier/src/main/java/cloud/commandframework/brigadier/CloudBrigadierManager.java +++ b/cloud-minecraft/cloud-brigadier/src/main/java/cloud/commandframework/brigadier/CloudBrigadierManager.java @@ -95,9 +95,10 @@ public final class CloudBrigadierManager { * @param commandManager Command manager * @param dummyContextProvider Provider of dummy context for completions */ - public CloudBrigadierManager(final @NonNull CommandManager commandManager, - final @NonNull Supplier<@NonNull CommandContext> - dummyContextProvider) { + public CloudBrigadierManager( + final @NonNull CommandManager commandManager, + final @NonNull Supplier<@NonNull CommandContext> dummyContextProvider + ) { this.mappers = new HashMap<>(); this.defaultArgumentTypeSuppliers = new HashMap<>(); this.commandManager = commandManager; @@ -199,10 +200,12 @@ public final class CloudBrigadierManager { * @param cloud argument type * @param Brigadier argument type value */ - public , O> void registerMapping(final @NonNull TypeToken argumentType, - final boolean nativeSuggestions, - final @NonNull Function<@NonNull ? extends K, - @NonNull ? extends ArgumentType> mapper) { + public , O> void registerMapping( + final @NonNull TypeToken argumentType, + final boolean nativeSuggestions, + final @NonNull Function<@NonNull ? extends K, + @NonNull ? extends ArgumentType> mapper + ) { this.mappers.put(GenericTypeReflector.erase(argumentType.getType()), Pair.of(mapper, nativeSuggestions)); } @@ -212,8 +215,10 @@ public final class CloudBrigadierManager { * @param clazz Type to map * @param supplier Supplier that supplies the argument type */ - public void registerDefaultArgumentTypeSupplier(final @NonNull Class clazz, - final @NonNull Supplier<@Nullable ArgumentType> supplier) { + public void registerDefaultArgumentTypeSupplier( + final @NonNull Class clazz, + final @NonNull Supplier<@Nullable ArgumentType> supplier + ) { this.defaultArgumentTypeSuppliers.put(clazz, supplier); } @@ -221,19 +226,23 @@ public final class CloudBrigadierManager { private > @Nullable Pair<@NonNull ArgumentType, @NonNull Boolean> getArgument( final @NonNull TypeToken valueType, final @NonNull TypeToken argumentType, - final @NonNull K argument) { + final @NonNull K argument + ) { final ArgumentParser commandArgument = (ArgumentParser) argument; final Pair pair = this.mappers.get(GenericTypeReflector.erase(argumentType.getType())); if (pair == null || pair.getFirst() == null) { return this.createDefaultMapper(valueType, commandArgument); } - return Pair.of((ArgumentType) ((Function) pair.getFirst()).apply(commandArgument), - (boolean) pair.getSecond()); + return Pair.of( + (ArgumentType) ((Function) pair.getFirst()).apply(commandArgument), + (boolean) pair.getSecond() + ); } private > @NonNull Pair<@NonNull ArgumentType, @NonNull Boolean> createDefaultMapper( final @NonNull TypeToken clazz, - final @NonNull ArgumentParser argument) { + final @NonNull ArgumentParser argument + ) { final Supplier> argumentTypeSupplier = this.defaultArgumentTypeSuppliers .get(GenericTypeReflector.erase(clazz.getType())); final @Nullable ArgumentType defaultType; @@ -258,20 +267,24 @@ public final class CloudBrigadierManager { * @param executor Command executor * @return Literal command node */ - public @NonNull LiteralCommandNode createLiteralCommandNode(final @NonNull String label, - final @NonNull Command cloudCommand, - final @NonNull BiPredicate<@NonNull S, - @NonNull CommandPermission> permissionChecker, - final boolean forceRegister, - final com.mojang.brigadier.@NonNull Command executor) { + public @NonNull LiteralCommandNode createLiteralCommandNode( + final @NonNull String label, + final @NonNull Command cloudCommand, + final @NonNull BiPredicate<@NonNull S, + @NonNull CommandPermission> permissionChecker, + final boolean forceRegister, + final com.mojang.brigadier.@NonNull Command executor + ) { final CommandTree.Node> node = this.commandManager .getCommandTree().getNamedNode(cloudCommand.getArguments().get(0).getName()); final SuggestionProvider provider = (context, builder) -> this.buildSuggestions(node.getValue(), context, builder); final LiteralArgumentBuilder literalArgumentBuilder = LiteralArgumentBuilder .literal(label) .requires(sender -> permissionChecker.test(sender, (CommandPermission) node.getNodeMeta() - .getOrDefault("permission", - Permission.empty()))); + .getOrDefault( + "permission", + Permission.empty() + ))); if (forceRegister || (node.getValue() != null && node.getValue().getOwningCommand() != null)) { literalArgumentBuilder.executes(executor); } @@ -279,7 +292,8 @@ public final class CloudBrigadierManager { final LiteralCommandNode constructedRoot = literalArgumentBuilder.build(); for (final CommandTree.Node> child : node.getChildren()) { constructedRoot.addChild(this.constructCommandNode(forceRegister, child, - permissionChecker, executor, provider).build()); + permissionChecker, executor, provider + ).build()); } return constructedRoot; } @@ -299,19 +313,25 @@ public final class CloudBrigadierManager { final @NonNull LiteralCommandNode root, final @NonNull SuggestionProvider suggestionProvider, final com.mojang.brigadier.@NonNull Command executor, - final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker) { + final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker + ) { final LiteralArgumentBuilder literalArgumentBuilder = LiteralArgumentBuilder.literal(root.getLiteral()) - .requires(sender -> permissionChecker.test(sender, - (CommandPermission) cloudCommand.getNodeMeta() - .getOrDefault("permission", - Permission.empty()))); + .requires(sender -> permissionChecker.test( + sender, + (CommandPermission) cloudCommand.getNodeMeta() + .getOrDefault( + "permission", + Permission.empty() + ) + )); if (cloudCommand.getValue() != null && cloudCommand.getValue().getOwningCommand() != null) { literalArgumentBuilder.executes(executor); } final LiteralCommandNode constructedRoot = literalArgumentBuilder.build(); for (final CommandTree.Node> child : cloudCommand.getChildren()) { constructedRoot.addChild(this.constructCommandNode(false, child, permissionChecker, - executor, suggestionProvider).build()); + executor, suggestionProvider + ).build()); } return constructedRoot; } @@ -321,10 +341,10 @@ public final class CloudBrigadierManager { final CommandTree.@NonNull Node> root, final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker, final com.mojang.brigadier.@NonNull Command executor, - final SuggestionProvider suggestionProvider) { + final SuggestionProvider suggestionProvider + ) { if (root.getValue() instanceof CompoundArgument) { - @SuppressWarnings("unchecked") - final CompoundArgument compoundArgument = (CompoundArgument) root.getValue(); + @SuppressWarnings("unchecked") final CompoundArgument compoundArgument = (CompoundArgument) root.getValue(); final Object[] parsers = compoundArgument.getParserTuple().toArray(); final Object[] types = compoundArgument.getTypes().toArray(); final Object[] names = compoundArgument.getNames().toArray(); @@ -334,18 +354,24 @@ public final class CloudBrigadierManager { for (int i = parsers.length - 1; i >= 0; i--) { @SuppressWarnings("unchecked") final ArgumentParser parser = (ArgumentParser) parsers[i]; - final Pair, Boolean> pair = this.getArgument(TypeToken.get((Class) types[i]), - TypeToken.get(parser.getClass()), - parser); + final Pair, Boolean> pair = this.getArgument( + TypeToken.get((Class) types[i]), + TypeToken.get(parser.getClass()), + parser + ); final SuggestionProvider provider = pair.getSecond() ? null : suggestionProvider; final ArgumentBuilder fragmentBuilder = RequiredArgumentBuilder .argument((String) names[i], (ArgumentType) pair.getFirst()) .suggests(provider) - .requires(sender -> permissionChecker.test(sender, - (CommandPermission) root.getNodeMeta() - .getOrDefault("permission", - Permission.empty()))); + .requires(sender -> permissionChecker.test( + sender, + (CommandPermission) root.getNodeMeta() + .getOrDefault( + "permission", + Permission.empty() + ) + )); argumentBuilders[i] = fragmentBuilder; if (forceExecutor || (i == parsers.length - 1) && (root.isLeaf() || !root.getValue().isRequired())) { @@ -369,24 +395,33 @@ public final class CloudBrigadierManager { if (root.getValue() instanceof StaticArgument) { argumentBuilder = LiteralArgumentBuilder.literal(root.getValue().getName()) .requires(sender -> permissionChecker.test(sender, (CommandPermission) root.getNodeMeta() - .getOrDefault("permission", - Permission.empty()))) + .getOrDefault( + "permission", + Permission.empty() + ))) .executes(executor); } else { - final Pair, Boolean> pair = this.getArgument(root.getValue().getValueType(), - TypeToken.get(root.getValue().getParser().getClass()), - root.getValue().getParser()); + final Pair, Boolean> pair = this.getArgument( + root.getValue().getValueType(), + TypeToken.get(root.getValue().getParser().getClass()), + root.getValue().getParser() + ); final SuggestionProvider provider = pair.getSecond() - ? null - : (context, builder) -> this.buildSuggestions(root.getValue(), - context, builder); + ? null + : (context, builder) -> this.buildSuggestions(root.getValue(), + context, builder + ); argumentBuilder = RequiredArgumentBuilder .argument(root.getValue().getName(), (ArgumentType) pair.getFirst()) .suggests(provider) - .requires(sender -> permissionChecker.test(sender, - (CommandPermission) root.getNodeMeta() - .getOrDefault("permission", - Permission.empty()))); + .requires(sender -> permissionChecker.test( + sender, + (CommandPermission) root.getNodeMeta() + .getOrDefault( + "permission", + Permission.empty() + ) + )); } if (forceExecutor || root.isLeaf() || !root.getValue().isRequired()) { argumentBuilder.executes(executor); @@ -400,7 +435,8 @@ public final class CloudBrigadierManager { private @NonNull CompletableFuture buildSuggestions( final @NonNull CommandArgument argument, final com.mojang.brigadier.context.@NonNull CommandContext s, - final @NonNull SuggestionsBuilder builder) { + final @NonNull SuggestionsBuilder builder + ) { final CommandContext commandContext = this.dummyContextProvider.get(); final LinkedList inputQueue = new LinkedList<>(Collections.singletonList(builder.getInput())); final CommandPreprocessingContext commandPreprocessingContext = diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitBrigadierMapper.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitBrigadierMapper.java index 8baa6c29..c630d56a 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitBrigadierMapper.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitBrigadierMapper.java @@ -61,8 +61,10 @@ public final class BukkitBrigadierMapper { * @param commandManager The {@link BukkitCommandManager} to use for mapping * @param brigadierManager The {@link CloudBrigadierManager} to use for mapping */ - public BukkitBrigadierMapper(final @NonNull BukkitCommandManager commandManager, - final @NonNull CloudBrigadierManager brigadierManager) { + public BukkitBrigadierMapper( + final @NonNull BukkitCommandManager commandManager, + final @NonNull CloudBrigadierManager brigadierManager + ) { this.commandManager = commandManager; this.brigadierManager = brigadierManager; @@ -90,8 +92,8 @@ public final class BukkitBrigadierMapper { this.mapComplexNMS(MultiplePlayerSelector.class, this.getEntitySelectorArgument(false, true)); } catch (final Exception e) { this.commandManager.getOwningPlugin() - .getLogger() - .log(Level.WARNING, "Failed to map Bukkit types to NMS argument types", e); + .getLogger() + .log(Level.WARNING, "Failed to map Bukkit types to NMS argument types", e); } } @@ -100,8 +102,10 @@ public final class BukkitBrigadierMapper { * @param playersOnly Whether the selector is for players only (true), or for all entities (false) * @return The NMS ArgumentType */ - private Supplier> getEntitySelectorArgument(final boolean single, - final boolean playersOnly) { + private Supplier> getEntitySelectorArgument( + final boolean single, + final boolean playersOnly + ) { return () -> { try { final Constructor constructor = this.getNMSArgument("Entity").getDeclaredConstructors()[0]; @@ -132,8 +136,10 @@ public final class BukkitBrigadierMapper { * @param type Type to map * @param constructor Constructor that construct the NMS argument type */ - public void mapSimpleNMS(final @NonNull Class type, - final @NonNull Constructor constructor) { + public void mapSimpleNMS( + final @NonNull Class type, + final @NonNull Constructor constructor + ) { try { this.brigadierManager.registerDefaultArgumentTypeSupplier(type, () -> { try { @@ -145,9 +151,11 @@ public final class BukkitBrigadierMapper { }); } catch (final Exception e) { this.commandManager.getOwningPlugin() - .getLogger() - .warning(String.format("Failed to map '%s' to a Mojang serializable argument type", - type.getCanonicalName())); + .getLogger() + .warning(String.format( + "Failed to map '%s' to a Mojang serializable argument type", + type.getCanonicalName() + )); } } @@ -157,15 +165,20 @@ public final class BukkitBrigadierMapper { * @param type Type to map * @param argumentTypeSupplier Supplier of the NMS argument type */ - public void mapComplexNMS(final @NonNull Class type, - final @NonNull Supplier> argumentTypeSupplier) { + public void mapComplexNMS( + final @NonNull Class type, + final @NonNull Supplier> argumentTypeSupplier + ) { try { this.brigadierManager.registerDefaultArgumentTypeSupplier(type, argumentTypeSupplier); } catch (final Exception e) { this.commandManager.getOwningPlugin() - .getLogger() - .warning(String.format("Failed to map '%s' to a Mojang serializable argument type", - type.getCanonicalName())); + .getLogger() + .warning(String.format( + "Failed to map '%s' to a Mojang serializable argument type", + type.getCanonicalName() + )); } } + } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommand.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommand.java index ce20b4f5..daeba9bd 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommand.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommand.java @@ -51,83 +51,91 @@ final class BukkitCommand extends org.bukkit.command.Command implements Plugi private final Command cloudCommand; @SuppressWarnings("unchecked") - BukkitCommand(final @NonNull String label, - final @NonNull List<@NonNull String> aliases, - final @NonNull Command cloudCommand, - final @NonNull CommandArgument command, - final @NonNull BukkitCommandManager manager) { - super(label, - cloudCommand.getCommandMeta().getOrDefault("description", ""), - "", - aliases); + BukkitCommand( + final @NonNull String label, + final @NonNull List<@NonNull String> aliases, + final @NonNull Command cloudCommand, + final @NonNull CommandArgument command, + final @NonNull BukkitCommandManager manager + ) { + super( + label, + cloudCommand.getCommandMeta().getOrDefault("description", ""), + "", + aliases + ); this.command = command; this.manager = manager; this.cloudCommand = cloudCommand; } @Override - public boolean execute(final @NonNull CommandSender commandSender, - final @NonNull String s, - final @NonNull String @NonNull [] strings) { + public boolean execute( + final @NonNull CommandSender commandSender, + final @NonNull String s, + final @NonNull String @NonNull [] strings + ) { /* Join input */ final StringBuilder builder = new StringBuilder(this.command.getName()); for (final String string : strings) { builder.append(" ").append(string); } final C sender = this.manager.getCommandSenderMapper().apply(commandSender); - this.manager.executeCommand(sender, - builder.toString()) - .whenComplete(((commandResult, throwable) -> { - if (throwable != null) { - if (throwable instanceof CompletionException) { - throwable = throwable.getCause(); - } - final Throwable finalThrowable = throwable; - if (throwable instanceof InvalidSyntaxException) { - this.manager.handleException(sender, - InvalidSyntaxException.class, - (InvalidSyntaxException) throwable, (c, e) -> - commandSender.sendMessage( - ChatColor.RED + "Invalid Command Syntax. " - + "Correct command syntax is: " - + ChatColor.GRAY + "/" - + ((InvalidSyntaxException) finalThrowable) - .getCorrectSyntax()) - ); - } else if (throwable instanceof InvalidCommandSenderException) { - this.manager.handleException(sender, - InvalidCommandSenderException.class, - (InvalidCommandSenderException) throwable, (c, e) -> - commandSender.sendMessage( - ChatColor.RED + finalThrowable.getMessage()) - ); - } else if (throwable instanceof NoPermissionException) { - this.manager.handleException(sender, - NoPermissionException.class, - (NoPermissionException) throwable, (c, e) -> - commandSender.sendMessage(MESSAGE_NO_PERMS) - ); - } else if (throwable instanceof NoSuchCommandException) { - this.manager.handleException(sender, - NoSuchCommandException.class, - (NoSuchCommandException) throwable, (c, e) -> - commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND) - ); - } else if (throwable instanceof ArgumentParseException) { - this.manager.handleException(sender, - ArgumentParseException.class, - (ArgumentParseException) throwable, (c, e) -> - commandSender.sendMessage( - ChatColor.RED + "Invalid Command Argument: " - + ChatColor.GRAY + finalThrowable.getCause() - .getMessage()) - ); - } else { - commandSender.sendMessage(throwable.getMessage()); - throwable.printStackTrace(); - } + this.manager.executeCommand( + sender, + builder.toString() + ) + .whenComplete(((commandResult, throwable) -> { + if (throwable != null) { + if (throwable instanceof CompletionException) { + throwable = throwable.getCause(); } - })); + final Throwable finalThrowable = throwable; + if (throwable instanceof InvalidSyntaxException) { + this.manager.handleException(sender, + InvalidSyntaxException.class, + (InvalidSyntaxException) throwable, (c, e) -> + commandSender.sendMessage( + ChatColor.RED + "Invalid Command Syntax. " + + "Correct command syntax is: " + + ChatColor.GRAY + "/" + + ((InvalidSyntaxException) finalThrowable) + .getCorrectSyntax()) + ); + } else if (throwable instanceof InvalidCommandSenderException) { + this.manager.handleException(sender, + InvalidCommandSenderException.class, + (InvalidCommandSenderException) throwable, (c, e) -> + commandSender.sendMessage( + ChatColor.RED + finalThrowable.getMessage()) + ); + } else if (throwable instanceof NoPermissionException) { + this.manager.handleException(sender, + NoPermissionException.class, + (NoPermissionException) throwable, (c, e) -> + commandSender.sendMessage(MESSAGE_NO_PERMS) + ); + } else if (throwable instanceof NoSuchCommandException) { + this.manager.handleException(sender, + NoSuchCommandException.class, + (NoSuchCommandException) throwable, (c, e) -> + commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND) + ); + } else if (throwable instanceof ArgumentParseException) { + this.manager.handleException(sender, + ArgumentParseException.class, + (ArgumentParseException) throwable, (c, e) -> + commandSender.sendMessage( + ChatColor.RED + "Invalid Command Argument: " + + ChatColor.GRAY + finalThrowable.getCause() + .getMessage()) + ); + } else { + commandSender.sendMessage(throwable.getMessage()); + throwable.printStackTrace(); + } + } + })); return true; } @@ -137,16 +145,20 @@ final class BukkitCommand extends org.bukkit.command.Command implements Plugi } @Override - public List tabComplete(final @NonNull CommandSender sender, - final @NonNull String alias, - final @NonNull String @NonNull [] args) + public List tabComplete( + final @NonNull CommandSender sender, + final @NonNull String alias, + final @NonNull String @NonNull [] args + ) throws IllegalArgumentException { final StringBuilder builder = new StringBuilder(this.command.getName()); for (final String string : args) { builder.append(" ").append(string); } - return this.manager.suggest(this.manager.getCommandSenderMapper().apply(sender), - builder.toString()); + return this.manager.suggest( + this.manager.getCommandSenderMapper().apply(sender), + builder.toString() + ); } @Override diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommandManager.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommandManager.java index dda1c222..2aaa44b1 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommandManager.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitCommandManager.java @@ -89,11 +89,13 @@ public class BukkitCommandManager extends CommandManager { * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender} * @throws Exception If the construction of the manager fails */ - public BukkitCommandManager(final @NonNull Plugin owningPlugin, - final @NonNull Function<@NonNull CommandTree, - @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, - final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper) + public BukkitCommandManager( + final @NonNull Plugin owningPlugin, + final @NonNull Function<@NonNull CommandTree, + @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, + final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, + final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper + ) throws Exception { super(commandExecutionCoordinator, new BukkitPluginRegistrationHandler<>()); ((BukkitPluginRegistrationHandler) this.getCommandRegistrationHandler()).initialize(this); @@ -108,14 +110,16 @@ public class BukkitCommandManager extends CommandManager { int version = -1; try { final Matcher matcher = Pattern.compile("\\(MC: (\\d)\\.(\\d+)\\.?(\\d+?)?\\)") - .matcher(Bukkit.getVersion()); + .matcher(Bukkit.getVersion()); if (matcher.find()) { - version = Integer.parseInt(matcher.toMatchResult().group(2), - VERSION_RADIX); + version = Integer.parseInt( + matcher.toMatchResult().group(2), + VERSION_RADIX + ); } } catch (final Exception e) { this.owningPlugin.getLogger().severe("Failed to determine Minecraft version " - + "for cloud Bukkit capability detection"); + + "for cloud Bukkit capability detection"); } this.minecraftVersion = version; @@ -132,13 +136,17 @@ public class BukkitCommandManager extends CommandManager { /* Register Bukkit Parsers */ this.getParserRegistry().registerParserSupplier(TypeToken.get(World.class), params -> new WorldArgument.WorldParser<>()); - this.getParserRegistry().registerParserSupplier(TypeToken.get(Material.class), - params -> new MaterialArgument.MaterialParser<>()); + this.getParserRegistry().registerParserSupplier( + TypeToken.get(Material.class), + params -> new MaterialArgument.MaterialParser<>() + ); this.getParserRegistry() - .registerParserSupplier(TypeToken.get(Player.class), params -> new PlayerArgument.PlayerParser<>()); + .registerParserSupplier(TypeToken.get(Player.class), params -> new PlayerArgument.PlayerParser<>()); this.getParserRegistry() - .registerParserSupplier(TypeToken.get(OfflinePlayer.class), - params -> new OfflinePlayerArgument.OfflinePlayerParser<>()); + .registerParserSupplier( + TypeToken.get(OfflinePlayer.class), + params -> new OfflinePlayerArgument.OfflinePlayerParser<>() + ); /* Register Entity Selector Parsers */ this.getParserRegistry().registerParserSupplier(TypeToken.get(SingleEntitySelector.class), parserParameters -> new SingleEntitySelectorArgument.SingleEntitySelectorParser<>()); @@ -195,18 +203,20 @@ public class BukkitCommandManager extends CommandManager { return this.backwardsCommandSenderMapper.apply(sender).hasPermission(permission); } - protected final void setSplitAliases(final boolean value) { - this.splitAliases = value; - } - protected final boolean getSplitAliases() { return this.splitAliases; } + protected final void setSplitAliases(final boolean value) { + this.splitAliases = value; + } + protected final void checkBrigadierCompatibility() throws BrigadierFailureException { if (!this.queryCapability(CloudBukkitCapabilities.BRIGADIER)) { - throw new BrigadierFailureException(BrigadierFailureReason.VERSION_TOO_LOW, - new IllegalArgumentException("Version: " + this.minecraftVersion)); + throw new BrigadierFailureException( + BrigadierFailureReason.VERSION_TOO_LOW, + new IllegalArgumentException("Version: " + this.minecraftVersion) + ); } } @@ -229,21 +239,27 @@ public class BukkitCommandManager extends CommandManager { if (this.paper) { if (this.minecraftVersion >= ASYNC_TAB_MINIMUM_VERSION) { if (this.minecraftVersion >= PAPER_BRIGADIER_VERSION) { - return EnumSet.of(CloudBukkitCapabilities.NATIVE_BRIGADIER, - CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION, - CloudBukkitCapabilities.BRIGADIER); + return EnumSet.of( + CloudBukkitCapabilities.NATIVE_BRIGADIER, + CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION, + CloudBukkitCapabilities.BRIGADIER + ); } else if (this.minecraftVersion >= BRIGADIER_MINIMUM_VERSION) { - return EnumSet.of(CloudBukkitCapabilities.COMMODORE_BRIGADIER, - CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION, - CloudBukkitCapabilities.BRIGADIER); + return EnumSet.of( + CloudBukkitCapabilities.COMMODORE_BRIGADIER, + CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION, + CloudBukkitCapabilities.BRIGADIER + ); } else { return EnumSet.of(CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION); } } } else { if (this.minecraftVersion >= BRIGADIER_MINIMUM_VERSION) { - return EnumSet.of(CloudBukkitCapabilities.COMMODORE_BRIGADIER, - CloudBukkitCapabilities.BRIGADIER); + return EnumSet.of( + CloudBukkitCapabilities.COMMODORE_BRIGADIER, + CloudBukkitCapabilities.BRIGADIER + ); } } return EnumSet.noneOf(CloudBukkitCapabilities.class); @@ -320,9 +336,11 @@ public class BukkitCommandManager extends CommandManager { @Override public String getMessage() { - return String.format("Could not initialize Brigadier mappings. Reason: %s (%s)", - this.reason.name().toLowerCase().replace("_", " "), - this.getCause() == null ? "" : this.getCause().getMessage()); + return String.format( + "Could not initialize Brigadier mappings. Reason: %s (%s)", + this.reason.name().toLowerCase().replace("_", " "), + this.getCause() == null ? "" : this.getCause().getMessage() + ); } } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPlayerSender.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPlayerSender.java index d740dee5..04764c5b 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPlayerSender.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPlayerSender.java @@ -41,4 +41,5 @@ final class BukkitPlayerSender extends BukkitCommandSender { public @NonNull Player asPlayer() { return (Player) this.getInternalSender(); } + } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPluginRegistrationHandler.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPluginRegistrationHandler.java index 06f8b8a9..dc46b4b4 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPluginRegistrationHandler.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitPluginRegistrationHandler.java @@ -79,7 +79,8 @@ public class BukkitPluginRegistrationHandler implements CommandRegistrationHa final String label; final String prefixedLabel = String.format("%s:%s", this.bukkitCommandManager.getOwningPlugin().getName(), - commandArgument.getName()).toLowerCase(); + commandArgument.getName() + ).toLowerCase(); if (!(this.bukkitCommandManager.getCommandRegistrationHandler() instanceof CloudCommodoreManager) && bukkitCommands.containsKey(commandArgument.getName())) { label = prefixedLabel; @@ -87,8 +88,7 @@ public class BukkitPluginRegistrationHandler implements CommandRegistrationHa label = commandArgument.getName(); } - @SuppressWarnings("unchecked") - final List aliases = new ArrayList<>(((StaticArgument) commandArgument).getAlternativeAliases()); + @SuppressWarnings("unchecked") final List aliases = new ArrayList<>(((StaticArgument) commandArgument).getAlternativeAliases()); if (!label.contains(":")) { aliases.add(prefixedLabel); @@ -99,11 +99,14 @@ public class BukkitPluginRegistrationHandler implements CommandRegistrationHa (this.bukkitCommandManager.getSplitAliases() ? Collections.emptyList() : aliases), (Command) command, (CommandArgument) commandArgument, - this.bukkitCommandManager); + this.bukkitCommandManager + ); this.registeredCommands.put(commandArgument, bukkitCommand); - this.commandMap.register(label, - this.bukkitCommandManager.getOwningPlugin().getName().toLowerCase(), - bukkitCommand); + this.commandMap.register( + label, + this.bukkitCommandManager.getOwningPlugin().getName().toLowerCase(), + bukkitCommand + ); this.registerExternal(label, command, bukkitCommand); this.recognizedAliases.add(label); @@ -115,10 +118,12 @@ public class BukkitPluginRegistrationHandler implements CommandRegistrationHa Collections.emptyList(), (Command) command, (CommandArgument) commandArgument, - this.bukkitCommandManager); + this.bukkitCommandManager + ); this.commandMap.register(alias, this.bukkitCommandManager.getOwningPlugin() - .getName().toLowerCase(), - bukkitCommand); + .getName().toLowerCase(), + bukkitCommand + ); this.registerExternal(alias, command, aliasCommand); this.recognizedAliases.add(alias); } @@ -138,9 +143,11 @@ public class BukkitPluginRegistrationHandler implements CommandRegistrationHa return this.recognizedAliases.contains(alias); } - protected void registerExternal(final @NonNull String label, - final @NonNull Command command, - final @NonNull BukkitCommand bukkitCommand) { + protected void registerExternal( + final @NonNull String label, + final @NonNull Command command, + final @NonNull BukkitCommand bukkitCommand + ) { } } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitSynchronizer.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitSynchronizer.java index f919b8d3..203d722b 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitSynchronizer.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/BukkitSynchronizer.java @@ -41,12 +41,12 @@ final class BukkitSynchronizer implements TaskSynchronizer { @Override public CompletableFuture runSynchronous(final @NonNull I input, final @NonNull TaskConsumer consumer) { - final CompletableFuture future = new CompletableFuture<>(); - this.plugin.getServer().getScheduler().runTask(this.plugin, () -> { - consumer.accept(input); - future.complete(null); - }); - return future; + final CompletableFuture future = new CompletableFuture<>(); + this.plugin.getServer().getScheduler().runTask(this.plugin, () -> { + consumer.accept(input); + future.complete(null); + }); + return future; } @Override diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudBukkitCapabilities.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudBukkitCapabilities.java index 1e424152..3ec72767 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudBukkitCapabilities.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudBukkitCapabilities.java @@ -27,5 +27,8 @@ package cloud.commandframework.bukkit; * Capabilities for the Bukkit module */ public enum CloudBukkitCapabilities { - BRIGADIER, COMMODORE_BRIGADIER, NATIVE_BRIGADIER, ASYNCHRONOUS_COMPLETION + BRIGADIER, + COMMODORE_BRIGADIER, + NATIVE_BRIGADIER, + ASYNCHRONOUS_COMPLETION } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudCommodoreManager.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudCommodoreManager.java index 6be11bd0..4b3b89c4 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudCommodoreManager.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/CloudCommodoreManager.java @@ -49,7 +49,7 @@ class CloudCommodoreManager extends BukkitPluginRegistrationHandler { throws BukkitCommandManager.BrigadierFailureException { if (!CommodoreProvider.isSupported()) { throw new BukkitCommandManager.BrigadierFailureException(BukkitCommandManager - .BrigadierFailureReason.COMMODORE_NOT_PRESENT); + .BrigadierFailureReason.COMMODORE_NOT_PRESENT); } this.commandManager = commandManager; this.commodore = CommodoreProvider.getCommodore(commandManager.getOwningPlugin()); @@ -59,21 +59,27 @@ class CloudCommodoreManager extends BukkitPluginRegistrationHandler { } @Override - protected void registerExternal(final @NonNull String label, - final @NonNull Command command, - final @NonNull BukkitCommand bukkitCommand) { + protected void registerExternal( + final @NonNull String label, + final @NonNull Command command, + final @NonNull BukkitCommand bukkitCommand + ) { this.registerWithCommodore(label, command); this.registerWithCommodore(String.format("%s:%s", bukkitCommand.getPlugin().getName(), label).toLowerCase(), command); } - private void registerWithCommodore(final @NonNull String label, - final @NonNull Command command) { + private void registerWithCommodore( + final @NonNull String label, + final @NonNull Command command + ) { final com.mojang.brigadier.Command cmd = o -> 1; final LiteralCommandNode literalCommandNode = this.brigadierManager .createLiteralCommandNode(label, command, (o, p) -> { final CommandSender sender = this.commodore.getBukkitSender(o); - return this.commandManager.hasPermission(this.commandManager.getCommandSenderMapper().apply(sender), - (CommandPermission) p); + return this.commandManager.hasPermission( + this.commandManager.getCommandSenderMapper().apply(sender), + (CommandPermission) p + ); }, false, cmd); final CommandNode existingNode = this.commodore.getDispatcher().findNode(Collections.singletonList(label)); if (existingNode != null) { diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/EntitySelector.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/EntitySelector.java index 1fada9e1..372f4542 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/EntitySelector.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/EntitySelector.java @@ -43,8 +43,10 @@ public abstract class EntitySelector { * @param selector The input string used to create this selector * @param entities The List of Bukkit {@link Entity entities} to construct the {@link EntitySelector} from */ - public EntitySelector(final @NonNull String selector, - final @NonNull List<@NonNull Entity> entities) { + public EntitySelector( + final @NonNull String selector, + final @NonNull List<@NonNull Entity> entities + ) { this.selector = selector; this.entities = entities; } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultipleEntitySelector.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultipleEntitySelector.java index 8f474573..423c33d7 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultipleEntitySelector.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultipleEntitySelector.java @@ -34,8 +34,10 @@ public class MultipleEntitySelector extends EntitySelector { * @param selector The input string used to create this selector * @param entities The List of Bukkit {@link Entity}s to construct the {@link EntitySelector} from */ - public MultipleEntitySelector(final @NonNull String selector, - final @NonNull List<@NonNull Entity> entities) { + public MultipleEntitySelector( + final @NonNull String selector, + final @NonNull List<@NonNull Entity> entities + ) { super(selector, entities); } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultiplePlayerSelector.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultiplePlayerSelector.java index c1aebb56..ce5c1120 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultiplePlayerSelector.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/MultiplePlayerSelector.java @@ -42,8 +42,10 @@ public class MultiplePlayerSelector extends MultipleEntitySelector { * @param selector The input string used to create this selector * @param entities The List of Bukkit {@link Entity}s to construct the {@link EntitySelector} from */ - public MultiplePlayerSelector(final @NonNull String selector, - final @NonNull List<@NonNull Entity> entities) { + public MultiplePlayerSelector( + final @NonNull String selector, + final @NonNull List<@NonNull Entity> entities + ) { super(selector, entities); entities.forEach(e -> { if (e.getType() != EntityType.PLAYER) { diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SingleEntitySelector.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SingleEntitySelector.java index 137aed28..d2e84031 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SingleEntitySelector.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SingleEntitySelector.java @@ -36,8 +36,10 @@ public final class SingleEntitySelector extends MultipleEntitySelector { * @param selector The input string used to create this selector * @param entities The List of Bukkit {@link Entity entities} to construct the {@link EntitySelector} from */ - public SingleEntitySelector(final @NonNull String selector, - final @NonNull List<@NonNull Entity> entities) { + public SingleEntitySelector( + final @NonNull String selector, + final @NonNull List<@NonNull Entity> entities + ) { super(selector, entities); if (entities.size() > 1) { throw new IllegalArgumentException("More than 1 entity selected in single entity selector."); diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SinglePlayerSelector.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SinglePlayerSelector.java index 1abf89e8..bb0676c2 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SinglePlayerSelector.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/arguments/selector/SinglePlayerSelector.java @@ -37,8 +37,10 @@ public final class SinglePlayerSelector extends MultiplePlayerSelector { * @param selector The input string used to create this selector * @param entities The List of Bukkit {@link Entity entities} to construct the {@link EntitySelector} from */ - public SinglePlayerSelector(final @NonNull String selector, - final @NonNull List<@NonNull Entity> entities) { + public SinglePlayerSelector( + final @NonNull String selector, + final @NonNull List<@NonNull Entity> entities + ) { super(selector, entities); if (getPlayers().size() > 1) { throw new IllegalArgumentException("More than 1 player selected in single player selector."); diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/MaterialArgument.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/MaterialArgument.java index 48805b04..3747bd11 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/MaterialArgument.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/MaterialArgument.java @@ -44,11 +44,13 @@ import java.util.stream.Collectors; */ public class MaterialArgument extends CommandArgument { - protected MaterialArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + protected MaterialArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new MaterialParser<>(), defaultValue, Material.class, suggestionsProvider); } @@ -93,8 +95,10 @@ public class MaterialArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull Material material) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull Material material + ) { return MaterialArgument.newBuilder(name).asOptionalWithDefault(material.name().toLowerCase()).build(); } @@ -110,8 +114,10 @@ public class MaterialArgument extends CommandArgument { public static final class MaterialParser implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -154,8 +160,9 @@ public class MaterialArgument extends CommandArgument { @Override public String getMessage() { return EnumSet.allOf(Material.class).stream().map(Material::name).map(String::toLowerCase) - .collect(Collectors.joining(", ")); + .collect(Collectors.joining(", ")); } + } } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/OfflinePlayerArgument.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/OfflinePlayerArgument.java index a1d0386e..3b654788 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/OfflinePlayerArgument.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/OfflinePlayerArgument.java @@ -49,11 +49,13 @@ import java.util.function.BiFunction; @SuppressWarnings("unused") public final class OfflinePlayerArgument extends CommandArgument { - private OfflinePlayerArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private OfflinePlayerArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new OfflinePlayerParser<>(), defaultValue, OfflinePlayer.class, suggestionsProvider); } @@ -98,8 +100,10 @@ public final class OfflinePlayerArgument extends CommandArgument Command sender type * @return Created component */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultPlayer) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultPlayer + ) { return OfflinePlayerArgument.newBuilder(name).asOptionalWithDefault(defaultPlayer).build(); } @@ -118,7 +122,8 @@ public final class OfflinePlayerArgument extends CommandArgument build() { return new OfflinePlayerArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(), - this.getSuggestionsProvider()); + this.getSuggestionsProvider() + ); } } @@ -127,8 +132,10 @@ public final class OfflinePlayerArgument extends CommandArgument implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -146,8 +153,10 @@ public final class OfflinePlayerArgument extends CommandArgument suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { List output = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) { @@ -156,6 +165,7 @@ public final class OfflinePlayerArgument extends CommandArgument extends CommandArgument extends CommandArgument { - private PlayerArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private PlayerArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new PlayerParser<>(), defaultValue, Player.class, suggestionsProvider); } @@ -94,8 +96,10 @@ public final class PlayerArgument extends CommandArgument { * @param Command sender type * @return Created component */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultPlayer) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultPlayer + ) { return PlayerArgument.newBuilder(name).asOptionalWithDefault(defaultPlayer).build(); } @@ -122,8 +126,10 @@ public final class PlayerArgument extends CommandArgument { public static final class PlayerParser implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -141,8 +147,10 @@ public final class PlayerArgument extends CommandArgument { } @Override - public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { List output = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) { @@ -151,6 +159,7 @@ public final class PlayerArgument extends CommandArgument { return output; } + } @@ -183,5 +192,7 @@ public final class PlayerArgument extends CommandArgument { public String getMessage() { return String.format("No player found for input '%s'.", input); } + } + } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/WorldArgument.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/WorldArgument.java index 948600bb..3e76c332 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/WorldArgument.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/WorldArgument.java @@ -44,10 +44,12 @@ import java.util.stream.Collectors; */ public class WorldArgument extends CommandArgument { - protected WorldArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction, String, List> suggestionsProvider) { + protected WorldArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction, String, List> suggestionsProvider + ) { super(required, name, new WorldParser<>(), defaultValue, World.class, suggestionsProvider); } @@ -92,8 +94,10 @@ public class WorldArgument extends CommandArgument { * @param Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultValue) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultValue + ) { return WorldArgument.newBuilder(name).asOptionalWithDefault(defaultValue).build(); } @@ -108,14 +112,17 @@ public class WorldArgument extends CommandArgument { public @NonNull CommandArgument build() { return new WorldArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(), this.getSuggestionsProvider()); } + } public static final class WorldParser implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -164,6 +171,7 @@ public class WorldArgument extends CommandArgument { public String getMessage() { return String.format("'%s' is not a valid Minecraft world", this.input); } + } } diff --git a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/selector/MultipleEntitySelectorArgument.java b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/selector/MultipleEntitySelectorArgument.java index 701c71c4..716ebb9b 100644 --- a/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/selector/MultipleEntitySelectorArgument.java +++ b/cloud-minecraft/cloud-bukkit/src/main/java/cloud/commandframework/bukkit/parsers/selector/MultipleEntitySelectorArgument.java @@ -41,13 +41,16 @@ import java.util.function.BiFunction; public final class MultipleEntitySelectorArgument extends CommandArgument { - private MultipleEntitySelectorArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private MultipleEntitySelectorArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new MultipleEntitySelectorParser<>(), defaultValue, MultipleEntitySelector.class, - suggestionsProvider); + suggestionsProvider + ); } /** @@ -91,8 +94,10 @@ public final class MultipleEntitySelectorArgument extends CommandArgument Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultEntitySelector) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultEntitySelector + ) { return MultipleEntitySelectorArgument.newBuilder(name).asOptionalWithDefault(defaultEntitySelector).build(); } @@ -111,7 +116,8 @@ public final class MultipleEntitySelectorArgument extends CommandArgument build() { return new MultipleEntitySelectorArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(), - this.getSuggestionsProvider()); + this.getSuggestionsProvider() + ); } } @@ -120,8 +126,10 @@ public final class MultipleEntitySelectorArgument extends CommandArgument implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { if (!commandContext.>get("CloudBukkitCapabilities").contains( CloudBukkitCapabilities.BRIGADIER)) { return ArgumentParseResult.failure( @@ -142,6 +150,7 @@ public final class MultipleEntitySelectorArgument extends CommandArgument extends CommandArgument { - private MultiplePlayerSelectorArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private MultiplePlayerSelectorArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new MultiplePlayerSelectorParser<>(), defaultValue, MultiplePlayerSelector.class, - suggestionsProvider); + suggestionsProvider + ); } /** @@ -95,8 +98,10 @@ public final class MultiplePlayerSelectorArgument extends CommandArgument Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultEntitySelector) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultEntitySelector + ) { return MultiplePlayerSelectorArgument.newBuilder(name).asOptionalWithDefault(defaultEntitySelector).build(); } @@ -115,7 +120,8 @@ public final class MultiplePlayerSelectorArgument extends CommandArgument build() { return new MultiplePlayerSelectorArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(), - this.getSuggestionsProvider()); + this.getSuggestionsProvider() + ); } } @@ -124,8 +130,10 @@ public final class MultiplePlayerSelectorArgument extends CommandArgument implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -160,8 +168,10 @@ public final class MultiplePlayerSelectorArgument extends CommandArgument suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { List output = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) { @@ -170,6 +180,7 @@ public final class MultiplePlayerSelectorArgument extends CommandArgument extends CommandArgument { - private SingleEntitySelectorArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private SingleEntitySelectorArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new SingleEntitySelectorParser<>(), defaultValue, SingleEntitySelector.class, suggestionsProvider); } @@ -90,8 +92,10 @@ public final class SingleEntitySelectorArgument extends CommandArgument Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultEntitySelector) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultEntitySelector + ) { return SingleEntitySelectorArgument.newBuilder(name).asOptionalWithDefault(defaultEntitySelector).build(); } @@ -110,7 +114,8 @@ public final class SingleEntitySelectorArgument extends CommandArgument build() { return new SingleEntitySelectorArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(), - this.getSuggestionsProvider()); + this.getSuggestionsProvider() + ); } } @@ -119,8 +124,10 @@ public final class SingleEntitySelectorArgument extends CommandArgument implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { if (!commandContext.>get("CloudBukkitCapabilities").contains( CloudBukkitCapabilities.BRIGADIER)) { return ArgumentParseResult.failure( @@ -146,6 +153,7 @@ public final class SingleEntitySelectorArgument extends CommandArgument extends CommandArgument { - private SinglePlayerSelectorArgument(final boolean required, - final @NonNull String name, - final @NonNull String defaultValue, - final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, - @NonNull List<@NonNull String>> suggestionsProvider) { + private SinglePlayerSelectorArgument( + final boolean required, + final @NonNull String name, + final @NonNull String defaultValue, + final @Nullable BiFunction<@NonNull CommandContext, @NonNull String, + @NonNull List<@NonNull String>> suggestionsProvider + ) { super(required, name, new SinglePlayerSelectorParser<>(), defaultValue, SinglePlayerSelector.class, suggestionsProvider); } @@ -94,8 +96,10 @@ public final class SinglePlayerSelectorArgument extends CommandArgument Command sender type * @return Created argument */ - public static @NonNull CommandArgument optional(final @NonNull String name, - final @NonNull String defaultEntitySelector) { + public static @NonNull CommandArgument optional( + final @NonNull String name, + final @NonNull String defaultEntitySelector + ) { return SinglePlayerSelectorArgument.newBuilder(name).asOptionalWithDefault(defaultEntitySelector).build(); } @@ -114,7 +118,8 @@ public final class SinglePlayerSelectorArgument extends CommandArgument build() { return new SinglePlayerSelectorArgument<>(this.isRequired(), this.getName(), this.getDefaultValue(), - this.getSuggestionsProvider()); + this.getSuggestionsProvider() + ); } } @@ -123,8 +128,10 @@ public final class SinglePlayerSelectorArgument extends CommandArgument implements ArgumentParser { @Override - public @NonNull ArgumentParseResult parse(final @NonNull CommandContext commandContext, - final @NonNull Queue<@NonNull String> inputQueue) { + public @NonNull ArgumentParseResult parse( + final @NonNull CommandContext commandContext, + final @NonNull Queue<@NonNull String> inputQueue + ) { final String input = inputQueue.peek(); if (input == null) { return ArgumentParseResult.failure(new NullPointerException("No input was provided")); @@ -163,8 +170,10 @@ public final class SinglePlayerSelectorArgument extends CommandArgument suggestions(final @NonNull CommandContext commandContext, - final @NonNull String input) { + public @NonNull List<@NonNull String> suggestions( + final @NonNull CommandContext commandContext, + final @NonNull String input + ) { List output = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) { @@ -173,6 +182,7 @@ public final class SinglePlayerSelectorArgument extends CommandArgument extends Command implements TabExecutor { private final cloud.commandframework.Command cloudCommand; @SuppressWarnings("unchecked") - BungeeCommand(final cloud.commandframework.@NonNull Command cloudCommand, - final @NonNull CommandArgument command, - final @NonNull BungeeCommandManager manager) { - super(command.getName(), - cloudCommand.getCommandPermission().toString(), - ((StaticArgument) command).getAlternativeAliases().toArray(new String[0])); + BungeeCommand( + final cloud.commandframework.@NonNull Command cloudCommand, + final @NonNull CommandArgument command, + final @NonNull BungeeCommandManager manager + ) { + super( + command.getName(), + cloudCommand.getCommandPermission().toString(), + ((StaticArgument) command).getAlternativeAliases().toArray(new String[0]) + ); this.command = command; this.manager = manager; this.cloudCommand = cloudCommand; @@ -70,86 +74,102 @@ public final class BungeeCommand extends Command implements TabExecutor { builder.append(" ").append(string); } final C sender = this.manager.getCommandSenderMapper().apply(commandSender); - this.manager.executeCommand(sender, - builder.toString()) - .whenComplete(((commandResult, throwable) -> { - if (throwable != null) { - if (throwable instanceof CompletionException) { - throwable = throwable.getCause(); - } - final Throwable finalThrowable = throwable; - if (throwable instanceof InvalidSyntaxException) { - this.manager.handleException(sender, - InvalidSyntaxException.class, - (InvalidSyntaxException) throwable, (c, e) -> - commandSender.sendMessage( - new ComponentBuilder("Invalid Command Syntax. Correct command syntax is: ") - .color(ChatColor.RED) - .append("/") - .color(ChatColor.GRAY) - .append(((InvalidSyntaxException) finalThrowable).getCorrectSyntax()) - .color(ChatColor.GRAY) - .create() - ) - ); - } else if (throwable instanceof InvalidCommandSenderException) { - final Throwable finalThrowable1 = throwable; - this.manager.handleException(sender, - InvalidCommandSenderException.class, - (InvalidCommandSenderException) throwable, (c, e) -> - commandSender.sendMessage(new ComponentBuilder(finalThrowable1.getMessage()) - .color(ChatColor.RED) - .create()) - ); - } else if (throwable instanceof NoPermissionException) { - this.manager.handleException(sender, - NoPermissionException.class, - (NoPermissionException) throwable, (c, e) -> - commandSender.sendMessage(new ComponentBuilder(MESSAGE_NO_PERMS) - .color(ChatColor.WHITE) - .create()) - ); - } else if (throwable instanceof NoSuchCommandException) { - this.manager.handleException(sender, - NoSuchCommandException.class, - (NoSuchCommandException) throwable, (c, e) -> - commandSender.sendMessage(new ComponentBuilder(MESSAGE_UNKNOWN_COMMAND) - .color(ChatColor.WHITE) - .create()) - ); - } else if (throwable instanceof ArgumentParseException) { - this.manager.handleException(sender, - ArgumentParseException.class, - (ArgumentParseException) throwable, (c, e) -> - commandSender.sendMessage(new ComponentBuilder("Invalid Command Argument: ") - .color(ChatColor.GRAY) - .append(finalThrowable.getCause().getMessage()) - .create()) - ); - } else { - commandSender.sendMessage(new ComponentBuilder(throwable.getMessage()).create()); - this.manager.getOwningPlugin().getLogger().warning( - String.format("(Cloud) Unknown exception type '%s' with cause '%s'", - throwable.getClass().getCanonicalName(), - throwable.getCause() == null ? "none" - : throwable.getCause() - .getClass().getCanonicalName()) - ); - throwable.printStackTrace(); - } - } - })); + this.manager.executeCommand( + sender, + builder.toString() + ) + .whenComplete(((commandResult, throwable) -> { + if (throwable != null) { + if (throwable instanceof CompletionException) { + throwable = throwable.getCause(); + } + final Throwable finalThrowable = throwable; + if (throwable instanceof InvalidSyntaxException) { + this.manager.handleException(sender, + InvalidSyntaxException.class, + (InvalidSyntaxException) throwable, (c, e) -> + commandSender.sendMessage( + new ComponentBuilder( + "Invalid Command Syntax. Correct command syntax is: ") + .color(ChatColor.RED) + .append("/") + .color(ChatColor.GRAY) + .append(((InvalidSyntaxException) finalThrowable) + .getCorrectSyntax()) + .color(ChatColor.GRAY) + .create() + ) + ); + } else if (throwable instanceof InvalidCommandSenderException) { + final Throwable finalThrowable1 = throwable; + this.manager.handleException(sender, + InvalidCommandSenderException.class, + (InvalidCommandSenderException) throwable, (c, e) -> + commandSender.sendMessage(new ComponentBuilder( + finalThrowable1.getMessage()) + .color(ChatColor.RED) + .create()) + ); + } else if (throwable instanceof NoPermissionException) { + this.manager.handleException(sender, + NoPermissionException.class, + (NoPermissionException) throwable, (c, e) -> + commandSender.sendMessage(new ComponentBuilder( + MESSAGE_NO_PERMS) + .color(ChatColor.WHITE) + .create()) + ); + } else if (throwable instanceof NoSuchCommandException) { + this.manager.handleException(sender, + NoSuchCommandException.class, + (NoSuchCommandException) throwable, (c, e) -> + commandSender.sendMessage(new ComponentBuilder( + MESSAGE_UNKNOWN_COMMAND) + .color(ChatColor.WHITE) + .create()) + ); + } else if (throwable instanceof ArgumentParseException) { + this.manager.handleException(sender, + ArgumentParseException.class, + (ArgumentParseException) throwable, (c, e) -> + commandSender.sendMessage(new ComponentBuilder( + "Invalid Command Argument: ") + .color(ChatColor.GRAY) + .append(finalThrowable + .getCause() + .getMessage()) + .create()) + ); + } else { + commandSender.sendMessage(new ComponentBuilder(throwable.getMessage()).create()); + this.manager.getOwningPlugin().getLogger().warning( + String.format( + "(Cloud) Unknown exception type '%s' with cause '%s'", + throwable.getClass().getCanonicalName(), + throwable.getCause() == null ? "none" + : throwable.getCause() + .getClass().getCanonicalName() + ) + ); + throwable.printStackTrace(); + } + } + })); } @Override - public Iterable onTabComplete(final CommandSender sender, - final String[] args) { + public Iterable onTabComplete( + final CommandSender sender, + final String[] args + ) { final StringBuilder builder = new StringBuilder(this.command.getName()); for (final String string : args) { builder.append(" ").append(string); } - return this.manager.suggest(this.manager.getCommandSenderMapper().apply(sender), - builder.toString()); + return this.manager.suggest( + this.manager.getCommandSenderMapper().apply(sender), + builder.toString() + ); } } diff --git a/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeeCommandManager.java b/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeeCommandManager.java index ef6d13d5..a8dd1541 100644 --- a/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeeCommandManager.java +++ b/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeeCommandManager.java @@ -48,11 +48,13 @@ public class BungeeCommandManager extends CommandManager { * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender} * @throws Exception If the construction of the manager fails */ - public BungeeCommandManager(final @NonNull Plugin owningPlugin, - final @NonNull Function<@NonNull CommandTree, - @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, - final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper) + public BungeeCommandManager( + final @NonNull Plugin owningPlugin, + final @NonNull Function<@NonNull CommandTree, + @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, + final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, + final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper + ) throws Exception { super(commandExecutionCoordinator, new BungeePluginRegistrationHandler<>()); ((BungeePluginRegistrationHandler) this.getCommandRegistrationHandler()).initialize(this); @@ -62,8 +64,10 @@ public class BungeeCommandManager extends CommandManager { } @Override - public final boolean hasPermission(final @NonNull C sender, - final @NonNull String permission) { + public final boolean hasPermission( + final @NonNull C sender, + final @NonNull String permission + ) { if (permission.isEmpty()) { return true; } diff --git a/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeePluginRegistrationHandler.java b/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeePluginRegistrationHandler.java index 80288c05..154312d8 100644 --- a/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeePluginRegistrationHandler.java +++ b/cloud-minecraft/cloud-bungee/src/main/java/cloud/commandframework/bungee/BungeePluginRegistrationHandler.java @@ -54,10 +54,11 @@ final class BungeePluginRegistrationHandler implements CommandRegistrationHan @SuppressWarnings("unchecked") final BungeeCommand bungeeCommand = new BungeeCommand<>( (Command) command, (CommandArgument) commandArgument, - this.bungeeCommandManager); + this.bungeeCommandManager + ); this.registeredCommands.put(commandArgument, bungeeCommand); this.bungeeCommandManager.getOwningPlugin().getProxy().getPluginManager() - .registerCommand(this.bungeeCommandManager.getOwningPlugin(), bungeeCommand); + .registerCommand(this.bungeeCommandManager.getOwningPlugin(), bungeeCommand); return true; } diff --git a/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommand.java b/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommand.java index e815dab2..dfe462b8 100644 --- a/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommand.java +++ b/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommand.java @@ -50,82 +50,88 @@ final class CloudburstCommand extends PluginCommand { private final CloudburstCommandManager manager; private final Command cloudCommand; - CloudburstCommand(final @NonNull String label, - final @NonNull List<@NonNull String> aliases, - final @NonNull Command cloudCommand, - final @NonNull CommandArgument command, - final @NonNull CloudburstCommandManager manager) { + CloudburstCommand( + final @NonNull String label, + final @NonNull List<@NonNull String> aliases, + final @NonNull Command cloudCommand, + final @NonNull CommandArgument command, + final @NonNull CloudburstCommandManager manager + ) { super(manager.getOwningPlugin(), CommandData.builder(label) - .addAliases(aliases.toArray(new String[0])) - .addPermission(cloudCommand.getCommandPermission().toString()) - .setDescription(cloudCommand.getCommandMeta().getOrDefault("description", "")) - .build()); + .addAliases(aliases.toArray(new String[0])) + .addPermission(cloudCommand.getCommandPermission().toString()) + .setDescription(cloudCommand.getCommandMeta().getOrDefault("description", "")) + .build()); this.command = command; this.manager = manager; this.cloudCommand = cloudCommand; } @Override - public boolean execute(final CommandSender commandSender, - final String commandLabel, - final String[] strings) { + public boolean execute( + final CommandSender commandSender, + final String commandLabel, + final String[] strings + ) { /* Join input */ final StringBuilder builder = new StringBuilder(this.command.getName()); for (final String string : strings) { builder.append(" ").append(string); } final C sender = this.manager.getCommandSenderMapper().apply(commandSender); - this.manager.executeCommand(sender, - builder.toString()) - .whenComplete(((commandResult, throwable) -> { - if (throwable != null) { - if (throwable instanceof CompletionException) { - throwable = throwable.getCause(); - } - final Throwable finalThrowable = throwable; - if (throwable instanceof InvalidSyntaxException) { - this.manager.handleException(sender, - InvalidSyntaxException.class, - (InvalidSyntaxException) throwable, (c, e) -> - commandSender.sendMessage( - "Invalid Command Syntax. " - + "Correct command syntax is: " - + "/" - + ((InvalidSyntaxException) finalThrowable) - .getCorrectSyntax()) - ); - } else if (throwable instanceof InvalidCommandSenderException) { - this.manager.handleException(sender, - InvalidCommandSenderException.class, - (InvalidCommandSenderException) throwable, (c, e) -> - commandSender.sendMessage(finalThrowable.getMessage()) - ); - } else if (throwable instanceof NoPermissionException) { - this.manager.handleException(sender, - NoPermissionException.class, - (NoPermissionException) throwable, (c, e) -> - commandSender.sendMessage(MESSAGE_NO_PERMS) - ); - } else if (throwable instanceof NoSuchCommandException) { - this.manager.handleException(sender, - NoSuchCommandException.class, - (NoSuchCommandException) throwable, (c, e) -> - commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND) - ); - } else if (throwable instanceof ArgumentParseException) { - this.manager.handleException(sender, - ArgumentParseException.class, - (ArgumentParseException) throwable, (c, e) -> - commandSender.sendMessage( - "Invalid Command Argument: " - + finalThrowable.getCause().getMessage()) - ); - } else { - commandSender.sendMessage(throwable.getMessage()); - throwable.printStackTrace(); - } + this.manager.executeCommand( + sender, + builder.toString() + ) + .whenComplete(((commandResult, throwable) -> { + if (throwable != null) { + if (throwable instanceof CompletionException) { + throwable = throwable.getCause(); } - })); + final Throwable finalThrowable = throwable; + if (throwable instanceof InvalidSyntaxException) { + this.manager.handleException(sender, + InvalidSyntaxException.class, + (InvalidSyntaxException) throwable, (c, e) -> + commandSender.sendMessage( + "Invalid Command Syntax. " + + "Correct command syntax is: " + + "/" + + ((InvalidSyntaxException) finalThrowable) + .getCorrectSyntax()) + ); + } else if (throwable instanceof InvalidCommandSenderException) { + this.manager.handleException(sender, + InvalidCommandSenderException.class, + (InvalidCommandSenderException) throwable, (c, e) -> + commandSender.sendMessage(finalThrowable.getMessage()) + ); + } else if (throwable instanceof NoPermissionException) { + this.manager.handleException(sender, + NoPermissionException.class, + (NoPermissionException) throwable, (c, e) -> + commandSender.sendMessage(MESSAGE_NO_PERMS) + ); + } else if (throwable instanceof NoSuchCommandException) { + this.manager.handleException(sender, + NoSuchCommandException.class, + (NoSuchCommandException) throwable, (c, e) -> + commandSender.sendMessage(MESSAGE_UNKNOWN_COMMAND) + ); + } else if (throwable instanceof ArgumentParseException) { + this.manager.handleException(sender, + ArgumentParseException.class, + (ArgumentParseException) throwable, (c, e) -> + commandSender.sendMessage( + "Invalid Command Argument: " + + finalThrowable.getCause().getMessage()) + ); + } else { + commandSender.sendMessage(throwable.getMessage()); + throwable.printStackTrace(); + } + } + })); return true; } diff --git a/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommandManager.java b/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommandManager.java index dbde484d..19e753b7 100644 --- a/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommandManager.java +++ b/cloud-minecraft/cloud-cloudburst/src/main/java/cloud/commandframework/cloudburst/CloudburstCommandManager.java @@ -54,11 +54,13 @@ public class CloudburstCommandManager extends CommandManager { * @param commandSenderMapper Function that maps {@link CommandSender} to the command sender type * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender} */ - public CloudburstCommandManager(final @NonNull Plugin owningPlugin, - final @NonNull Function<@NonNull CommandTree, - @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, - final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper) { + public CloudburstCommandManager( + final @NonNull Plugin owningPlugin, + final @NonNull Function<@NonNull CommandTree, + @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, + final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, + final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper + ) { super(commandExecutionCoordinator, new CloudburstPluginRegistrationHandler<>()); ((CloudburstPluginRegistrationHandler) this.getCommandRegistrationHandler()).initialize(this); this.commandSenderMapper = commandSenderMapper; @@ -67,8 +69,10 @@ public class CloudburstCommandManager extends CommandManager { } @Override - public final boolean hasPermission(final @NonNull C sender, - final @NonNull String permission) { + public final boolean hasPermission( + final @NonNull C sender, + final @NonNull String permission + ) { return this.backwardsCommandSenderMapper.apply(sender).hasPermission(permission); } diff --git a/cloud-minecraft/cloud-minecraft-extras/src/main/java/cloud/commandframework/MinecraftHelp.java b/cloud-minecraft/cloud-minecraft-extras/src/main/java/cloud/commandframework/MinecraftHelp.java index dea74cce..7ed9c9fe 100644 --- a/cloud-minecraft/cloud-minecraft-extras/src/main/java/cloud/commandframework/MinecraftHelp.java +++ b/cloud-minecraft/cloud-minecraft-extras/src/main/java/cloud/commandframework/MinecraftHelp.java @@ -73,9 +73,11 @@ public final class MinecraftHelp { * @param audienceProvider Provider that maps the command sender type to {@link Audience} * @param commandManager Command manager instance */ - public MinecraftHelp(final @NonNull String commandPrefix, - final @NonNull AudienceProvider audienceProvider, - final @NonNull CommandManager commandManager) { + public MinecraftHelp( + final @NonNull String commandPrefix, + final @NonNull AudienceProvider audienceProvider, + final @NonNull CommandManager commandManager + ) { this.commandPrefix = commandPrefix; this.audienceProvider = audienceProvider; this.commandManager = commandManager; @@ -85,9 +87,9 @@ public final class MinecraftHelp { this.messageMap.put(MESSAGE_QUERY_QUERY, "Showing search results for query: \"/\""); this.messageMap.put(MESSAGE_QUERY_AVAILABLE_COMMANDS, "└─ Available Commands:"); this.messageMap.put(MESSAGE_QUERY_COMMAND_SYNTAX, " ├─ " - + "\">/"); + + "\">/"); this.messageMap.put(MESSAGE_QUERY_COMMAND_SYNTAX_LAST, " └─ " - + "\">/"); + + "\">/"); this.messageMap.put(MESSAGE_QUERY_LONGEST_PATH, "└─ /"); this.messageMap.put(MESSAGE_QUERY_SUGGESTION, " >Click to show help for this command\">" @@ -138,8 +140,10 @@ public final class MinecraftHelp { * @param key Message key * @param message Message */ - public void setMessage(final @NonNull String key, - final @NonNull String message) { + public void setMessage( + final @NonNull String key, + final @NonNull String message + ) { this.messageMap.put(key, message); } @@ -149,19 +153,25 @@ public final class MinecraftHelp { * @param query Command query (without leading '/') * @param recipient Recipient */ - public void queryCommands(final @NonNull String query, - final @NonNull C recipient) { + public void queryCommands( + final @NonNull String query, + final @NonNull C recipient + ) { final Audience audience = this.getAudience(recipient); audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_HELP_HEADER))); this.printTopic(recipient, query, this.commandManager.getCommandHelpHandler().queryHelp(recipient, query)); audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_HELP_FOOTER))); } - private void printTopic(final @NonNull C sender, - final @NonNull String query, - final CommandHelpHandler.@NonNull HelpTopic helpTopic) { - this.getAudience(sender).sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_QUERY), - Template.of("query", query))); + private void printTopic( + final @NonNull C sender, + final @NonNull String query, + final CommandHelpHandler.@NonNull HelpTopic helpTopic + ) { + this.getAudience(sender).sendMessage(this.miniMessage.parse( + this.messageMap.get(MESSAGE_QUERY_QUERY), + Template.of("query", query) + )); if (helpTopic instanceof CommandHelpHandler.IndexHelpTopic) { this.printIndexHelpTopic(sender, (CommandHelpHandler.IndexHelpTopic) helpTopic); } else if (helpTopic instanceof CommandHelpHandler.MultiHelpTopic) { @@ -173,8 +183,10 @@ public final class MinecraftHelp { } } - private void printIndexHelpTopic(final @NonNull C sender, - final CommandHelpHandler.@NonNull IndexHelpTopic helpTopic) { + private void printIndexHelpTopic( + final @NonNull C sender, + final CommandHelpHandler.@NonNull IndexHelpTopic helpTopic + ) { final Audience audience = this.getAudience(sender); audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_AVAILABLE_COMMANDS))); final Iterator> iterator = helpTopic.getEntries().iterator(); @@ -182,30 +194,34 @@ public final class MinecraftHelp { final CommandHelpHandler.VerboseHelpEntry entry = iterator.next(); final String description = entry.getDescription().isEmpty() ? "Click to show help for this command" - : entry.getDescription(); + : entry.getDescription(); String message = this.messageMap.get(iterator.hasNext() ? MESSAGE_QUERY_COMMAND_SYNTAX - : MESSAGE_QUERY_COMMAND_SYNTAX_LAST); + : MESSAGE_QUERY_COMMAND_SYNTAX_LAST); final String suggestedCommand = entry.getSyntaxString() - .replace("<", "") - .replace(">", "") - .replace("[", "") - .replace("]", ""); + .replace("<", "") + .replace(">", "") + .replace("[", "") + .replace("]", ""); message = message.replace("", entry.getSyntaxString()) - .replace("", description) - .replace("cmdprefix", this.commandPrefix + ' ' + suggestedCommand); + .replace("", description) + .replace("cmdprefix", this.commandPrefix + ' ' + suggestedCommand); audience.sendMessage(this.miniMessage.parse(message)); } } - private void printMultiHelpTopic(final @NonNull C sender, - final CommandHelpHandler.@NonNull MultiHelpTopic helpTopic) { + private void printMultiHelpTopic( + final @NonNull C sender, + final CommandHelpHandler.@NonNull MultiHelpTopic helpTopic + ) { final Audience audience = this.getAudience(sender); - audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_LONGEST_PATH), - Template.of("command", helpTopic.getLongestPath()))); + audience.sendMessage(this.miniMessage.parse( + this.messageMap.get(MESSAGE_QUERY_LONGEST_PATH), + Template.of("command", helpTopic.getLongestPath()) + )); final int headerIndentation = helpTopic.getLongestPath().length(); final Iterator iterator = helpTopic.getChildSuggestions().iterator(); while (iterator.hasNext()) { @@ -224,27 +240,35 @@ public final class MinecraftHelp { } final String suggestedCommand = suggestion.replace("<", "") - .replace(">", "") - .replace("[", "") - .replace("]", ""); + .replace(">", "") + .replace("[", "") + .replace("]", ""); - audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_SUGGESTION), - Template.of("indentation", indentation.toString()), - Template.of("prefix", prefix), - Template.of("suggestion", suggestion), - Template.of("cmdprefix", this.commandPrefix + ' ' + suggestedCommand))); + audience.sendMessage(this.miniMessage.parse( + this.messageMap.get(MESSAGE_QUERY_SUGGESTION), + Template.of("indentation", indentation.toString()), + Template.of("prefix", prefix), + Template.of("suggestion", suggestion), + Template.of("cmdprefix", this.commandPrefix + ' ' + suggestedCommand) + )); } } - private void printVerboseHelpTopic(final @NonNull C sender, - final CommandHelpHandler.@NonNull VerboseHelpTopic helpTopic) { + private void printVerboseHelpTopic( + final @NonNull C sender, + final CommandHelpHandler.@NonNull VerboseHelpTopic helpTopic + ) { final Audience audience = this.getAudience(sender); final String command = this.commandManager.getCommandSyntaxFormatter() - .apply(helpTopic.getCommand().getArguments(), null); - audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_VERBOSE_SYNTAX), - Template.of("command", command))); - audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_VERBOSE_DESCRIPTION), - Template.of("description", helpTopic.getDescription()))); + .apply(helpTopic.getCommand().getArguments(), null); + audience.sendMessage(this.miniMessage.parse( + this.messageMap.get(MESSAGE_QUERY_VERBOSE_SYNTAX), + Template.of("command", command) + )); + audience.sendMessage(this.miniMessage.parse( + this.messageMap.get(MESSAGE_QUERY_VERBOSE_DESCRIPTION), + Template.of("description", helpTopic.getDescription()) + )); audience.sendMessage(this.miniMessage.parse(this.messageMap.get(MESSAGE_QUERY_VERBOSE_ARGS))); final Iterator> iterator = helpTopic.getCommand().getArguments().iterator(); @@ -262,7 +286,7 @@ public final class MinecraftHelp { } String syntax = this.commandManager.getCommandSyntaxFormatter() - .apply(Collections.singletonList(argument), null); + .apply(Collections.singletonList(argument), null); if (argument instanceof StaticArgument) { syntax = this.messageMap.get(MESSAGE_QUERY_VERBOSE_LITERAL).replace("", syntax); @@ -278,10 +302,12 @@ public final class MinecraftHelp { message = this.messageMap.get(MESSAGE_QUERY_VERBOSE_OPTIONAL); } - audience.sendMessage(this.miniMessage.parse(message, - Template.of("prefix", prefix), - Template.of("syntax", syntax), - Template.of("description", description))); + audience.sendMessage(this.miniMessage.parse( + message, + Template.of("prefix", prefix), + Template.of("syntax", syntax), + Template.of("description", description) + )); } } diff --git a/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/AsyncCommandSuggestionsListener.java b/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/AsyncCommandSuggestionsListener.java index 8ad3c8b3..191d2426 100644 --- a/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/AsyncCommandSuggestionsListener.java +++ b/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/AsyncCommandSuggestionsListener.java @@ -52,16 +52,17 @@ class AsyncCommandSuggestionsListener implements Listener { if (this.paperCommandManager.getCommandTree().getNamedNode(arguments[0]) == null) { return; } - @SuppressWarnings("unchecked") - final BukkitPluginRegistrationHandler bukkitPluginRegistrationHandler = + @SuppressWarnings("unchecked") final BukkitPluginRegistrationHandler bukkitPluginRegistrationHandler = (BukkitPluginRegistrationHandler) this.paperCommandManager.getCommandRegistrationHandler(); if (!bukkitPluginRegistrationHandler.isRecognized(arguments[0])) { return; } final CommandSender sender = event.getSender(); final C cloudSender = this.paperCommandManager.getCommandSenderMapper().apply(sender); - final List suggestions = new ArrayList<>(this.paperCommandManager.suggest(cloudSender, - event.getBuffer().substring(1))); + final List suggestions = new ArrayList<>(this.paperCommandManager.suggest( + cloudSender, + event.getBuffer().substring(1) + )); event.setCompletions(suggestions); event.setHandled(true); } diff --git a/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperBrigadierListener.java b/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperBrigadierListener.java index 2b0d0382..561fca0e 100644 --- a/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperBrigadierListener.java +++ b/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperBrigadierListener.java @@ -47,10 +47,12 @@ class PaperBrigadierListener implements Listener { PaperBrigadierListener(final @NonNull PaperCommandManager paperCommandManager) { this.paperCommandManager = paperCommandManager; - this.brigadierManager = new CloudBrigadierManager<>(this.paperCommandManager, - () -> new CommandContext<>( - this.paperCommandManager.getCommandSenderMapper() - .apply(Bukkit.getConsoleSender()))); + this.brigadierManager = new CloudBrigadierManager<>( + this.paperCommandManager, + () -> new CommandContext<>( + this.paperCommandManager.getCommandSenderMapper() + .apply(Bukkit.getConsoleSender())) + ); new BukkitBrigadierMapper<>(this.paperCommandManager, this.brigadierManager); } @@ -79,11 +81,13 @@ class PaperBrigadierListener implements Listener { final C sender = this.paperCommandManager.getCommandSenderMapper().apply(s.getBukkitSender()); return this.paperCommandManager.hasPermission(sender, p); }; - event.setLiteral(this.brigadierManager.createLiteralCommandNode(node, - event.getLiteral(), - event.getBrigadierCommand(), - event.getBrigadierCommand(), - permissionChecker)); + event.setLiteral(this.brigadierManager.createLiteralCommandNode( + node, + event.getLiteral(), + event.getBrigadierCommand(), + event.getBrigadierCommand(), + permissionChecker + )); } } diff --git a/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperCommandManager.java b/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperCommandManager.java index 063077b8..e55b118f 100644 --- a/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperCommandManager.java +++ b/cloud-minecraft/cloud-paper/src/main/java/cloud/commandframework/paper/PaperCommandManager.java @@ -50,11 +50,13 @@ public class PaperCommandManager extends BukkitCommandManager { * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender} * @throws Exception If the construction of the manager fails */ - public PaperCommandManager(final @NonNull Plugin owningPlugin, - final @NonNull Function, - CommandExecutionCoordinator> commandExecutionCoordinator, - final @NonNull Function commandSenderMapper, - final @NonNull Function backwardsCommandSenderMapper) throws + public PaperCommandManager( + final @NonNull Plugin owningPlugin, + final @NonNull Function, + CommandExecutionCoordinator> commandExecutionCoordinator, + final @NonNull Function commandSenderMapper, + final @NonNull Function backwardsCommandSenderMapper + ) throws Exception { super(owningPlugin, commandExecutionCoordinator, commandSenderMapper, backwardsCommandSenderMapper); @@ -73,8 +75,10 @@ public class PaperCommandManager extends BukkitCommandManager { } else { try { final PaperBrigadierListener brigadierListener = new PaperBrigadierListener<>(this); - Bukkit.getPluginManager().registerEvents(brigadierListener, - this.getOwningPlugin()); + Bukkit.getPluginManager().registerEvents( + brigadierListener, + this.getOwningPlugin() + ); this.setSplitAliases(true); } catch (final Throwable e) { throw new BrigadierFailureException(BrigadierFailureReason.PAPER_BRIGADIER_INITIALIZATION_FAILURE, e); diff --git a/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityCommandManager.java b/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityCommandManager.java index 5acdd02b..a1d7c6d6 100644 --- a/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityCommandManager.java +++ b/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityCommandManager.java @@ -57,7 +57,8 @@ public class VelocityCommandManager extends CommandManager { final @NonNull ProxyServer proxyServer, final @NonNull Function<@NonNull CommandTree, @NonNull CommandExecutionCoordinator> commandExecutionCoordinator, final @NonNull Function<@NonNull CommandSource, @NonNull C> commandSenderMapper, - final @NonNull Function<@NonNull C, @NonNull CommandSource> backwardsCommandSenderMapper) { + final @NonNull Function<@NonNull C, @NonNull CommandSource> backwardsCommandSenderMapper + ) { super(commandExecutionCoordinator, new VelocityPluginRegistrationHandler<>()); ((VelocityPluginRegistrationHandler) this.getCommandRegistrationHandler()).initialize(this); this.proxyServer = proxyServer; diff --git a/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityPluginRegistrationHandler.java b/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityPluginRegistrationHandler.java index f33774c4..a883325f 100644 --- a/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityPluginRegistrationHandler.java +++ b/cloud-minecraft/cloud-velocity/src/main/java/cloud/commandframework/velocity/VelocityPluginRegistrationHandler.java @@ -23,10 +23,10 @@ // package cloud.commandframework.velocity; -import cloud.commandframework.brigadier.CloudBrigadierManager; import cloud.commandframework.Command; import cloud.commandframework.arguments.CommandArgument; import cloud.commandframework.arguments.StaticArgument; +import cloud.commandframework.brigadier.CloudBrigadierManager; import cloud.commandframework.context.CommandContext; import cloud.commandframework.exceptions.ArgumentParseException; import cloud.commandframework.exceptions.InvalidCommandSenderException; @@ -56,11 +56,12 @@ final class VelocityPluginRegistrationHandler implements CommandRegistrationH void initialize(final @NonNull VelocityCommandManager velocityCommandManager) { this.manager = velocityCommandManager; - this.brigadierManager = new CloudBrigadierManager<>(velocityCommandManager, - () -> new CommandContext<>( - velocityCommandManager.getCommandSenderMapper() - .apply(velocityCommandManager.getProxyServer() - .getConsoleCommandSource())) + this.brigadierManager = new CloudBrigadierManager<>( + velocityCommandManager, + () -> new CommandContext<>( + velocityCommandManager.getCommandSenderMapper() + .apply(velocityCommandManager.getProxyServer() + .getConsoleCommandSource())) ); } @@ -70,67 +71,107 @@ final class VelocityPluginRegistrationHandler implements CommandRegistrationH final List aliases = ((StaticArgument) argument).getAlternativeAliases(); final BrigadierCommand brigadierCommand = new BrigadierCommand( this.brigadierManager.createLiteralCommandNode(command.getArguments().get(0).getName(), (Command) command, - (c, p) -> this.manager.hasPermission( - this.manager.getCommandSenderMapper() - .apply(c), p), true, - commandContext -> { - final CommandSource source = commandContext.getSource(); - final String input = commandContext.getInput(); - final C sender = this.manager.getCommandSenderMapper().apply(source); - this.manager.executeCommand(sender, input).whenComplete((result, throwable) -> { - if (throwable != null) { - if (throwable instanceof CompletionException) { - throwable = throwable.getCause(); - } - final Throwable finalThrowable = throwable; - if (throwable instanceof InvalidSyntaxException) { - this.manager.handleException(sender, - InvalidSyntaxException.class, - (InvalidSyntaxException) throwable, (c, e) -> - source.sendMessage(TextComponent.builder("Invalid Command Syntax. Correct command syntax is: ", - NamedTextColor.RED) - .append(e.getCorrectSyntax(), NamedTextColor.GRAY).build()) - ); - } else if (throwable instanceof InvalidCommandSenderException) { - this.manager.handleException(sender, - InvalidCommandSenderException.class, - (InvalidCommandSenderException) throwable, (c, e) -> - source.sendMessage(TextComponent.of(finalThrowable.getMessage()).color(NamedTextColor.RED)) - ); - } else if (throwable instanceof NoPermissionException) { - this.manager.handleException(sender, - NoPermissionException.class, - (NoPermissionException) throwable, (c, e) -> - source.sendMessage(TextComponent.of(MESSAGE_NO_PERMS)) - ); - } else if (throwable instanceof NoSuchCommandException) { - this.manager.handleException(sender, - NoSuchCommandException.class, - (NoSuchCommandException) throwable, (c, e) -> - source.sendMessage(TextComponent.of(MESSAGE_UNKNOWN_COMMAND)) - ); - } else if (throwable instanceof ArgumentParseException) { - this.manager.handleException(sender, - ArgumentParseException.class, - (ArgumentParseException) throwable, (c, e) -> - source.sendMessage(TextComponent.builder("Invalid Command Argument: ", - NamedTextColor.RED) - .append(finalThrowable.getCause().getMessage(), - NamedTextColor.GRAY) - .build()) - ); - } else { - source.sendMessage(TextComponent.of(throwable.getMessage()).color(NamedTextColor.RED)); - throwable.printStackTrace(); - } - } - }); - return com.mojang.brigadier.Command.SINGLE_SUCCESS; - }) + (c, p) -> this.manager.hasPermission( + this.manager.getCommandSenderMapper() + .apply(c), p), true, + commandContext -> { + final CommandSource source = commandContext.getSource(); + final String input = commandContext.getInput(); + final C sender = this.manager.getCommandSenderMapper().apply( + source); + this.manager + .executeCommand(sender, input) + .whenComplete((result, throwable) -> { + if (throwable != null) { + if (throwable instanceof CompletionException) { + throwable = throwable.getCause(); + } + final Throwable finalThrowable = throwable; + if (throwable instanceof InvalidSyntaxException) { + this.manager.handleException( + sender, + InvalidSyntaxException.class, + (InvalidSyntaxException) throwable, + (c, e) -> + source.sendMessage( + TextComponent + .builder( + "Invalid Command Syntax. Correct command syntax is: ", + NamedTextColor.RED + ) + .append( + e.getCorrectSyntax(), + NamedTextColor.GRAY + ) + .build()) + ); + } else if (throwable instanceof InvalidCommandSenderException) { + this.manager.handleException( + sender, + InvalidCommandSenderException.class, + (InvalidCommandSenderException) throwable, + (c, e) -> + source.sendMessage( + TextComponent + .of(finalThrowable + .getMessage()) + .color(NamedTextColor.RED)) + ); + } else if (throwable instanceof NoPermissionException) { + this.manager.handleException( + sender, + NoPermissionException.class, + (NoPermissionException) throwable, + (c, e) -> + source.sendMessage( + TextComponent + .of(MESSAGE_NO_PERMS)) + ); + } else if (throwable instanceof NoSuchCommandException) { + this.manager.handleException( + sender, + NoSuchCommandException.class, + (NoSuchCommandException) throwable, + (c, e) -> + source.sendMessage( + TextComponent + .of(MESSAGE_UNKNOWN_COMMAND)) + ); + } else if (throwable instanceof ArgumentParseException) { + this.manager.handleException( + sender, + ArgumentParseException.class, + (ArgumentParseException) throwable, + (c, e) -> + source.sendMessage( + TextComponent + .builder( + "Invalid Command Argument: ", + NamedTextColor.RED + ) + .append( + finalThrowable + .getCause() + .getMessage(), + NamedTextColor.GRAY + ) + .build()) + ); + } else { + source.sendMessage(TextComponent + .of(throwable.getMessage()) + .color(NamedTextColor.RED)); + throwable.printStackTrace(); + } + } + }); + return com.mojang.brigadier.Command.SINGLE_SUCCESS; + } + ) ); final CommandMeta commandMeta = this.manager.getProxyServer().getCommandManager() - .metaBuilder(brigadierCommand) - .aliases(aliases.toArray(new String[0])).build(); + .metaBuilder(brigadierCommand) + .aliases(aliases.toArray(new String[0])).build(); aliases.forEach(this.manager.getProxyServer().getCommandManager()::unregister); this.manager.getProxyServer().getCommandManager().register(commandMeta, brigadierCommand); return true; diff --git a/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodService.java b/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodService.java index 6933fc6d..2e12164c 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodService.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodService.java @@ -40,58 +40,61 @@ class AnnotatedMethodService implements Service that = (AnnotatedMethodService) o; - return Objects.equals(this.methodHandle, that.methodHandle); - } - @Override - public int hashCode() { - return Objects.hash(this.methodHandle); - } + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final AnnotatedMethodService that = (AnnotatedMethodService) o; + return Objects.equals(this.methodHandle, that.methodHandle); + } + + @Override + public int hashCode() { + return Objects.hash(this.methodHandle); + } } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodServiceFactory.java b/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodServiceFactory.java index 4c733464..3bc5821c 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodServiceFactory.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/AnnotatedMethodServiceFactory.java @@ -36,24 +36,28 @@ enum AnnotatedMethodServiceFactory { INSTANCE; @NonNull Map, TypeToken>> lookupServices( - final @NonNull Object instance) throws Exception { - final Map, TypeToken>> map = new HashMap<>(); - final Class clazz = instance.getClass(); - for (final Method method : clazz.getDeclaredMethods()) { - final ServiceImplementation serviceImplementation = - method.getAnnotation(ServiceImplementation.class); - if (serviceImplementation == null) { - continue; - } - if (method.getParameterCount() != 1) { - throw new IllegalArgumentException(String.format( - "Method '%s' in class '%s'" + " has wrong parameter count. Expected 1, got %d", - method.getName(), instance.getClass().getCanonicalName(), - method.getParameterCount())); + final @NonNull Object instance + ) throws Exception { + final Map, TypeToken>> map = new HashMap<>(); + final Class clazz = instance.getClass(); + for (final Method method : clazz.getDeclaredMethods()) { + final ServiceImplementation serviceImplementation = + method.getAnnotation(ServiceImplementation.class); + if (serviceImplementation == null) { + continue; + } + if (method.getParameterCount() != 1) { + throw new IllegalArgumentException(String.format( + "Method '%s' in class '%s'" + " has wrong parameter count. Expected 1, got %d", + method.getName(), instance.getClass().getCanonicalName(), + method.getParameterCount() + )); } - map.put(new AnnotatedMethodService<>(instance, method), - TypeToken.get(serviceImplementation.value())); + map.put( + new AnnotatedMethodService<>(instance, method), + TypeToken.get(serviceImplementation.value()) + ); } return map; } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ChunkedRequestContext.java b/cloud-services/src/main/java/cloud/commandframework/services/ChunkedRequestContext.java index ea7811e7..dc23b194 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ChunkedRequestContext.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ChunkedRequestContext.java @@ -55,27 +55,27 @@ public abstract class ChunkedRequestContext<@NonNull Context, @NonNull Result> { this.results = new HashMap<>(requests.size()); } - /** - * Get a view of the (currently) available results - * - * @return Unmodifiable map of results - */ - public final @NonNull Map<@NonNull Context, @NonNull Result> getAvailableResults() { - synchronized (this.lock) { - return Collections.unmodifiableMap(this.results); + /** + * Get a view of the (currently) available results + * + * @return Unmodifiable map of results + */ + public final @NonNull Map<@NonNull Context, @NonNull Result> getAvailableResults() { + synchronized (this.lock) { + return Collections.unmodifiableMap(this.results); + } } - } - /** - * Get all remaining requests - * - * @return Unmodifiable list of remaining requests - */ - public final @NonNull List<@NonNull Context> getRemaining() { - synchronized (this.lock) { - return Collections.unmodifiableList(this.requests); + /** + * Get all remaining requests + * + * @return Unmodifiable list of remaining requests + */ + public final @NonNull List<@NonNull Context> getRemaining() { + synchronized (this.lock) { + return Collections.unmodifiableList(this.requests); + } } - } /** * Store a result for a specific context @@ -90,11 +90,11 @@ public abstract class ChunkedRequestContext<@NonNull Context, @NonNull Result> { } } - /** - * Check if the request has been completed - * - * @return {@code true} if the request has been completed, {@code false} if not - */ + /** + * Check if the request has been completed + * + * @return {@code true} if the request has been completed, {@code false} if not + */ public final boolean isCompleted() { synchronized (this.lock) { return this.requests.isEmpty(); diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ExecutionOrder.java b/cloud-services/src/main/java/cloud/commandframework/services/ExecutionOrder.java index 3dd3cdee..2b54e5f5 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ExecutionOrder.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ExecutionOrder.java @@ -28,5 +28,10 @@ package cloud.commandframework.services; */ @SuppressWarnings("unused") public enum ExecutionOrder { - LAST, LATER, LATE, SOON, SOONER, FIRST + LAST, + LATER, + LATE, + SOON, + SOONER, + FIRST } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ServiceFilterHandler.java b/cloud-services/src/main/java/cloud/commandframework/services/ServiceFilterHandler.java index f40874de..2e8dcea8 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ServiceFilterHandler.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ServiceFilterHandler.java @@ -33,7 +33,8 @@ enum ServiceFilterHandler { boolean passes( final @NonNull ServiceRepository.ServiceWrapper> service, - final @NonNull Context context) { + final @NonNull Context context + ) { if (!service.isDefaultImplementation()) { for (final Predicate predicate : service.getFilters()) { try { @@ -43,7 +44,8 @@ enum ServiceFilterHandler { } catch (final Exception e) { throw new PipelineException(String .format("Failed to evaluate filter '%s' for '%s'", - predicate.getClass().getCanonicalName(), service.toString()), e); + predicate.getClass().getCanonicalName(), service.toString() + ), e); } } } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ServicePipeline.java b/cloud-services/src/main/java/cloud/commandframework/services/ServicePipeline.java index 3053f6ed..b7192f1f 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ServicePipeline.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ServicePipeline.java @@ -73,11 +73,15 @@ public final class ServicePipeline { */ public @NonNull ServicePipeline registerServiceType( final @NonNull TypeToken> type, - final @NonNull Service<@NonNull Context, @NonNull Result> defaultImplementation) { + final @NonNull Service<@NonNull Context, @NonNull Result> defaultImplementation + ) { synchronized (this.lock) { if (repositories.containsKey(type.getType())) { throw new IllegalArgumentException(String - .format("Service of type '%s' has already been registered", type.toString())); + .format( + "Service of type '%s' has already been registered", + type.toString() + )); } final ServiceRepository repository = new ServiceRepository<>(type); repository.registerImplementation(defaultImplementation, Collections.emptyList()); @@ -106,7 +110,8 @@ public final class ServicePipeline { */ @SuppressWarnings("unchecked") public @NonNull ServicePipeline registerMethods( - final @NonNull T instance) throws Exception { + final @NonNull T instance + ) throws Exception { synchronized (this.lock) { final Map, TypeToken>> services = AnnotatedMethodServiceFactory.INSTANCE.lookupServices(instance); @@ -118,8 +123,10 @@ public final class ServicePipeline { throw new IllegalArgumentException( String.format("No service registered for type '%s'", type.toString())); } - repository.registerImplementation(serviceEntry.getKey(), - Collections.emptyList()); + repository.registerImplementation( + serviceEntry.getKey(), + Collections.emptyList() + ); } } return this; @@ -141,7 +148,8 @@ public final class ServicePipeline { public ServicePipeline registerServiceImplementation( final @NonNull TypeToken> type, final @NonNull Service implementation, - final @NonNull Collection> filters) { + final @NonNull Collection> filters + ) { synchronized (this.lock) { final ServiceRepository repository = getRepository(type); repository.registerImplementation(implementation, filters); @@ -165,7 +173,8 @@ public final class ServicePipeline { public ServicePipeline registerServiceImplementation( final @NonNull Class> type, final @NonNull Service implementation, - final @NonNull Collection> filters) { + final @NonNull Collection> filters + ) { return registerServiceImplementation(TypeToken.get(type), implementation, filters); } @@ -183,9 +192,9 @@ public final class ServicePipeline { } @SuppressWarnings("unchecked") - @NonNull - ServiceRepository getRepository( - final @NonNull TypeToken> type) { + @NonNull ServiceRepository getRepository( + final @NonNull TypeToken> type + ) { final ServiceRepository repository = (ServiceRepository) this.repositories.get(type.getType()); if (repository == null) { @@ -213,12 +222,13 @@ public final class ServicePipeline { * @param The result type. * @param The service type. * @return Returns an collection of the {@link TypeToken}s of the implementations for a given - * service. Iterator order matches the priority when pumping contexts through the pipeline + * service. Iterator order matches the priority when pumping contexts through the pipeline */ @NonNull @SuppressWarnings("unchecked") public > Collection> getImplementations( - final @NonNull TypeToken type) { + final @NonNull TypeToken type + ) { ServiceRepository repository = getRepository(type); List> collection = new LinkedList<>(); final LinkedList.ServiceWrapper>> diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ServicePump.java b/cloud-services/src/main/java/cloud/commandframework/services/ServicePump.java index 26e537f5..80637c4c 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ServicePump.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ServicePump.java @@ -37,8 +37,10 @@ public final class ServicePump { private final ServicePipeline servicePipeline; private final Context context; - ServicePump(final @NonNull ServicePipeline servicePipeline, - final @NonNull Context context) { + ServicePump( + final @NonNull ServicePipeline servicePipeline, + final @NonNull Context context + ) { this.servicePipeline = servicePipeline; this.context = context; } @@ -51,7 +53,8 @@ public final class ServicePump { * @return Service spigot instance */ public @NonNull ServiceSpigot<@NonNull Context, @NonNull Result> through( - final @NonNull TypeToken> type) { + final @NonNull TypeToken> type + ) { return new ServiceSpigot<>(this.servicePipeline, this.context, type); } @@ -63,7 +66,8 @@ public final class ServicePump { * @return Service spigot instance */ public @NonNull ServiceSpigot<@NonNull Context, @NonNull Result> through( - final @NonNull Class> clazz) { + final @NonNull Class> clazz + ) { return this.through(TypeToken.get(clazz)); } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ServiceRepository.java b/cloud-services/src/main/java/cloud/commandframework/services/ServiceRepository.java index 71cfebff..ee3708b4 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ServiceRepository.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ServiceRepository.java @@ -23,9 +23,9 @@ // package cloud.commandframework.services; -import io.leangen.geantyref.TypeToken; import cloud.commandframework.services.annotations.Order; import cloud.commandframework.services.types.Service; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.Collection; @@ -66,8 +66,10 @@ public final class ServiceRepository { * @param filters Filters that will be used to determine whether or not the service gets used * @param Type of the implementation */ - > void registerImplementation(final @NonNull T service, - final @NonNull Collection> filters) { + > void registerImplementation( + final @NonNull T service, + final @NonNull Collection> filters + ) { synchronized (this.lock) { this.implementations.add(new ServiceWrapper<>(service, filters)); } @@ -101,8 +103,10 @@ public final class ServiceRepository { private final int registrationOrder = ServiceRepository.this.registrationOrder++; private final ExecutionOrder executionOrder; - private ServiceWrapper(final @NonNull T implementation, - final @NonNull Collection> filters) { + private ServiceWrapper( + final @NonNull T implementation, + final @NonNull Collection> filters + ) { this.defaultImplementation = implementations.isEmpty(); this.implementation = implementation; this.filters = filters; @@ -136,15 +140,16 @@ public final class ServiceRepository { public String toString() { return String .format("ServiceWrapper{type=%s,implementation=%s}", serviceType.toString(), - TypeToken.get(implementation.getClass()).toString()); + TypeToken.get(implementation.getClass()).toString() + ); } @Override public int compareTo(final @NonNull ServiceWrapper other) { return Comparator.>comparingInt( wrapper -> wrapper.isDefaultImplementation() - ? Integer.MIN_VALUE - : Integer.MAX_VALUE).thenComparingInt(wrapper -> wrapper.executionOrder.ordinal()) + ? Integer.MIN_VALUE + : Integer.MAX_VALUE).thenComparingInt(wrapper -> wrapper.executionOrder.ordinal()) .thenComparingInt(wrapper -> wrapper.registrationOrder).compare(this, other); } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/ServiceSpigot.java b/cloud-services/src/main/java/cloud/commandframework/services/ServiceSpigot.java index 2a766184..e50c4f1e 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/ServiceSpigot.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/ServiceSpigot.java @@ -23,10 +23,10 @@ // package cloud.commandframework.services; -import io.leangen.geantyref.TypeToken; import cloud.commandframework.services.types.ConsumerService; import cloud.commandframework.services.types.Service; import cloud.commandframework.services.types.SideEffectService; +import io.leangen.geantyref.TypeToken; import org.checkerframework.checker.nullness.qual.NonNull; import java.util.LinkedList; @@ -45,9 +45,11 @@ public final class ServiceSpigot { private final ServicePipeline pipeline; private final ServiceRepository repository; - ServiceSpigot(final @NonNull ServicePipeline pipeline, - final @NonNull Context context, - final @NonNull TypeToken> type) { + ServiceSpigot( + final @NonNull ServicePipeline pipeline, + final @NonNull Context context, + final @NonNull TypeToken> type + ) { this.context = context; this.pipeline = pipeline; this.repository = pipeline.getRepository(type); @@ -71,7 +73,7 @@ public final class ServiceSpigot { * PipelineException}. Use {@link PipelineException#getCause()} to * get the exception that was thrown. * @see PipelineException PipelineException wraps exceptions thrown during filtering and result - * retrieval + * retrieval */ @SuppressWarnings("unchecked") public @NonNull Result getResult() diff --git a/cloud-services/src/main/java/cloud/commandframework/services/annotations/Order.java b/cloud-services/src/main/java/cloud/commandframework/services/annotations/Order.java index 337a9e86..02e790cc 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/annotations/Order.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/annotations/Order.java @@ -43,4 +43,5 @@ public @interface Order { * @return Priority */ ExecutionOrder value() default ExecutionOrder.SOON; + } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/annotations/ServiceImplementation.java b/cloud-services/src/main/java/cloud/commandframework/services/annotations/ServiceImplementation.java index a3c6576b..861cf7e2 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/annotations/ServiceImplementation.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/annotations/ServiceImplementation.java @@ -45,10 +45,11 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) public @interface ServiceImplementation { - /** + /** * The service class that the method implements * * @return Service to implement */ Class> value(); + } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/types/ConsumerService.java b/cloud-services/src/main/java/cloud/commandframework/services/types/ConsumerService.java index 59bb411e..1e9d7f6c 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/types/ConsumerService.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/types/ConsumerService.java @@ -38,52 +38,52 @@ import java.util.function.Consumer; */ @FunctionalInterface public interface ConsumerService - extends SideEffectService, Consumer { + extends SideEffectService, Consumer { - /** - * Immediately terminate the execution and return {@link State#ACCEPTED} - * - * @throws PipeBurst Pipe burst - */ - static void interrupt() throws PipeBurst { - throw new PipeBurst(); - } - - @Override - default @NonNull State handle(final @NonNull Context context) { - try { - this.accept(context); - } catch (final PipeBurst burst) { - return State.ACCEPTED; - } - return State.REJECTED; - } - - /** - * Accept the context. Call {@link #interrupt()} to interrupt the entire pipeline and immediately - * return {@link State#ACCEPTED} to the sink - * - * @param context Context to consume - */ - @Override - void accept(@NonNull Context context); - - - class PipeBurst extends RuntimeException { - - private PipeBurst() { + /** + * Immediately terminate the execution and return {@link State#ACCEPTED} + * + * @throws PipeBurst Pipe burst + */ + static void interrupt() throws PipeBurst { + throw new PipeBurst(); } @Override - public synchronized Throwable fillInStackTrace() { - return this; + default @NonNull State handle(final @NonNull Context context) { + try { + this.accept(context); + } catch (final PipeBurst burst) { + return State.ACCEPTED; + } + return State.REJECTED; } + /** + * Accept the context. Call {@link #interrupt()} to interrupt the entire pipeline and immediately + * return {@link State#ACCEPTED} to the sink + * + * @param context Context to consume + */ @Override - public synchronized Throwable initCause(final Throwable cause) { - return this; - } + void accept(@NonNull Context context); - } + + class PipeBurst extends RuntimeException { + + private PipeBurst() { + } + + @Override + public synchronized Throwable fillInStackTrace() { + return this; + } + + @Override + public synchronized Throwable initCause(final Throwable cause) { + return this; + } + + } } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/types/PartialResultService.java b/cloud-services/src/main/java/cloud/commandframework/services/types/PartialResultService.java index a3638767..495696e7 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/types/PartialResultService.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/types/PartialResultService.java @@ -38,26 +38,26 @@ import java.util.Map; * @param Chunk request context */ public interface PartialResultService> - extends Service> { + extends Service> { - @Override - default @Nullable Map<@NonNull Context, @NonNull Result> handle(final @NonNull Chunked context) { - if (!context.isCompleted()) { - this.handleRequests(context.getRemaining()).forEach(context::storeResult); + @Override + default @Nullable Map<@NonNull Context, @NonNull Result> handle(final @NonNull Chunked context) { + if (!context.isCompleted()) { + this.handleRequests(context.getRemaining()).forEach(context::storeResult); + } + if (context.isCompleted()) { + return context.getAvailableResults(); + } + return null; } - if (context.isCompleted()) { - return context.getAvailableResults(); - } - return null; - } - /** - * Attempt to generate results for a list of requests, and return a map of all successful - * requests - * - * @param requests Requests - * @return Map of request-result pairs - */ - @NonNull Map<@NonNull Context, @NonNull Result> handleRequests(@NonNull List requests); + /** + * Attempt to generate results for a list of requests, and return a map of all successful + * requests + * + * @param requests Requests + * @return Map of request-result pairs + */ + @NonNull Map<@NonNull Context, @NonNull Result> handleRequests(@NonNull List requests); } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/types/Service.java b/cloud-services/src/main/java/cloud/commandframework/services/types/Service.java index 7bffe09f..2647de04 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/types/Service.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/types/Service.java @@ -41,36 +41,36 @@ import java.util.function.Function; @FunctionalInterface public interface Service extends Function<@NonNull Context, @Nullable Result> { - /** - * Provide a response for the given context. If the service implementation cannot provide a - * response for the given context, it should return {@code null} - * - * @param context Context used in the generation of the response - * @return Response. If the response isn't {@code null}, the next service in the service chain - * will get to act on the context. Otherwise the execution halts, and the provided response is the - * final response. - * @throws Exception Any exception that occurs during the handling can be thrown, and will be - * wrapped by a {@link PipelineException} - */ - @Nullable Result handle(@NonNull Context context) throws Exception; + /** + * Provide a response for the given context. If the service implementation cannot provide a + * response for the given context, it should return {@code null} + * + * @param context Context used in the generation of the response + * @return Response. If the response isn't {@code null}, the next service in the service chain + * will get to act on the context. Otherwise the execution halts, and the provided response is the + * final response. + * @throws Exception Any exception that occurs during the handling can be thrown, and will be + * wrapped by a {@link PipelineException} + */ + @Nullable Result handle(@NonNull Context context) throws Exception; - @Override - default @Nullable Result apply(@NonNull Context context) { - try { - return this.handle(context); - } catch (final Exception exception) { - throw new PipelineException(exception); + @Override + default @Nullable Result apply(@NonNull Context context) { + try { + return this.handle(context); + } catch (final Exception exception) { + throw new PipelineException(exception); + } } - } - /** - * Get the execution order of the service. This should not be overridden, unless you know what you - * are doing - * - * @return Execution order - */ - default @Nullable ExecutionOrder order() { - return null; - } + /** + * Get the execution order of the service. This should not be overridden, unless you know what you + * are doing + * + * @return Execution order + */ + default @Nullable ExecutionOrder order() { + return null; + } } diff --git a/cloud-services/src/main/java/cloud/commandframework/services/types/SideEffectService.java b/cloud-services/src/main/java/cloud/commandframework/services/types/SideEffectService.java index 679b958b..7a319a2c 100644 --- a/cloud-services/src/main/java/cloud/commandframework/services/types/SideEffectService.java +++ b/cloud-services/src/main/java/cloud/commandframework/services/types/SideEffectService.java @@ -36,18 +36,18 @@ import org.checkerframework.checker.nullness.qual.NonNull; @FunctionalInterface public interface SideEffectService extends Service { - /** - * Consumes the context, if possible. Returns {@link State#ACCEPTED} if the input was consumed, - * else {@link State#REJECTED} - * - * @param context context used in the generation of the response - * @return Response. If the response isn't {@link State#ACCEPTED}, the next service in the service - * chain will get to act on the context. Otherwise the execution halts, and the provided response - * is the final response. - * @throws Exception Any exception that occurs during the handling can be thrown, and will be - * wrapped by a {@link cloud.commandframework.services.PipelineException} - */ - @Override - @NonNull State handle(@NonNull Context context) throws Exception; + /** + * Consumes the context, if possible. Returns {@link State#ACCEPTED} if the input was consumed, + * else {@link State#REJECTED} + * + * @param context context used in the generation of the response + * @return Response. If the response isn't {@link State#ACCEPTED}, the next service in the service + * chain will get to act on the context. Otherwise the execution halts, and the provided response + * is the final response. + * @throws Exception Any exception that occurs during the handling can be thrown, and will be + * wrapped by a {@link cloud.commandframework.services.PipelineException} + */ + @Override + @NonNull State handle(@NonNull Context context) throws Exception; } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/ServicesTest.java b/cloud-services/src/test/java/cloud/commandframework/services/ServicesTest.java index 24c87bec..4da68b45 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/ServicesTest.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/ServicesTest.java @@ -67,22 +67,31 @@ public class ServicesTest { final SecondaryMockService secondaryMockService = new SecondaryMockService(); servicePipeline .registerServiceImplementation(TypeToken.get(MockService.class), secondaryMockService, - Collections.singleton(secondaryMockService)); - servicePipeline.registerServiceImplementation(MockService.class, + Collections.singleton(secondaryMockService) + ); + servicePipeline.registerServiceImplementation( + MockService.class, mockContext -> new MockService.MockResult(-91), - Collections.singleton(mockContext -> mockContext.getString().startsWith("-91"))); - Assertions.assertEquals(32, + Collections.singleton(mockContext -> mockContext.getString().startsWith("-91")) + ); + Assertions.assertEquals( + 32, servicePipeline.pump(new MockService.MockContext("Hello")).through(MockService.class) - .getResult().getInteger()); + .getResult().getInteger() + ); servicePipeline.pump(new MockService.MockContext("Hello")).through(MockService.class) .getResult( (mockResult, throwable) -> Assertions.assertEquals(32, mockResult.getInteger())); - Assertions.assertEquals(999, + Assertions.assertEquals( + 999, servicePipeline.pump(new MockService.MockContext("potato")).through(MockService.class) - .getResult().getInteger()); - Assertions.assertEquals(-91, + .getResult().getInteger() + ); + Assertions.assertEquals( + -91, servicePipeline.pump(new MockService.MockContext("-91")).through(MockService.class) - .getResult().getInteger()); + .getResult().getInteger() + ); Assertions.assertNotNull( servicePipeline.pump(new MockService.MockContext("oi")).through(MockService.class) .getResultAsynchronously().get()); @@ -92,66 +101,98 @@ public class ServicesTest { @Test public void testSideEffectServices() { final ServicePipeline servicePipeline = ServicePipeline.builder().build(); - servicePipeline.registerServiceType(TypeToken.get(MockSideEffectService.class), - new DefaultSideEffectService()); + servicePipeline.registerServiceType( + TypeToken.get(MockSideEffectService.class), + new DefaultSideEffectService() + ); final MockSideEffectService.MockPlayer mockPlayer = new MockSideEffectService.MockPlayer(20); Assertions.assertEquals(20, mockPlayer.getHealth()); - Assertions.assertEquals(State.ACCEPTED, - servicePipeline.pump(mockPlayer).through(MockSideEffectService.class).getResult()); + Assertions.assertEquals( + State.ACCEPTED, + servicePipeline.pump(mockPlayer).through(MockSideEffectService.class).getResult() + ); Assertions.assertEquals(0, mockPlayer.getHealth()); mockPlayer.setHealth(20); servicePipeline.registerServiceImplementation(MockSideEffectService.class, - new SecondaryMockSideEffectService(), Collections.emptyList()); - Assertions.assertThrows(IllegalStateException.class, + new SecondaryMockSideEffectService(), Collections.emptyList() + ); + Assertions.assertThrows( + IllegalStateException.class, () -> servicePipeline.pump(mockPlayer).through(MockSideEffectService.class) - .getResult()); + .getResult() + ); } @Test public void testForwarding() throws Exception { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockService.class), new DefaultMockService()) - .registerServiceType(TypeToken.get(MockResultConsumer.class), new MockResultConsumer()); - Assertions.assertEquals(State.ACCEPTED, + .registerServiceType( + TypeToken.get(MockService.class), + new DefaultMockService() + ) + .registerServiceType( + TypeToken.get(MockResultConsumer.class), + new MockResultConsumer() + ); + Assertions.assertEquals( + State.ACCEPTED, servicePipeline.pump(new MockService.MockContext("huh")).through(MockService.class) - .forward().through(MockResultConsumer.class).getResult()); - Assertions.assertEquals(State.ACCEPTED, + .forward().through(MockResultConsumer.class).getResult() + ); + Assertions.assertEquals( + State.ACCEPTED, servicePipeline.pump(new MockService.MockContext("Something")) .through(MockService.class).forwardAsynchronously() .thenApply(pump -> pump.through(MockResultConsumer.class)) - .thenApply(ServiceSpigot::getResult).get()); + .thenApply(ServiceSpigot::getResult).get() + ); } @Test public void testSorting() { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockService.class), new DefaultMockService()); + .registerServiceType( + TypeToken.get(MockService.class), + new DefaultMockService() + ); servicePipeline.registerServiceImplementation(MockService.class, new MockOrderedFirst(), - Collections.emptyList()); + Collections.emptyList() + ); servicePipeline.registerServiceImplementation(MockService.class, new MockOrderedLast(), - Collections.emptyList()); + Collections.emptyList() + ); // Test that the annotations worked - Assertions.assertEquals(1, + Assertions.assertEquals( + 1, servicePipeline.pump(new MockService.MockContext("")).through(MockService.class) - .getResult().getInteger()); + .getResult().getInteger() + ); } @Test public void testRecognisedTypes() { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockService.class), new DefaultMockService()); + .registerServiceType( + TypeToken.get(MockService.class), + new DefaultMockService() + ); Assertions.assertEquals(1, servicePipeline.getRecognizedTypes().size()); } @Test public void testImplementationGetters() { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockService.class), new DefaultMockService()); + .registerServiceType( + TypeToken.get(MockService.class), + new DefaultMockService() + ); servicePipeline.registerServiceImplementation(MockService.class, new MockOrderedFirst(), - Collections.emptyList()); + Collections.emptyList() + ); servicePipeline.registerServiceImplementation(MockService.class, new MockOrderedLast(), - Collections.emptyList()); + Collections.emptyList() + ); final TypeToken> first = TypeToken.get(MockOrderedFirst.class), last = TypeToken.get(MockOrderedLast.class); final TypeToken mockServiceType = TypeToken.get(MockService.class); @@ -171,21 +212,31 @@ public class ServicesTest { @Test public void testAnnotatedMethods() throws Exception { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockService.class), new DefaultMockService()) + .registerServiceType( + TypeToken.get(MockService.class), + new DefaultMockService() + ) .registerMethods(new AnnotatedMethodTest()); final String testString = UUID.randomUUID().toString(); - Assertions.assertEquals(testString.length(), + Assertions.assertEquals( + testString.length(), servicePipeline.pump(new MockService.MockContext(testString)).through(MockService.class) - .getResult().getInteger()); + .getResult().getInteger() + ); } @Test public void testConsumerServices() { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockConsumerService.class), - new StateSettingConsumerService()) - .registerServiceImplementation(MockConsumerService.class, - new InterruptingMockConsumer(), Collections.emptyList()); + .registerServiceType( + TypeToken.get(MockConsumerService.class), + new StateSettingConsumerService() + ) + .registerServiceImplementation( + MockConsumerService.class, + new InterruptingMockConsumer(), + Collections.emptyList() + ); final MockService.MockContext context = new MockService.MockContext(""); servicePipeline.pump(context).through(MockConsumerService.class).getResult(); Assertions.assertEquals("", context.getState()); @@ -194,10 +245,15 @@ public class ServicesTest { @Test public void testPartialResultServices() { final ServicePipeline servicePipeline = ServicePipeline.builder().build() - .registerServiceType(TypeToken.get(MockPartialResultService.class), - new DefaultPartialRequestService()) - .registerServiceImplementation(MockPartialResultService.class, - new CompletingPartialResultService(), Collections.emptyList()); + .registerServiceType( + TypeToken.get(MockPartialResultService.class), + new DefaultPartialRequestService() + ) + .registerServiceImplementation( + MockPartialResultService.class, + new CompletingPartialResultService(), + Collections.emptyList() + ); final MockChunkedRequest.Animal cow = new MockChunkedRequest.Animal("cow"); final MockChunkedRequest.Animal dog = new MockChunkedRequest.Animal("dog"); final MockChunkedRequest.Animal cat = new MockChunkedRequest.Animal("cat"); @@ -215,16 +271,22 @@ public class ServicesTest { Assertions.assertNotNull(servicePipeline); servicePipeline .registerServiceType(TypeToken.get(MockService.class), new DefaultMockService()); - final PipelineException pipelineException = Assertions.assertThrows(PipelineException.class, + final PipelineException pipelineException = Assertions.assertThrows( + PipelineException.class, () -> servicePipeline.pump(new MockService.MockContext("pls throw exception")) - .through(MockService.class).getResult()); - Assertions.assertEquals(DefaultMockService.TotallyIntentionalException.class, - pipelineException.getCause().getClass()); + .through(MockService.class).getResult() + ); + Assertions.assertEquals( + DefaultMockService.TotallyIntentionalException.class, + pipelineException.getCause().getClass() + ); servicePipeline.pump(new MockService.MockContext("pls throw exception")) .through(MockService.class).getResult((result, throwable) -> { Assertions.assertNotNull(throwable); - Assertions.assertEquals(DefaultMockService.TotallyIntentionalException.class, - throwable.getClass()); + Assertions.assertEquals( + DefaultMockService.TotallyIntentionalException.class, + throwable.getClass() + ); Assertions.assertNull(result); }); } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/CompletingPartialResultService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/CompletingPartialResultService.java index d2c31b65..156d33d2 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/CompletingPartialResultService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/CompletingPartialResultService.java @@ -29,17 +29,17 @@ import java.util.Map; public class CompletingPartialResultService implements MockPartialResultService { - @Override - public Map handleRequests(List requests) { - final Map map = new HashMap<>(); - for (final MockChunkedRequest.Animal animal : requests) { - if (animal.getName().equals("cow")) { - map.put(animal, new MockChunkedRequest.Sound("moo")); - } else if (animal.getName().equals("dog")) { - map.put(animal, new MockChunkedRequest.Sound("woof")); - } + @Override + public Map handleRequests(List requests) { + final Map map = new HashMap<>(); + for (final MockChunkedRequest.Animal animal : requests) { + if (animal.getName().equals("cow")) { + map.put(animal, new MockChunkedRequest.Sound("moo")); + } else if (animal.getName().equals("dog")) { + map.put(animal, new MockChunkedRequest.Sound("woof")); + } + } + return map; } - return map; - } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultMockService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultMockService.java index 0dad4ac5..12806150 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultMockService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultMockService.java @@ -25,19 +25,19 @@ package cloud.commandframework.services.mock; public class DefaultMockService implements MockService { - @Override - public MockResult handle(final MockContext mockContext) - throws Exception { - if (mockContext.getString().equals("pls throw exception")) { - throw new TotallyIntentionalException(); + @Override + public MockResult handle(final MockContext mockContext) + throws Exception { + if (mockContext.getString().equals("pls throw exception")) { + throw new TotallyIntentionalException(); + } + return new MockResult(32); } - return new MockResult(32); - } - public static class TotallyIntentionalException extends Exception { + public static class TotallyIntentionalException extends Exception { - } + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultPartialRequestService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultPartialRequestService.java index f79becfa..e745b9e6 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultPartialRequestService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultPartialRequestService.java @@ -29,14 +29,14 @@ import java.util.Map; public class DefaultPartialRequestService implements MockPartialResultService { - @Override - public Map handleRequests(final List requests) { - final Map map = - new HashMap<>(requests.size()); - for (final MockChunkedRequest.Animal animal : requests) { - map.put(animal, new MockChunkedRequest.Sound("unknown")); + @Override + public Map handleRequests(final List requests) { + final Map map = + new HashMap<>(requests.size()); + for (final MockChunkedRequest.Animal animal : requests) { + map.put(animal, new MockChunkedRequest.Sound("unknown")); + } + return map; } - return map; - } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultSideEffectService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultSideEffectService.java index 8e624d53..727d55ce 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultSideEffectService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/DefaultSideEffectService.java @@ -27,10 +27,10 @@ import cloud.commandframework.services.State; public class DefaultSideEffectService implements MockSideEffectService { - @Override - public State handle(final MockPlayer mockPlayer) { - mockPlayer.setHealth(0); - return State.ACCEPTED; - } + @Override + public State handle(final MockPlayer mockPlayer) { + mockPlayer.setHealth(0); + return State.ACCEPTED; + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/InterruptingMockConsumer.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/InterruptingMockConsumer.java index 1e9b25a5..d6c8bc61 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/InterruptingMockConsumer.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/InterruptingMockConsumer.java @@ -27,9 +27,9 @@ import cloud.commandframework.services.types.ConsumerService; public class InterruptingMockConsumer implements MockConsumerService { - @Override - public void accept(final MockService.MockContext mockContext) { - ConsumerService.interrupt(); - } + @Override + public void accept(final MockService.MockContext mockContext) { + ConsumerService.interrupt(); + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockChunkedRequest.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockChunkedRequest.java index 708909fa..3c7afc4b 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockChunkedRequest.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockChunkedRequest.java @@ -28,37 +28,39 @@ import cloud.commandframework.services.ChunkedRequestContext; import java.util.Collection; public class MockChunkedRequest - extends ChunkedRequestContext { + extends ChunkedRequestContext { - public MockChunkedRequest(final Collection requests) { - super(requests); - } - - public static class Animal { - - private final String name; - - public Animal(final String name) { - this.name = name; + public MockChunkedRequest(final Collection requests) { + super(requests); } - public String getName() { - return this.name; - } - } + public static class Animal { + private final String name; - public static class Sound { + public Animal(final String name) { + this.name = name; + } - private final String sound; + public String getName() { + return this.name; + } - public Sound(final String sound) { - this.sound = sound; } - public String getSound() { - return this.sound; + + public static class Sound { + + private final String sound; + + public Sound(final String sound) { + this.sound = sound; + } + + public String getSound() { + return this.sound; + } + } - } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedFirst.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedFirst.java index 0e973696..06c810af 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedFirst.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedFirst.java @@ -29,9 +29,9 @@ import cloud.commandframework.services.annotations.Order; @Order(ExecutionOrder.FIRST) public class MockOrderedFirst implements MockService { - @Override - public MockResult handle(final MockContext mockContext) { - return new MockResult(1); - } + @Override + public MockResult handle(final MockContext mockContext) { + return new MockResult(1); + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedLast.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedLast.java index 8d1dcad1..c9f3cc87 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedLast.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockOrderedLast.java @@ -29,9 +29,9 @@ import cloud.commandframework.services.annotations.Order; @Order(ExecutionOrder.LAST) public class MockOrderedLast implements MockService { - @Override - public MockResult handle(final MockContext mockContext) { - return new MockResult(2); - } + @Override + public MockResult handle(final MockContext mockContext) { + return new MockResult(2); + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockPartialResultService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockPartialResultService.java index 6f4a45a6..2b56be0c 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockPartialResultService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockPartialResultService.java @@ -26,6 +26,6 @@ package cloud.commandframework.services.mock; import cloud.commandframework.services.types.PartialResultService; public interface MockPartialResultService extends - PartialResultService { + PartialResultService { } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockResultConsumer.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockResultConsumer.java index c6714447..14d00642 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockResultConsumer.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockResultConsumer.java @@ -28,9 +28,9 @@ import cloud.commandframework.services.types.SideEffectService; public class MockResultConsumer implements SideEffectService { - @Override - public State handle(final MockService.MockResult mockResultConsumer) { - return State.ACCEPTED; - } + @Override + public State handle(final MockService.MockResult mockResultConsumer) { + return State.ACCEPTED; + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockService.java index b9daaea9..6a8237ec 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/MockService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/MockService.java @@ -29,24 +29,24 @@ public interface MockService extends Service { - @Override - public MockResult handle(final MockContext mockContext) { - return new MockResult(999); - } + @Override + public MockResult handle(final MockContext mockContext) { + return new MockResult(999); + } - @Override - public boolean test(final MockContext mockContext) { - return mockContext.getString().equalsIgnoreCase("potato"); - } + @Override + public boolean test(final MockContext mockContext) { + return mockContext.getString().equalsIgnoreCase("potato"); + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/SecondaryMockSideEffectService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/SecondaryMockSideEffectService.java index ca881c4e..d4dedd6b 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/SecondaryMockSideEffectService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/SecondaryMockSideEffectService.java @@ -27,9 +27,9 @@ import cloud.commandframework.services.State; public class SecondaryMockSideEffectService implements MockSideEffectService { - @Override - public State handle(final MockPlayer mockPlayer) { - return null; - } + @Override + public State handle(final MockPlayer mockPlayer) { + return null; + } } diff --git a/cloud-services/src/test/java/cloud/commandframework/services/mock/StateSettingConsumerService.java b/cloud-services/src/test/java/cloud/commandframework/services/mock/StateSettingConsumerService.java index 5d2cf8cc..387415ad 100644 --- a/cloud-services/src/test/java/cloud/commandframework/services/mock/StateSettingConsumerService.java +++ b/cloud-services/src/test/java/cloud/commandframework/services/mock/StateSettingConsumerService.java @@ -25,9 +25,9 @@ package cloud.commandframework.services.mock; public class StateSettingConsumerService implements MockConsumerService { - @Override - public void accept(final MockService.MockContext mockContext) { - mockContext.setState(""); - } + @Override + public void accept(final MockService.MockContext mockContext) { + mockContext.setState(""); + } } diff --git a/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskFunction.java b/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskFunction.java index ca0ee3e7..dbb946c0 100644 --- a/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskFunction.java +++ b/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskFunction.java @@ -35,12 +35,6 @@ import java.util.function.Function; */ public interface TaskFunction extends Function<@NonNull I, @NonNull O>, TaskRecipeStep { - /** - * {@inheritDoc} - */ - @Override - @NonNull O apply(@NonNull I input); - /** * Equivalent to {@link Function#identity()} * @@ -51,4 +45,10 @@ public interface TaskFunction extends Function<@NonNull I, @NonNull O>, Ta return i -> i; } + /** + * {@inheritDoc} + */ + @Override + @NonNull O apply(@NonNull I input); + } diff --git a/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipe.java b/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipe.java index 64781e24..2eac2a6a 100644 --- a/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipe.java +++ b/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipe.java @@ -50,7 +50,7 @@ public final class TaskRecipe { * * @param input Input * @param Input type - * @return Function that maps the input to itself + * @return Function that maps the input to itself */ public @NonNull TaskRecipeComponentOutputting begin(final @NonNull I input) { this.addAsynchronous(TaskFunction.identity()); @@ -71,8 +71,10 @@ public final class TaskRecipe { completableFuture.whenComplete(this.execute(iterator, callback)); } - private BiConsumer execute(final @NonNull Iterator> iterator, - final @NonNull Runnable callback) { + private BiConsumer execute( + final @NonNull Iterator> iterator, + final @NonNull Runnable callback + ) { return (o, o2) -> { if (iterator.hasNext()) { final Map.Entry entry = iterator.next(); @@ -121,7 +123,7 @@ public final class TaskRecipe { * Add a new synchronous step, consuming the input of the earlier step * * @param function Function mapping the input to some output - * @param Output type + * @param Output type * @return New task recipe component */ public TaskRecipeComponentOutputting synchronous(final @NonNull TaskFunction function) { @@ -133,7 +135,7 @@ public final class TaskRecipe { * Add a new asynchronous step, consuming the input of the earlier step * * @param function Function mapping the input to some output - * @param Output type + * @param Output type * @return New task recipe component */ public TaskRecipeComponentOutputting asynchronous(final @NonNull TaskFunction function) { @@ -176,7 +178,8 @@ public final class TaskRecipe { * Execute the recipe */ public void execute() { - this.execute(() -> {}); + this.execute(() -> { + }); } } @@ -229,7 +232,8 @@ public final class TaskRecipe { * Execute the recipe */ public void execute() { - this.execute(() -> {}); + this.execute(() -> { + }); } } diff --git a/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipeStep.java b/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipeStep.java index 7684e2e1..22d0f42d 100644 --- a/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipeStep.java +++ b/cloud-tasks/src/main/java/cloud/commandframework/tasks/TaskRecipeStep.java @@ -27,4 +27,5 @@ package cloud.commandframework.tasks; * Part of a {@link TaskRecipe} */ public interface TaskRecipeStep { + } diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index ec754c81..81cc5265 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -79,7 +79,7 @@ + default="checkstyle-suppressions.xml"/> @@ -100,7 +100,7 @@ - + @@ -131,7 +131,7 @@ - + @@ -210,7 +210,7 @@ + default="checkstyle-xpath-suppressions.xml"/> diff --git a/examples/example-bukkit/src/main/java/cloud/commandframework/examples/bukkit/ExamplePlugin.java b/examples/example-bukkit/src/main/java/cloud/commandframework/examples/bukkit/ExamplePlugin.java index 04aaffe2..8d0b0f0c 100644 --- a/examples/example-bukkit/src/main/java/cloud/commandframework/examples/bukkit/ExamplePlugin.java +++ b/examples/example-bukkit/src/main/java/cloud/commandframework/examples/bukkit/ExamplePlugin.java @@ -89,7 +89,7 @@ public final class ExamplePlugin extends JavaPlugin { // asynchronously // final Function, CommandExecutionCoordinator> executionCoordinatorFunction = - AsynchronousCommandExecutionCoordinator.newBuilder().build(); + AsynchronousCommandExecutionCoordinator.newBuilder().build(); // // However, in many cases it is fine for to run everything synchronously: // @@ -161,9 +161,9 @@ public final class ExamplePlugin extends JavaPlugin { // final Function commandMetaFunction = p -> BukkitCommandMetaBuilder.builder() - // This will allow you to decorate commands with descriptions - .withDescription(p.get(StandardParameters.DESCRIPTION, "No description")) - .build(); + // This will allow you to decorate commands with descriptions + .withDescription(p.get(StandardParameters.DESCRIPTION, "No description")) + .build(); this.annotationParser = new AnnotationParser<>( /* Manager */ this.manager, /* Command sender type */ CommandSender.class, @@ -188,8 +188,8 @@ public final class ExamplePlugin extends JavaPlugin { // Add a confirmation command // this.manager.command(builder.literal("confirm") - .meta("description", "Confirm a pending command") - .handler(this.confirmationManager.createConfirmationExecutionHandler())); + .meta("description", "Confirm a pending command") + .handler(this.confirmationManager.createConfirmationExecutionHandler())); // // Create a world argument // @@ -198,63 +198,70 @@ public final class ExamplePlugin extends JavaPlugin { // Create a teleportation command // this.manager.command(builder.literal("teleport") - .literal("me") - // Require a player sender - .withSenderType(Player.class) - .argument(worldArgument, Description.of("World name")) - .argumentTriplet( - "coords", - TypeToken.get(Vector.class), - Triplet.of("x", "y", "z"), - Triplet.of(Integer.class, Integer.class, Integer.class), - (sender, triplet) -> new Vector(triplet.getFirst(), triplet.getSecond(), - triplet.getThird()), - Description.of("Coordinates")) - .handler(context -> manager.taskRecipe().begin(context) - .synchronous(commandContext -> { - final Player player = (Player) commandContext.getSender(); - final World world = commandContext.get(worldArgument); - final Vector coords = commandContext.get("coords"); - final Location location = coords.toLocation(world); - player.teleport(location); - }).execute())) - .command(builder.literal("teleport") - .literal("entity") - .withSenderType(Player.class) - .argument(SingleEntitySelectorArgument.of("entity"), - Description.of("Entity to teleport")) - .literal("here") - .handler( - context -> manager.taskRecipe().begin(context) - .synchronous(commandContext -> { - final Player player = (Player) commandContext.getSender(); - final SingleEntitySelector singleEntitySelector = commandContext.get("entity"); - if (singleEntitySelector.hasAny()) { - singleEntitySelector.getEntity().teleport(player); - player.sendMessage(ChatColor.GREEN + "The entity was teleported to you!"); - } else { - player.sendMessage(ChatColor.RED + "No entity matched your query."); - } - }).execute() - )); + .literal("me") + // Require a player sender + .senderType(Player.class) + .argument(worldArgument, Description.of("World name")) + .argumentTriplet( + "coords", + TypeToken.get(Vector.class), + Triplet.of("x", "y", "z"), + Triplet.of(Integer.class, Integer.class, Integer.class), + (sender, triplet) -> new Vector(triplet.getFirst(), triplet.getSecond(), + triplet.getThird() + ), + Description.of("Coordinates") + ) + .handler(context -> manager.taskRecipe().begin(context) + .synchronous(commandContext -> { + final Player player = (Player) commandContext.getSender(); + final World world = commandContext.get(worldArgument); + final Vector coords = commandContext.get("coords"); + final Location location = coords.toLocation(world); + player.teleport(location); + }).execute())) + .command(builder.literal("teleport") + .literal("entity") + .senderType(Player.class) + .argument( + SingleEntitySelectorArgument.of("entity"), + Description.of("Entity to teleport") + ) + .literal("here") + .handler( + context -> manager.taskRecipe().begin(context) + .synchronous(commandContext -> { + final Player player = (Player) commandContext.getSender(); + final SingleEntitySelector singleEntitySelector = commandContext + .get("entity"); + if (singleEntitySelector.hasAny()) { + singleEntitySelector.getEntity().teleport(player); + player.sendMessage(ChatColor.GREEN + "The entity was teleported to you!"); + } else { + player.sendMessage(ChatColor.RED + "No entity matched your query."); + } + }).execute() + )); manager.command(builder.literal("tasktest") - .handler(context -> manager.taskRecipe() - .begin(context) - .asynchronous(c -> { - c.getSender().sendMessage("ASYNC: " + !Bukkit.isPrimaryThread()); - return c; - }) - .synchronous(c -> { - c.getSender().sendMessage("SYNC: " + Bukkit.isPrimaryThread()); - }) - .execute(() -> context.getSender().sendMessage("DONE!")) - )); + .handler(context -> manager.taskRecipe() + .begin(context) + .asynchronous(c -> { + c.getSender().sendMessage("ASYNC: " + !Bukkit.isPrimaryThread()); + return c; + }) + .synchronous(c -> { + c.getSender().sendMessage("SYNC: " + Bukkit.isPrimaryThread()); + }) + .execute(() -> context.getSender().sendMessage("DONE!")) + )); } @CommandMethod("example help [query]") @CommandDescription("Help menu") - private void commandHelp(final @NonNull CommandSender sender, - final @Argument("query") @Greedy String query) { + private void commandHelp( + final @NonNull CommandSender sender, + final @Argument("query") @Greedy String query + ) { this.minecraftHelp.queryCommands(query == null ? "" : query, sender); } @@ -265,21 +272,25 @@ public final class ExamplePlugin extends JavaPlugin { private void commandClear(final @NonNull Player player) { player.getInventory().clear(); this.bukkitAudiences.player(player) - .sendMessage(Component.text("Your inventory has been cleared", NamedTextColor.GOLD)); + .sendMessage(Component.text("Your inventory has been cleared", NamedTextColor.GOLD)); } @CommandMethod("example give ") @CommandDescription("Give yourself an item") - private void commandGive(final @NonNull Player player, - final @NonNull @Argument("material") Material material, - final @Argument("amount") int number, - final @Nullable @Flag("color") ChatColor nameColor) { + private void commandGive( + final @NonNull Player player, + final @NonNull @Argument("material") Material material, + final @Argument("amount") int number, + final @Nullable @Flag("color") ChatColor nameColor + ) { final ItemStack itemStack = new ItemStack(material, number); - String itemName = String.format("%s's %s", - player.getName(), - material.name() - .toLowerCase() - .replace('_', ' ')); + String itemName = String.format( + "%s's %s", + player.getName(), + material.name() + .toLowerCase() + .replace('_', ' ') + ); if (nameColor != null) { itemName = nameColor + itemName; } diff --git a/icons/cloud.svg b/icons/cloud.svg index 6feaa377..0612542e 100644 --- a/icons/cloud.svg +++ b/icons/cloud.svg @@ -1,29 +1,62 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + +