From 94a920627d86d492cdbebb7c3635518c1bc55c4b Mon Sep 17 00:00:00 2001 From: YanSergey Date: Wed, 20 Oct 2021 13:53:19 +0300 Subject: [PATCH 1/6] =?UTF-8?q?=D0=9D=D0=B0=D1=81=D1=82=D1=80=D0=BE=D0=B9?= =?UTF-8?q?=D0=BA=D0=B8=20=D1=84=D0=BE=D1=80=D0=BC=D0=B0=D1=82=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=B8=20=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20codestyle?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- clusterAdminApplication/.checkstyle | 7 + clusterAdminApplication/.project | 10 +- .../.settings/org.eclipse.jdt.core.prefs | 385 ++++++++++++++++++ .../.settings/org.eclipse.jdt.ui.prefs | 7 + clusterAdminApplication/pom.xml | 27 ++ clusterAdminLibrary/.checkstyle | 10 + clusterAdminLibrary/.project | 6 + .../.settings/org.eclipse.jdt.core.prefs | 385 ++++++++++++++++++ .../.settings/org.eclipse.jdt.ui.prefs | 8 + clusterAdminLibrary/pom.xml | 29 +- 10 files changed, 872 insertions(+), 2 deletions(-) create mode 100644 clusterAdminApplication/.checkstyle create mode 100644 clusterAdminApplication/.settings/org.eclipse.jdt.ui.prefs create mode 100644 clusterAdminLibrary/.checkstyle create mode 100644 clusterAdminLibrary/.settings/org.eclipse.jdt.ui.prefs diff --git a/clusterAdminApplication/.checkstyle b/clusterAdminApplication/.checkstyle new file mode 100644 index 0000000..5783bc0 --- /dev/null +++ b/clusterAdminApplication/.checkstyle @@ -0,0 +1,7 @@ + + + + + + + diff --git a/clusterAdminApplication/.project b/clusterAdminApplication/.project index a09e464..40a5317 100644 --- a/clusterAdminApplication/.project +++ b/clusterAdminApplication/.project @@ -10,12 +10,20 @@ + + net.sf.eclipsecs.core.CheckstyleBuilder + + + org.eclipse.m2e.core.maven2Builder - + + + org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + net.sf.eclipsecs.core.CheckstyleNature diff --git a/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs b/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs index ec55441..1f04118 100644 --- a/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs +++ b/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs @@ -13,3 +13,388 @@ org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=11 +org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns=false +org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.align_variable_declarations_on_columns=false +org.eclipse.jdt.core.formatter.align_with_spaces=false +org.eclipse.jdt.core.formatter.alignment_for_additive_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_enum_constant=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter=0 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type=49 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assertion_message=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=52 +org.eclipse.jdt.core.formatter.alignment_for_compact_loops=52 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression_chain=0 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_logical_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_module_statements=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_record_components=16 +org.eclipse.jdt.core.formatter.alignment_for_relational_operator=0 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_shift_operator=0 +org.eclipse.jdt.core.formatter.alignment_for_string_concatenation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_record_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_type_annotations=0 +org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0 +org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=0 +org.eclipse.jdt.core.formatter.blank_lines_after_last_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_after_package=0 +org.eclipse.jdt.core.formatter.blank_lines_before_abstract_method=0 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=0 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=0 +org.eclipse.jdt.core.formatter.blank_lines_before_method=0 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=0 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_statement_group_in_switch=0 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=0 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_record_constructor=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_record_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.align_tags_descriptions_grouped=false +org.eclipse.jdt.core.formatter.comment.align_tags_names_descriptions=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.count_line_length_from_starting_position=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.indent_tag_description=false +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_between_different_tags=do not insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_record_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_additive_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_default=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_bitwise_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_record_components=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_switch_case_expressions=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_multiplicative_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_not_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_record_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_relational_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_string_concatenation=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_additive_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_case=insert +org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_default=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_record_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_record_components=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_switch_case_expressions=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_multiplicative_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_record_constructor=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_record_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_record_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_relational_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_string_concatenation=insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_annotation_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_anonymous_type_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_code_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_enum_constant_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_enum_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_if_then_body_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_lambda_body_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_loop_body_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_method_body_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_record_constructor_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_record_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_simple_do_while_body_on_same_line=false +org.eclipse.jdt.core.formatter.keep_simple_for_body_on_same_line=false +org.eclipse.jdt.core.formatter.keep_simple_getter_setter_on_one_line=false +org.eclipse.jdt.core.formatter.keep_simple_while_body_on_same_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_type_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_after_code_block=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_code_block=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_end_of_code_block=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_end_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_before_code_block=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_record_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.text_block_indentation=0 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_additive_operator=true +org.eclipse.jdt.core.formatter.wrap_before_assertion_message_operator=true +org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false +org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator=true +org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_logical_operator=true +org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_before_relational_operator=true +org.eclipse.jdt.core.formatter.wrap_before_shift_operator=true +org.eclipse.jdt.core.formatter.wrap_before_string_concatenation=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/clusterAdminApplication/.settings/org.eclipse.jdt.ui.prefs b/clusterAdminApplication/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..4a94aa1 --- /dev/null +++ b/clusterAdminApplication/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +formatter_profile=org.eclipse.jdt.ui.default_profile +formatter_settings_version=21 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder= +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.staticondemandthreshold=99 diff --git a/clusterAdminApplication/pom.xml b/clusterAdminApplication/pom.xml index d71ace0..5a52537 100644 --- a/clusterAdminApplication/pom.xml +++ b/clusterAdminApplication/pom.xml @@ -285,6 +285,33 @@ + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.2 + + + + com.puppycrawl.tools + checkstyle + 8.44 + + + + google_checks.xml + + + + + validate + validate + + check + + + + diff --git a/clusterAdminLibrary/.checkstyle b/clusterAdminLibrary/.checkstyle new file mode 100644 index 0000000..ab9f1e5 --- /dev/null +++ b/clusterAdminLibrary/.checkstyle @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/clusterAdminLibrary/.project b/clusterAdminLibrary/.project index d3dc532..dcbae6c 100644 --- a/clusterAdminLibrary/.project +++ b/clusterAdminLibrary/.project @@ -10,6 +10,11 @@ + + net.sf.eclipsecs.core.CheckstyleBuilder + + + org.eclipse.m2e.core.maven2Builder @@ -19,5 +24,6 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + net.sf.eclipsecs.core.CheckstyleNature diff --git a/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs b/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs index 2bd4e77..4304b63 100644 --- a/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs +++ b/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs @@ -14,3 +14,388 @@ org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=11 +org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns=false +org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines=2147483647 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.align_variable_declarations_on_columns=false +org.eclipse.jdt.core.formatter.align_with_spaces=false +org.eclipse.jdt.core.formatter.alignment_for_additive_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_enum_constant=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_field=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_local_variable=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_method=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_package=49 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_parameter=0 +org.eclipse.jdt.core.formatter.alignment_for_annotations_on_type=49 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assertion_message=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=52 +org.eclipse.jdt.core.formatter.alignment_for_compact_loops=52 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression_chain=0 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header=0 +org.eclipse.jdt.core.formatter.alignment_for_logical_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_module_statements=16 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator=16 +org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references=0 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_record_components=16 +org.eclipse.jdt.core.formatter.alignment_for_relational_operator=0 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_shift_operator=0 +org.eclipse.jdt.core.formatter.alignment_for_string_concatenation=16 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_record_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=64 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_type_annotations=0 +org.eclipse.jdt.core.formatter.alignment_for_type_arguments=0 +org.eclipse.jdt.core.formatter.alignment_for_type_parameters=0 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=0 +org.eclipse.jdt.core.formatter.blank_lines_after_last_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_after_package=0 +org.eclipse.jdt.core.formatter.blank_lines_before_abstract_method=0 +org.eclipse.jdt.core.formatter.blank_lines_before_field=0 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=0 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=0 +org.eclipse.jdt.core.formatter.blank_lines_before_method=0 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=0 +org.eclipse.jdt.core.formatter.blank_lines_before_package=0 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_statement_group_in_switch=0 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=0 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_lambda_body=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_record_constructor=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_record_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.align_tags_descriptions_grouped=false +org.eclipse.jdt.core.formatter.comment.align_tags_names_descriptions=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.count_line_length_from_starting_position=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.indent_tag_description=false +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_between_different_tags=do not insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=80 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_record_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_additive_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_arrow_in_switch_default=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_bitwise_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_record_components=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_switch_case_expressions=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_after_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_multiplicative_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_not_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_record_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_relational_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_string_concatenation=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_additive_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_case=insert +org.eclipse.jdt.core.formatter.insert_space_before_arrow_in_switch_default=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_record_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_record_components=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_switch_case_expressions=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow=insert +org.eclipse.jdt.core.formatter.insert_space_before_logical_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_multiplicative_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_record_constructor=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_record_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_record_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_relational_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_shift_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_string_concatenation=insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_annotation_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_anonymous_type_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_code_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_enum_constant_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_enum_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_if_then_body_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_lambda_body_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_loop_body_block_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_method_body_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_record_constructor_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_record_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.keep_simple_do_while_body_on_same_line=false +org.eclipse.jdt.core.formatter.keep_simple_for_body_on_same_line=false +org.eclipse.jdt.core.formatter.keep_simple_getter_setter_on_one_line=false +org.eclipse.jdt.core.formatter.keep_simple_while_body_on_same_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_type_declaration_on_one_line=one_line_never +org.eclipse.jdt.core.formatter.lineSplit=80 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_after_code_block=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_code_block=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_end_of_code_block=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_end_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_blank_lines_before_code_block=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_record_declaration=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement=common_lines +org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause=common_lines +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=false +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.text_block_indentation=0 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_additive_operator=true +org.eclipse.jdt.core.formatter.wrap_before_assertion_message_operator=true +org.eclipse.jdt.core.formatter.wrap_before_assignment_operator=false +org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator=true +org.eclipse.jdt.core.formatter.wrap_before_conditional_operator=true +org.eclipse.jdt.core.formatter.wrap_before_logical_operator=true +org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_before_relational_operator=true +org.eclipse.jdt.core.formatter.wrap_before_shift_operator=true +org.eclipse.jdt.core.formatter.wrap_before_string_concatenation=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/clusterAdminLibrary/.settings/org.eclipse.jdt.ui.prefs b/clusterAdminLibrary/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000..2ae3e15 --- /dev/null +++ b/clusterAdminLibrary/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,8 @@ +eclipse.preferences.version=1 +formatter_profile=org.eclipse.jdt.ui.default_profile +formatter_settings_version=21 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=; +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.staticondemandthreshold=99 +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/clusterAdminLibrary/pom.xml b/clusterAdminLibrary/pom.xml index adf114b..57c68ab 100644 --- a/clusterAdminLibrary/pom.xml +++ b/clusterAdminLibrary/pom.xml @@ -367,7 +367,34 @@ - + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.2 + + + + com.puppycrawl.tools + checkstyle + 8.44 + + + + google_checks.xml + + + + + validate + validate + + check + + + + + From 5995b8f7f8fe41fbc766de7a87ef7cc5ac4cb32c Mon Sep 17 00:00:00 2001 From: YanSergey Date: Wed, 20 Oct 2021 13:54:08 +0300 Subject: [PATCH 2/6] =?UTF-8?q?=D0=A4=D0=BE=D1=80=D0=BC=D0=B0=D1=82=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=BE=D0=B4?= =?UTF-8?q?=20=D0=BA=D0=BE=D0=B4=D1=81=D1=82=D0=B0=D0=B9=D0=BB,=20=D1=80?= =?UTF-8?q?=D0=B5=D1=84=D0=B0=D0=BA=D1=82=D0=BE=D1=80=D0=B8=D0=BD=D0=B3=20?= =?UTF-8?q?=D0=B8=20JavaDoc?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../clusterAdminApplication/ClusterAdmin.java | 37 +- .../ClusterViewer.java | 328 +- .../ClusterAdminLibraryMain.java | 17 +- .../clusterAdminLibrary/ClusterProvider.java | 521 +- .../clusterAdminLibrary/ColumnProperties.java | 201 +- .../yanygin/clusterAdminLibrary/Config.java | 957 ++- .../ConnectionInfoExtended.java | 205 +- .../clusterAdminLibrary/IInfoExtended.java | 181 +- .../clusterAdminLibrary/LockInfoExtended.java | 286 +- .../yanygin/clusterAdminLibrary/Messages.java | 48 +- .../yanygin/clusterAdminLibrary/Server.java | 5317 +++++++++-------- .../SessionInfoExtended.java | 558 +- .../WorkingProcessInfoExtended.java | 294 +- .../WorkingServerInfoExtended.java | 233 +- .../clusterAdminLibraryUI/AboutDialog.java | 175 +- .../AuthenticateDialog.java | 224 +- .../CreateEditClusterDialog.java | 852 +-- .../CreateEditServerDialog.java | 763 +-- .../CreateEditWorkingServerDialog.java | 1178 ++-- .../CreateInfobaseDialog.java | 662 +- .../DropInfobaseDialog.java | 209 +- .../EditInfobaseDialog.java | 844 +-- .../clusterAdminLibraryUI/Messages.java | 35 +- .../SessionInfoDialog.java | 483 +- .../clusterAdminLibraryUI/SettingsDialog.java | 448 +- .../clusterAdminLibraryUI/ViewerArea.java | 4869 ++++++++------- .../src/main/resources/logback.xml | 4 +- 27 files changed, 10858 insertions(+), 9071 deletions(-) diff --git a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java index a24333f..051636e 100644 --- a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java +++ b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java @@ -4,22 +4,27 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** ClusterAdmin application. */ public class ClusterAdmin { - public static void main (String[] args) { - Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ - - try { - ClusterViewer window = new ClusterViewer(); - window.setBlockOnOpen(true); - window.open(); - Display.getCurrent().dispose(); - - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error:", excp); //$NON-NLS-1$ - } - - } - + private static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ + + /** + * ClusterAdmin application main. + * + * @param args - args + */ + public static void main(String[] args) { + + try { + ClusterViewer window = new ClusterViewer(); + window.setBlockOnOpen(true); + window.open(); + Display.getCurrent().dispose(); + + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error("Error:", excp); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java index e4be881..75819a4 100644 --- a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java +++ b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java @@ -5,245 +5,111 @@ import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; -import org.eclipse.swt.events.MouseAdapter; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; -import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.ToolBar; -import org.eclipse.swt.widgets.ToolItem; -import org.eclipse.swt.widgets.Tree; -import org.eclipse.swt.widgets.TreeColumn; -import org.eclipse.wb.swt.SWTResourceManager; - import ru.yanygin.clusterAdminLibrary.ClusterProvider; import ru.yanygin.clusterAdminLibraryUI.ViewerArea; +/** Application window class. */ public class ClusterViewer extends ApplicationWindow { - - Tree serversTree; - Composite mainForm; - - ClusterProvider clusterProvider = new ClusterProvider(); - private Table tableOfSessions; - - /** - * Create the application window. - */ - public ClusterViewer() { - super(null); - createActions(); - addToolBar(SWT.FLAT | SWT.WRAP); - addMenuBar(); - addStatusLine(); -// addItems(); - - } - - @Override - public boolean close() { - clusterProvider.close(); - return super.close(); - } - /** - * Create contents of the application window. - * @param parent - */ - @Override - protected Control createContents(Composite parent) { - this.mainForm = parent; - - ToolBar toolBar = this.getToolBarManager().createControl(parent); - - Menu menu = this.getMenuBarManager().getMenu(); - - ViewerArea container = new ViewerArea(parent, SWT.NONE, menu, toolBar, clusterProvider); - - //Composite container = alternativeInit(parent); - - return container; - } - - private Composite alternativeInit(Composite parent) { - Composite container = new Composite(parent, SWT.NONE); - - // Toolbar -// ToolBar toolBar = new ToolBar(container, SWT.FLAT | SWT.RIGHT); -// toolBar.setBounds(0, 0, 500, 23); - ToolBar toolBar = getToolBarManager().createControl(container); - final Cursor handCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_HAND); - toolBar.setCursor(handCursor); - // Cursor needs to be explicitly disposed - toolBar.addDisposeListener(new DisposeListener() { - public void widgetDisposed(DisposeEvent e) { - if (handCursor.isDisposed() == false) { - handCursor.dispose(); - } - } - }); - - ToolItem toolBarItemFindNewServers = new ToolItem(toolBar, SWT.NONE); - toolBarItemFindNewServers.setText("Find new Servers"); - toolBarItemFindNewServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { -// List newServers = clusterProvider.findNewServers(); -// if (!newServers.isEmpty()) { -// fillServersList(); -// } - } - }); - - ToolItem toolBarItemConnectToServers = new ToolItem(toolBar, SWT.NONE); - toolBarItemConnectToServers.setText("Connect to servers"); - toolBarItemConnectToServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - } - }); - container.setLayout(new FillLayout(SWT.HORIZONTAL)); - - SashForm sashForm = new SashForm(container, SWT.NONE); - - serversTree = new Tree(sashForm, SWT.BORDER | SWT.FULL_SELECTION); - serversTree.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - } - }); - serversTree.addMouseListener(new MouseAdapter() { - @Override - public void mouseDown(MouseEvent e) { - int button = e.button; - } - }); - serversTree.setHeaderVisible(true); - serversTree.setSortDirection(SWT.DOWN); - - TreeColumn columnServer = new TreeColumn(serversTree, SWT.LEFT); - columnServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - } - }); - columnServer.setText("Cluster/Infobase"); - columnServer.setWidth(200); - - TreeColumn columnPing = new TreeColumn(serversTree, SWT.CENTER); - columnPing.setText("RAS port"); - columnPing.setWidth(60); - - Menu menu = new Menu(serversTree); - serversTree.setMenu(menu); - - MenuItem menuItemEditServer = new MenuItem(menu, SWT.NONE); - menuItemEditServer.setText("Edit Server"); - menuItemEditServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - } - }); - - TabFolder tabFolder = new TabFolder(sashForm, SWT.NONE); - - TabItem tabItem = new TabItem(tabFolder, SWT.NONE); - tabItem.setText("New Item"); - - tableOfSessions = new Table(tabFolder, SWT.BORDER | SWT.CHECK | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.VIRTUAL | SWT.MULTI); - tableOfSessions.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.NORMAL)); - tabItem.setControl(tableOfSessions); - tableOfSessions.setHeaderVisible(true); - tableOfSessions.setLinesVisible(true); - - Menu menu2 = new Menu(tableOfSessions); - tableOfSessions.setMenu(menu2); - - MenuItem menuItemEditServer_1 = new MenuItem(menu2, SWT.NONE); - menuItemEditServer_1.setText("Edit Server"); - - TableColumn tblclmnAppID = new TableColumn(tableOfSessions, SWT.NONE); - tblclmnAppID.setWidth(100); - tblclmnAppID.setText("Application"); - - sashForm.setWeights(new int[] {1, 2}); - - return container; - } - - /** - * Create the actions. - */ - private void createActions() { - // Create the actions - } - - /** - * Create the menu manager. - * @return the menu manager - */ - @Override - protected MenuManager createMenuManager() { - MenuManager menuManager = new MenuManager("menu"); - return menuManager; - } - - /** - * Create the toolbar manager. - * @return the toolbar manager - */ - @Override - protected ToolBarManager createToolBarManager(int style) { - ToolBarManager toolBarManager = new ToolBarManager(style); - return toolBarManager; - } - - /** - * Create the status line manager. - * @return the status line manager - */ - @Override - protected StatusLineManager createStatusLineManager() { - StatusLineManager statusLineManager = new StatusLineManager(); - return statusLineManager; - } - - /** - * Configure the shell. - * @param newShell - */ - @Override - protected void configureShell(Shell newShell) { - super.configureShell(newShell); - newShell.setText("OneS Cluster Administrator"); - // icon - } - - /** - * Return the initial size of the window. - */ - @Override - protected Point getInitialSize() { - return new Point(1600, 800); - } - -// @Override -// public int open() { -// ((ViewerArea) this.getContents()).open(); -// return super.open(); -// } + + Composite mainForm; + + ClusterProvider clusterProvider = new ClusterProvider(); + + /** Create the application window. */ + public ClusterViewer() { + super(null); + createActions(); + addToolBar(SWT.FLAT | SWT.WRAP); + addMenuBar(); + addStatusLine(); + + } + + @Override + public boolean close() { + clusterProvider.close(); + return super.close(); + } + + /** + * Create contents of the application window. + * + * @param parent - parent composite + */ + @Override + protected Control createContents(Composite parent) { + this.mainForm = parent; + + ToolBar toolBar = this.getToolBarManager().createControl(parent); + + Menu menu = this.getMenuBarManager().getMenu(); + + ViewerArea container = new ViewerArea(parent, SWT.NONE, menu, toolBar, clusterProvider); + + return container; + } + + + /** Create the actions. */ + private void createActions() { + // Create the actions + } + + /** + * Create the menu manager. + * + * @return the menu manager + */ + @Override + protected MenuManager createMenuManager() { + MenuManager menuManager = new MenuManager("menu"); + return menuManager; + } + + /** + * Create the toolbar manager. + * + * @return the toolbar manager + */ + @Override + protected ToolBarManager createToolBarManager(int style) { + ToolBarManager toolBarManager = new ToolBarManager(style); + return toolBarManager; + } + + /** + * Create the status line manager. + * + * @return the status line manager + */ + @Override + protected StatusLineManager createStatusLineManager() { + StatusLineManager statusLineManager = new StatusLineManager(); + return statusLineManager; + } + + /** + * Configure the shell. + * + * @param newShell - shell + */ + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText("OneS Cluster Administrator"); + // icon + } + + /** Return the initial size of the window. */ + @Override + protected Point getInitialSize() { + return new Point(1600, 800); + } + } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterAdminLibraryMain.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterAdminLibraryMain.java index f00f52c..acc7033 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterAdminLibraryMain.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterAdminLibraryMain.java @@ -1,9 +1,18 @@ package ru.yanygin.clusterAdminLibrary; +/** + * Entry point main class. + * + * @author Yanygin Sergey + */ public class ClusterAdminLibraryMain { - public static void main(String[] args) { -// ClusterProvider clusterProvider = new ClusterProvider(); - } - + /** + * Entry point. + * + * @param args - command args + */ + public static void main(String[] args) { + new ClusterProvider(); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java index ca8c6e0..e05bef8 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java @@ -1,5 +1,10 @@ package ru.yanygin.clusterAdminLibrary; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonIOException; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -14,287 +19,253 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.UUID; - import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.widgets.Display; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com._1c.v8.ibis.admin.IClusterInfo; -import com._1c.v8.ibis.admin.IInfoBaseInfo; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonIOException; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; - public class ClusterProvider { - - File configFile; - static Config commonConfig; - public static final String DEFAULT_CONFIG_PATH = "config.json"; //$NON-NLS-1$ - - private static Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ - - public ClusterProvider() { - - - } - - public static Config getCommonConfig() { - return commonConfig; - } - - public void readConfig(String configPath) { - LOGGER.info("Start read config from file <{}>", configPath); //$NON-NLS-1$ - - if (configPath.isBlank()) { - LOGGER.debug("Config path is empty, create new config in root folder"); //$NON-NLS-1$ - commonConfig = new Config(); - return; - } - - configFile = new File(configPath); - if (!configFile.exists()) { - LOGGER.debug("Config file not exists, create new"); //$NON-NLS-1$ - commonConfig = new Config(); - return; - } - - JsonReader jsonReader = null; - - try { - jsonReader = new JsonReader( - new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); - } catch (FileNotFoundException excp) { - LOGGER.debug("Config file read error:", excp); //$NON-NLS-1$ - LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ - configFile = new File(DEFAULT_CONFIG_PATH); - commonConfig = new Config(); - return; - } - Gson gson = new GsonBuilder() - .excludeFieldsWithoutExposeAnnotation() - .create(); - - try { - commonConfig = gson.fromJson(jsonReader, Config.class); - } catch (Exception excp) { - LOGGER.debug("error convert config from json"); //$NON-NLS-1$ - LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ - configFile = new File(DEFAULT_CONFIG_PATH); - commonConfig = new Config(); - return; - } - - if (commonConfig == null) { - LOGGER.debug("config is null, after read json"); //$NON-NLS-1$ - LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ - configFile = new File(DEFAULT_CONFIG_PATH); - commonConfig = new Config(); - } else { - - commonConfig.init(); - - if (commonConfig.locale != null) { - LOGGER.debug("Set locale is <{}>", commonConfig.locale); //$NON-NLS-1$ - Locale locale = Locale.forLanguageTag(commonConfig.locale); - java.util.Locale.setDefault(locale); - Messages.reloadBundle(locale); - } - } - LOGGER.info("Config file read successfully"); //$NON-NLS-1$ - } - - public void saveConfig() {//String configPath) { - - LOGGER.info("Start save config to file <{}>", configFile.getAbsolutePath()); //$NON-NLS-1$ - -// configFile = new File(configPath); - - JsonWriter jsonWriter; - try { - jsonWriter = new JsonWriter( - new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8)); - } catch (FileNotFoundException excp) { - LOGGER.debug("Config file save error: {}", excp); //$NON-NLS-1$ - return; - } - Gson gson = new GsonBuilder() - .excludeFieldsWithoutExposeAnnotation() - .setPrettyPrinting() - .create(); - try { - gson.toJson(getCommonConfig(), getCommonConfig().getClass(), jsonWriter); - } catch (JsonIOException excp) { - LOGGER.debug("Config file save error: {}", excp); //$NON-NLS-1$ - } - - try { - jsonWriter.close(); - } catch (IOException excp) { - LOGGER.debug("Config file save error: {}", excp); //$NON-NLS-1$ - } - LOGGER.info("Config file write successfully"); //$NON-NLS-1$ - - } - - public Server createNewServer() { - Server newServer = null; - - if (commonConfig.readClipboard) { - Clipboard clipboard = new Clipboard(Display.getDefault()); - String clip = (String)clipboard.getContents(TextTransfer.getInstance()); - clipboard.dispose(); - - if (clip != null && clip.startsWith("Srvr=")) { //$NON-NLS-1$ - String[] srvrPart = clip.split(";"); //$NON-NLS-1$ - String srvr = srvrPart[0].substring(6, srvrPart[0].length() - 1); - newServer = new Server(srvr); + + File configFile; + static Config commonConfig; + private static final String DEFAULT_CONFIG_PATH = "config.json"; //$NON-NLS-1$ + + private static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ + + public ClusterProvider() {} + + public static Config getCommonConfig() { + return commonConfig; + } + + public void readConfig() { + readConfig(DEFAULT_CONFIG_PATH); + } + + public void readConfig(String configPath) { + LOGGER.info("Start read config from file <{}>", configPath); //$NON-NLS-1$ + + if (configPath.isBlank()) { + LOGGER.debug("Config path is empty, create new config in root folder"); //$NON-NLS-1$ + commonConfig = new Config(); + return; + } + + configFile = new File(configPath); + if (!configFile.exists()) { + LOGGER.debug("Config file not exists, create new"); //$NON-NLS-1$ + commonConfig = new Config(); + return; + } + + JsonReader jsonReader = null; + + try { + jsonReader = + new JsonReader( + new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); + } catch (FileNotFoundException excp) { + LOGGER.debug("Config file read error:", excp); //$NON-NLS-1$ + LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ + configFile = new File(DEFAULT_CONFIG_PATH); + commonConfig = new Config(); + return; + } + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + + try { + commonConfig = gson.fromJson(jsonReader, Config.class); + } catch (Exception excp) { + LOGGER.debug("error convert config from json"); //$NON-NLS-1$ + LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ + configFile = new File(DEFAULT_CONFIG_PATH); + commonConfig = new Config(); + return; + } + + if (commonConfig == null) { + LOGGER.debug("config is null, after read json"); //$NON-NLS-1$ + LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ + configFile = new File(DEFAULT_CONFIG_PATH); + commonConfig = new Config(); + } else { + + commonConfig.init(); + + if (commonConfig.getLocale() != null) { + LOGGER.debug("Set locale is <{}>", commonConfig.getLocale()); //$NON-NLS-1$ + Locale locale = Locale.forLanguageTag(commonConfig.getLocale()); + java.util.Locale.setDefault(locale); + Messages.reloadBundle(locale); + } + } + LOGGER.info("Config file read successfully"); //$NON-NLS-1$ + } + + public void saveConfig() { + + LOGGER.info("Start save config to file <{}>", configFile.getAbsolutePath()); //$NON-NLS-1$ + + // configFile = new File(configPath); + + JsonWriter jsonWriter; + try { + jsonWriter = + new JsonWriter( + new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8)); + } catch (FileNotFoundException excp) { + LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + return; + } + Gson gson = + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); + try { + gson.toJson(getCommonConfig(), getCommonConfig().getClass(), jsonWriter); + } catch (JsonIOException excp) { + LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + } + + try { + jsonWriter.close(); + } catch (IOException excp) { + LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + } + LOGGER.info("Config file write successfully"); //$NON-NLS-1$ + } + + public Server createNewServer() { + Server newServer = null; + + if (commonConfig.isReadClipboard()) { + Clipboard clipboard = new Clipboard(Display.getDefault()); + String clip = (String) clipboard.getContents(TextTransfer.getInstance()); + clipboard.dispose(); + + if (clip != null && clip.startsWith("Srvr=")) { //$NON-NLS-1$ + String[] srvrPart = clip.split(";"); //$NON-NLS-1$ + String srvr = srvrPart[0].substring(6, srvrPart[0].length() - 1); + newServer = new Server(srvr); + } + } else { + newServer = new Server("Server:1541"); //$NON-NLS-1$ + } + + return newServer; + } + + public void addNewServer(Server server) { + commonConfig.getServers().put(server.getServerKey(), server); + saveConfig(); + } + + public void removeServer(Server server) { + getCommonConfig().getServers().remove(server.getServerKey(), server); + saveConfig(); + } + + public Map getServers() { + return getCommonConfig().getServers(); + } + + public List findNewServers() { + + List addedServers = new ArrayList<>(); + + return addedServers; + } + + public void connectToServers() { + + getCommonConfig().connectAllServers(); + } + + public List getConnectedServers() { + + List connectedServers = new ArrayList<>(); + + getCommonConfig() + .getServers() + .forEach( + (server, config) -> { + if (config.isConnected()) { + connectedServers.add(config.getServerKey()); + } + }); + + return connectedServers; + } + + public void checkConnectToServers() { + + getCommonConfig().checkConnectionAllServers(); + } + + public void close() { + + saveConfig(); + + getServers() + .forEach( + (server, config) -> { + if (config.isConnected()) { + config.disconnectFromAgent(); + } + }); + } + + public static Map getInstalledV8Versions() { + LOGGER.debug("Get installed v8 platform versions"); //$NON-NLS-1$ + + Map versions = new HashMap<>(); + + if (!commonConfig.isWindows()) { + return versions; + } + + File v8x64CommonPath = new File("C:\\Program Files\\1cv8"); //$NON-NLS-1$ + File v8x86CommonPath = new File("C:\\Program Files (x86)\\1cv8"); //$NON-NLS-1$ + + FilenameFilter filter = + new FilenameFilter() { + @Override + public boolean accept(File f, String name) { + return name.matches("8.3.\\d\\d.\\d{4}"); //$NON-NLS-1$ + } + }; + + try { + if (v8x64CommonPath.exists()) { + File[] v8x64dirs = v8x64CommonPath.listFiles(filter); + for (File dir : v8x64dirs) { + if (dir.isDirectory()) { + File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ + if (ras.exists() && ras.isFile()) { + versions.put(dir.getName().concat(" (x86_64)"), ras.getAbsolutePath()); //$NON-NLS-1$ } - } else { - newServer = new Server("Server:1541"); //$NON-NLS-1$ - } - - return newServer; - } - - public void addNewServer(Server server) { - commonConfig.servers.put(server.getServerKey(), server); - saveConfig(); - } - - public void removeServer(Server server) { - getCommonConfig().servers.remove(server.getServerKey(), server); - saveConfig(); - } - - public Map getServers() { - return getCommonConfig().servers; - } - - public List findNewServers() { - - List addedServers = new ArrayList<>(); - - return addedServers; - } - - public void connectToServers() { - - getCommonConfig().connectAllServers(); - - } - - public List getConnectedServers() { - - List connectedServers = new ArrayList<>(); - - getCommonConfig().servers.forEach((server, config) -> { - if (config.isConnected()) - connectedServers.add(config.getServerKey()); - }); - - return connectedServers; - } - - public void checkConnectToServers() { - - getCommonConfig().checkConnectionAllServers(); - - } - - public List getInfobases(Server server){ // not used? - - List infobases = new ArrayList<>(); - - if (server.isConnected()) { - - List clusterInfoList = server.getClusters(); - - UUID uuid = clusterInfoList.get(0).getClusterId(); - - infobases = server.getInfoBases(uuid); - - } - - return infobases; - } - - public void close() { - - saveConfig(); - - getServers().forEach((server, config) -> { - if (config.isConnected()) - config.disconnectFromAgent(); - }); - - } - - public static Map getInstalledV8Versions() { - LOGGER.debug("Get installed v8 platform versions"); //$NON-NLS-1$ - - Map versions = new HashMap<>(); - - if (!commonConfig.isWindows()) - return versions; - - File v8x64CommonPath = new File("C:\\Program Files\\1cv8"); //$NON-NLS-1$ - File v8x86CommonPath = new File("C:\\Program Files (x86)\\1cv8"); //$NON-NLS-1$ - - FilenameFilter filter = new FilenameFilter() { - public boolean accept(File f, String name) { - return name.matches("8.3.\\d\\d.\\d{4}"); //$NON-NLS-1$ - } - }; - - try { - if (v8x64CommonPath.exists()) { - File[] v8x64dirs = v8x64CommonPath.listFiles(filter); - for (File dir : v8x64dirs) { - if (dir.isDirectory()) { - File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ - if (ras.exists() && ras.isFile()) - versions.put(dir.getName().concat(" (x86_64)"), ras.getAbsolutePath()); //$NON-NLS-1$ - } - } - } - } catch (Exception excp) { - LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ - } - - try { - if (v8x86CommonPath.exists()) { - File[] v8x86dirs = v8x86CommonPath.listFiles(filter); - for (File dir : v8x86dirs) { - if (dir.isDirectory()) { - File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ - if (ras.exists() && ras.isFile()) - versions.put(dir.getName(), ras.getAbsolutePath()); // $NON-NLS-1$ - } - } - } - } catch (Exception excp) { - LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ - } - - return versions; - - } - - - - - - - - - - - - - + } + } + } + } catch (Exception excp) { + LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ + } + + try { + if (v8x86CommonPath.exists()) { + File[] v8x86dirs = v8x86CommonPath.listFiles(filter); + for (File dir : v8x86dirs) { + if (dir.isDirectory()) { + File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ + if (ras.exists() && ras.isFile()) { + versions.put(dir.getName(), ras.getAbsolutePath()); //$NON-NLS-1$ + } + } + } + } + } catch (Exception excp) { + LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ + } + + return versions; + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java index 3103307..223c137 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java @@ -3,73 +3,140 @@ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; +/** Column properties. */ public class ColumnProperties { - - @SerializedName("Order") - @Expose - public int[] order = null; - - @SerializedName("Width") - @Expose - public int[] width = null; - - @SerializedName("Visible") - @Expose - public boolean[] visible = null; - - public ColumnProperties(int size) { - - // Порядок столбцов - this.order = new int[size]; - for (int i = 0; i < this.order.length; i++) - this.order[i] = i; - - // Ширина столбцов - this.width = new int[size]; - - // Видимость столбцов - this.visible = new boolean[size]; - for (int i = 0; i < this.visible.length; i++) - this.visible[i] = true; - } - - public void updateColumnProperties(int arraySize) { - - // если после десериализации количество не равно текущему - // (например, поменялся состав колонок), - // нужно переложить в новый массив без потерь - - // Порядок столбцов - if (order.length != arraySize) { - int[] columnOrderTemp = order; - order = new int[arraySize]; - System.arraycopy(columnOrderTemp, 0, order, 0, - Math.min(arraySize, columnOrderTemp.length)); - - if (arraySize > columnOrderTemp.length) - for (int i = columnOrderTemp.length; i < arraySize; i++) - order[i] = i; - } - - // Ширина столбцов - if (width.length != arraySize) { - int[] columnWidthTemp = width; - width = new int[arraySize]; - System.arraycopy(columnWidthTemp, 0, width, 0, - Math.min(arraySize, columnWidthTemp.length)); - } - - // Видимость столбцов - if (visible.length != arraySize) { - boolean[] columnVisibleTemp = visible; - visible = new boolean[arraySize]; - System.arraycopy(columnVisibleTemp, 0, visible, 0, - Math.min(arraySize, columnVisibleTemp.length)); - if (arraySize > columnVisibleTemp.length) - for (int i = columnVisibleTemp.length; i < arraySize; i++) - visible[i] = true; - } - - } + @SerializedName("Order") + @Expose + private int[] order = null; + + @SerializedName("Width") + @Expose + private int[] width = null; + + @SerializedName("Visible") + @Expose + private boolean[] visible = null; + + /** + * Get column order. + * + * @return column order + */ + public int[] getOrder() { + return order; + } + + /** + * Set column order. + * + * @param order - new column order + */ + public void setOrder(int[] order) { + this.order = order; + } + + /** + * Get column width. + * + * @return column width + */ + public int[] getWidth() { + return width; + } + + /** + * Set column width. + * + * @param width - new column width + */ + public void setWidth(int index, int width) { + this.width[index] = width; + } + + /** + * Get column visible. + * + * @return column visible + */ + public boolean[] getVisible() { + return visible; + } + + /** + * Set column visible. + * + * @param visible - new column visible + */ + public void setVisible(boolean[] visible) { + this.visible = visible; + } + + /** + * Column properties. + * + * @param size - column count + */ + public ColumnProperties(int size) { + + // Порядок столбцов + this.order = new int[size]; + for (int i = 0; i < this.order.length; i++) { + this.order[i] = i; + } + + // Ширина столбцов + this.width = new int[size]; + + // Видимость столбцов + this.visible = new boolean[size]; + for (int i = 0; i < this.visible.length; i++) { + this.visible[i] = true; + } + } + + /** + * Update column count by the current count. + * + * @param arraySize - current colimn count + */ + public void updateColumnProperties(int arraySize) { + + // если после десериализации количество не равно текущему + // (например, поменялся состав колонок), + // нужно переложить в новый массив без потерь + + // Порядок столбцов + if (order.length != arraySize) { + int[] columnOrderTemp = order; + order = new int[arraySize]; + System.arraycopy(columnOrderTemp, 0, order, 0, Math.min(arraySize, columnOrderTemp.length)); + + if (arraySize > columnOrderTemp.length) { + for (int i = columnOrderTemp.length; i < arraySize; i++) { + order[i] = i; + } + } + } + + // Ширина столбцов + if (width.length != arraySize) { + int[] columnWidthTemp = width; + width = new int[arraySize]; + System.arraycopy(columnWidthTemp, 0, width, 0, Math.min(arraySize, columnWidthTemp.length)); + } + + // Видимость столбцов + if (visible.length != arraySize) { + boolean[] columnVisibleTemp = visible; + visible = new boolean[arraySize]; + System.arraycopy( + columnVisibleTemp, 0, visible, 0, Math.min(arraySize, columnVisibleTemp.length)); + if (arraySize > columnVisibleTemp.length) { + for (int i = columnVisibleTemp.length; i < arraySize; i++) { + visible[i] = true; + } + } + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java index e70199f..aad7d88 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java @@ -1,264 +1,719 @@ package ru.yanygin.clusterAdminLibrary; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.annotations.Expose; -import com.google.gson.annotations.SerializedName; - +/** Main config for applacation. */ public class Config { - @SerializedName("Servers") - @Expose - public Map servers = new HashMap<>(); - - @SerializedName("ExpandServers") - @Expose - public boolean expandServersTree; - - @SerializedName("ExpandClustersTree") - @Expose - public boolean expandClustersTree; - - @SerializedName("ExpandInfobasesTree") - @Expose - public boolean expandInfobasesTree; - - @SerializedName("ShowWorkingServersTree") - @Expose - public boolean showWorkingServersTree; - - @SerializedName("ExpandWorkingServersTree") - @Expose - public boolean expandWorkingServersTree; - - @SerializedName("ShowWorkingProcessesTree") - @Expose - public boolean showWorkingProcessesTree; - - @SerializedName("ExpandWorkingProcessesTree") - @Expose - public boolean expandWorkingProcessesTree; - - @SerializedName("ShowServerDescription") - @Expose - public boolean showServerDescription; - - @SerializedName("ShowServerVersion") - @Expose - public boolean showServerVersion; - - @SerializedName("ShowInfobaseDescription") - @Expose - public boolean showInfobaseDescription; - - @SerializedName("ShowLocalRasConnectInfo") - @Expose - public boolean showLocalRasConnectInfo; - - @SerializedName("Locale") - @Expose - public String locale; - - @SerializedName("SessionColumnProperties") - @Expose - public ColumnProperties sessionColumnProperties; - - @SerializedName("ConnectionColumnProperties") - @Expose - public ColumnProperties connectionColumnProperties; - - @SerializedName("LockColumnProperties") - @Expose - public ColumnProperties lockColumnProperties; - - @SerializedName("WPColumnProperties") - @Expose - public ColumnProperties wpColumnProperties; - - @SerializedName("WSColumnProperties") - @Expose - public ColumnProperties wsColumnProperties; - - @SerializedName("ShadowSleepSessions") - @Expose - public boolean shadowSleepSessions; - - @SerializedName("HighlightNewItems") - @Expose - public boolean highlightNewItems; - - @SerializedName("HighlightNewItemsDuration") - @Expose - public int highlightNewItemsDuration; - @SerializedName("ReadClipboard") - @Expose - public boolean readClipboard; - - - private static Logger LOGGER = LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ - - private OSType currrentOS; - - private enum OSType { - WINDOWS, MACOS, LINUX, OTHER - } - - public Config() { - this.init(); - } - - public void init() { - getOperatingSystemType(); - - this.servers.forEach((key, server) -> { - server.init(); - }); - } - - private void getOperatingSystemType() { - if (currrentOS == null) { - String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); - LOGGER.debug("Current OS is <{}>", osName); //$NON-NLS-1$ - - if ((osName.indexOf("mac") >= 0) || (osName.indexOf("darwin") >= 0)) { - currrentOS = OSType.MACOS; - } else if (osName.indexOf("win") >= 0) { - currrentOS = OSType.WINDOWS; - } else if (osName.indexOf("nux") >= 0) { - currrentOS = OSType.LINUX; - } else { - currrentOS = OSType.OTHER; - } - } - } - - public List addNewServers(List servers) { - // Пакетное добавление серверов в список, предполагается для механизма импорта из списка информационных баз - - List addedServers = new ArrayList<>(); - - // Имя сервера, которое приходит сюда не равно Представлению сервера, выводимому в списке - // Имя сервера. оно же Key в map и json, строка вида Server:1541, с обязательным указанием порта менеджера, к которому подключаемся - // если порт менеджера не задан - ставим стандартный 1541 - // переделать - for (String serverName : servers) { - if (!this.servers.containsKey(serverName)) { - Server serverConfig = new Server(serverName); - this.servers.put(serverName, serverConfig); - - addedServers.add(serverName); - } - } - - return addedServers; - } - - public void connectAllServers() { - servers.forEach((serverKey, server) -> server.connectToServer(false, true)); - } - - public void checkConnectionAllServers() { - servers.forEach((serverKey, server) -> server.connectToServer(true, true)); - } - - public boolean isWindows() { - return currrentOS == OSType.WINDOWS; - } - - public boolean isLinux() { - return currrentOS == OSType.LINUX; - } - - public boolean isMacOS() { - return currrentOS == OSType.MACOS; - } - - public void setSessionsColumnOrder(int[] columnOrder) { - sessionColumnProperties.order = columnOrder; - } - - public void setConnectionsColumnOrder(int[] columnOrder) { - connectionColumnProperties.order = columnOrder; - } - - public void setLocksColumnOrder(int[] columnOrder) { - lockColumnProperties.order = columnOrder; - } - - public void setWorkingProcessesColumnOrder(int[] columnOrder) { - wpColumnProperties.order = columnOrder; - } - - public void setWorkingServersColumnOrder(int[] columnOrder) { - wsColumnProperties.order = columnOrder; - } - - public void initSessionsColumnCount(int columnCount) { - - if (sessionColumnProperties == null) - sessionColumnProperties = new ColumnProperties(columnCount); - else - sessionColumnProperties.updateColumnProperties(columnCount); - } - - public void initConnectionsColumnCount(int columnCount) { - - if (connectionColumnProperties == null) - connectionColumnProperties = new ColumnProperties(columnCount); - else - connectionColumnProperties.updateColumnProperties(columnCount); - } - - public void initLocksColumnCount(int columnCount) { - - if (lockColumnProperties == null) - lockColumnProperties = new ColumnProperties(columnCount); - else - lockColumnProperties.updateColumnProperties(columnCount); - } - - public void initWorkingProcessesColumnCount(int columnCount) { - - if (wpColumnProperties == null) - wpColumnProperties = new ColumnProperties(columnCount); - else - wpColumnProperties.updateColumnProperties(columnCount); - } - - public void initWorkingServersColumnCount(int columnCount) { - - if (wsColumnProperties == null) - wsColumnProperties = new ColumnProperties(columnCount); - else - wsColumnProperties.updateColumnProperties(columnCount); - } - - public void setSessionsColumnWidth(int index, int width) { - sessionColumnProperties.width[index] = width; - } - - public void setConnectionsColumnWidth(int index, int width) { - connectionColumnProperties.width[index] = width; - } - - public void setLocksColumnWidth(int index, int width) { - lockColumnProperties.width[index] = width; - } - - public void setWorkingProcessesColumnWidth(int index, int width) { - wpColumnProperties.width[index] = width; - } - - public void setWorkingServersColumnWidth(int index, int width) { - wsColumnProperties.width[index] = width; - } - -} + @SerializedName("Servers") + @Expose + private Map servers = new HashMap<>(); + + @SerializedName("ExpandServers") + @Expose + private boolean expandServersTree; + + @SerializedName("ExpandClustersTree") + @Expose + private boolean expandClustersTree; + + @SerializedName("ExpandInfobasesTree") + @Expose + private boolean expandInfobasesTree; + + @SerializedName("ShowWorkingServersTree") + @Expose + private boolean showWorkingServersTree; + + @SerializedName("ExpandWorkingServersTree") + @Expose + private boolean expandWorkingServersTree; + + @SerializedName("ShowWorkingProcessesTree") + @Expose + private boolean showWorkingProcessesTree; + + @SerializedName("ExpandWorkingProcessesTree") + @Expose + private boolean expandWorkingProcessesTree; + + @SerializedName("ShowServerDescription") + @Expose + private boolean showServerDescription; + + @SerializedName("ShowServerVersion") + @Expose + private boolean showServerVersion; + + @SerializedName("ShowInfobaseDescription") + @Expose + private boolean showInfobaseDescription; + + @SerializedName("ShowLocalRasConnectInfo") + @Expose + private boolean showLocalRasConnectInfo; + + @SerializedName("Locale") + @Expose + private String locale; + + @SerializedName("SessionColumnProperties") + @Expose + private ColumnProperties sessionColumnProperties; + + @SerializedName("ConnectionColumnProperties") + @Expose + private ColumnProperties connectionColumnProperties; + + @SerializedName("LockColumnProperties") + @Expose + private ColumnProperties lockColumnProperties; + + @SerializedName("WPColumnProperties") + @Expose + private ColumnProperties wpColumnProperties; + + @SerializedName("WSColumnProperties") + @Expose + private ColumnProperties wsColumnProperties; + + @SerializedName("ShadowSleepSessions") + @Expose + private boolean shadowSleepSessions; + + @SerializedName("HighlightNewItems") + @Expose + private boolean highlightNewItems; + + @SerializedName("HighlightNewItemsDuration") + @Expose + private int highlightNewItemsDuration; + + @SerializedName("ReadClipboard") + @Expose + private boolean readClipboard; + + private static final Logger LOGGER = + LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ + + private OsType currrentOs; + + private enum OsType { + WINDOWS, + MACOS, + LINUX, + OTHER + } + + /** + * Get servers. + * + * @return the servers + */ + public Map getServers() { + return servers; + } + + /** + * Expand servers in tree. + * + * @return the expandServersTree + */ + public boolean isExpandServersTree() { + return expandServersTree; + } + + /** + * Set expand servers in tree. + * + * @param expandServersTree the expandServersTree to set + */ + public void setExpandServersTree(boolean expandServersTree) { + this.expandServersTree = expandServersTree; + } + + /** + * Expand clusters in tree. + * + * @return the expandClustersTree + */ + public boolean isExpandClustersTree() { + return expandClustersTree; + } + + /** + * Set expand clusters in tree. + * + * @param expandClustersTree the expandClustersTree to set + */ + public void setExpandClustersTree(boolean expandClustersTree) { + this.expandClustersTree = expandClustersTree; + } + + /** + * Expand infobases in tree. + * + * @return the expandInfobasesTree + */ + public boolean isExpandInfobasesTree() { + return expandInfobasesTree; + } + + /** + * Set expand infobases in tree. + * + * @param expandInfobasesTree the expandInfobasesTree to set + */ + public void setExpandInfobasesTree(boolean expandInfobasesTree) { + this.expandInfobasesTree = expandInfobasesTree; + } + + /** + * Show working servers in tree. + * + * @return the showWorkingServersTree + */ + public boolean isShowWorkingServersTree() { + return showWorkingServersTree; + } + + /** + * Set show working servers in tree. + * + * @param showWorkingServersTree the showWorkingServersTree to set + */ + public void setShowWorkingServersTree(boolean showWorkingServersTree) { + this.showWorkingServersTree = showWorkingServersTree; + } + + /** + * Expand working servers in tree. + * + * @return the expandWorkingServersTree + */ + public boolean isExpandWorkingServersTree() { + return expandWorkingServersTree; + } + + /** + * Set expand working servers in tree. + * + * @param expandWorkingServersTree the expandWorkingServersTree to set + */ + public void setExpandWorkingServersTree(boolean expandWorkingServersTree) { + this.expandWorkingServersTree = expandWorkingServersTree; + } + + /** + * Show working processes in tree. + * + * @return the showWorkingProcessesTree + */ + public boolean isShowWorkingProcessesTree() { + return showWorkingProcessesTree; + } + + /** + * Set show working processes in tree. + * + * @param showWorkingProcessesTree the showWorkingProcessesTree to set + */ + public void setShowWorkingProcessesTree(boolean showWorkingProcessesTree) { + this.showWorkingProcessesTree = showWorkingProcessesTree; + } + + /** + * Expand working processes in tree. + * + * @return the expandWorkingProcessesTree + */ + public boolean isExpandWorkingProcessesTree() { + return expandWorkingProcessesTree; + } + + /** + * Set expand working processes in tree. + * + * @param expandWorkingProcessesTree the expandWorkingProcessesTree to set + */ + public void setExpandWorkingProcessesTree(boolean expandWorkingProcessesTree) { + this.expandWorkingProcessesTree = expandWorkingProcessesTree; + } + + /** + * Show server description in tree. + * + * @return the showServerDescription + */ + public boolean isShowServerDescription() { + return showServerDescription; + } + + /** + * Set show server description in tree. + * + * @param showServerDescription the showServerDescription to set + */ + public void setShowServerDescription(boolean showServerDescription) { + this.showServerDescription = showServerDescription; + } + + /** + * Show server version in tree. + * + * @return the showServerVersion + */ + public boolean isShowServerVersion() { + return showServerVersion; + } + + /** + * Set show server version in tree. + * + * @param showServerVersion the showServerVersion to set + */ + public void setShowServerVersion(boolean showServerVersion) { + this.showServerVersion = showServerVersion; + } + + /** + * Show infobase description in tree. + * + * @return the showInfobaseDescription + */ + public boolean isShowInfobaseDescription() { + return showInfobaseDescription; + } + + /** + * Set show infobase description in tree. + * + * @param showInfobaseDescription the showInfobaseDescription to set + */ + public void setShowInfobaseDescription(boolean showInfobaseDescription) { + this.showInfobaseDescription = showInfobaseDescription; + } + /** + * Show local-RAS connection info in tree. + * + * @return the showLocalRasConnectInfo + */ + public boolean isShowLocalRasConnectInfo() { + return showLocalRasConnectInfo; + } + /** + * Set show local-RAS connection info in tree. + * + * @param showLocalRasConnectInfo the showLocalRasConnectInfo to set + */ + public void setShowLocalRasConnectInfo(boolean showLocalRasConnectInfo) { + this.showLocalRasConnectInfo = showLocalRasConnectInfo; + } + + /** + * Get locale. + * + * @return the locale + */ + public String getLocale() { + return locale; + } + + /** + * Set locale. + * + * @param locale the locale to set + */ + public void setLocale(String locale) { + this.locale = locale; + } + + /** + * Get session column properties. + * + * @return the sessionColumnProperties + */ + public ColumnProperties getSessionColumnProperties() { + return sessionColumnProperties; + } + + /** + * Get connection column properties. + * + * @return the connectionColumnProperties + */ + public ColumnProperties getConnectionColumnProperties() { + return connectionColumnProperties; + } + + /** + * Get lock column properties. + * + * @return the lockColumnProperties + */ + public ColumnProperties getLockColumnProperties() { + return lockColumnProperties; + } + + /** + * Get working processes column properties. + * + * @return the wpColumnProperties + */ + public ColumnProperties getWpColumnProperties() { + return wpColumnProperties; + } + + /** + * Get working servers column properties. + * + * @return the wsColumnProperties + */ + public ColumnProperties getWsColumnProperties() { + return wsColumnProperties; + } + + /** + * Shadow sleep sessions. + * + * @return the shadowSleepSessions + */ + public boolean isShadowSleepSessions() { + return shadowSleepSessions; + } + + /** + * Set shadow sleep sessions. + * + * @param shadowSleepSessions the shadowSleepSessions to set + */ + public void setShadowSleepSessions(boolean shadowSleepSessions) { + this.shadowSleepSessions = shadowSleepSessions; + } + + /** + * Highlight new items in lists. + * + * @return the highlightNewItems + */ + public boolean isHighlightNewItems() { + return highlightNewItems; + } + + /** + * Set highlight new items in lists. + * + * @param highlightNewItems the highlightNewItems to set + */ + public void setHighlightNewItems(boolean highlightNewItems) { + this.highlightNewItems = highlightNewItems; + } + + /** + * Highlight new items duration. + * + * @return the highlightNewItemsDuration + */ + public int getHighlightNewItemsDuration() { + return highlightNewItemsDuration; + } + + /** + * Set highlight new items duration. + * + * @param highlightNewItemsDuration the highlightNewItemsDuration to set + */ + public void setHighlightNewItemsDuration(int highlightNewItemsDuration) { + this.highlightNewItemsDuration = highlightNewItemsDuration; + } + + /** + * Read clipboard. + * + * @return the readClipboard + */ + public boolean isReadClipboard() { + return readClipboard; + } + + /** + * Set read clipboard. + * + * @param readClipboard the readClipboard to set + */ + public void setReadClipboard(boolean readClipboard) { + this.readClipboard = readClipboard; + } + + /** Constructor for main config. */ + public Config() { + this.init(); + } + + /** Init config. */ + public void init() { + getOperatingSystemType(); + + this.servers.forEach( + (key, server) -> { + server.init(); + }); + } + + private void getOperatingSystemType() { + if (currrentOs == null) { + String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); + LOGGER.debug("Current OS is <{}>", osName); //$NON-NLS-1$ + + if ((osName.indexOf("mac") >= 0) || (osName.indexOf("darwin") >= 0)) { + currrentOs = OsType.MACOS; + } else if (osName.indexOf("win") >= 0) { + currrentOs = OsType.WINDOWS; + } else if (osName.indexOf("nux") >= 0) { + currrentOs = OsType.LINUX; + } else { + currrentOs = OsType.OTHER; + } + } + } + + /** + * Add new servers in main config. + * + * @param servers - list of servers + * @return list of servers + */ + public List addNewServers(List servers) { + // Пакетное добавление серверов в список, предполагается для механизма импорта из списка + // информационных баз + + List addedServers = new ArrayList<>(); + + // Имя сервера, которое приходит сюда не равно Представлению сервера, выводимому в списке + // Имя сервера. оно же Key в map и json, строка вида Server:1541, с обязательным указанием порта + // менеджера, к которому подключаемся + // если порт менеджера не задан - ставим стандартный 1541 + // переделать + for (String serverName : servers) { + if (!this.servers.containsKey(serverName)) { + Server serverConfig = new Server(serverName); + this.servers.put(serverName, serverConfig); + + addedServers.add(serverName); + } + } + + return addedServers; + } + + /** Connect to all servers in silent mode. */ + public void connectAllServers() { + servers.forEach((serverKey, server) -> server.connectToServer(false, true)); + } + + /** Check connection to all servers in silent mode. */ + public void checkConnectionAllServers() { + servers.forEach((serverKey, server) -> server.connectToServer(true, true)); + } + + /** + * Is Windows. + * + * @return true is Windows + */ + public boolean isWindows() { + return currrentOs == OsType.WINDOWS; + } + + /** + * Is Linux. + * + * @return true is Linux + */ + public boolean isLinux() { + return currrentOs == OsType.LINUX; + } + + /** + * Is MacOs. + * + * @return true is MacOs + */ + public boolean isMacOs() { + return currrentOs == OsType.MACOS; + } + + /** + * Set sessions column order. + * + * @param columnOrder - new column order + */ + public void setSessionsColumnOrder(int[] columnOrder) { + sessionColumnProperties.setOrder(columnOrder); + } + + /** + * Set connection column order. + * + * @param columnOrder - new column order + */ + public void setConnectionsColumnOrder(int[] columnOrder) { + connectionColumnProperties.setOrder(columnOrder); + } + + /** + * Set lock column order. + * + * @param columnOrder - new column order + */ + public void setLocksColumnOrder(int[] columnOrder) { + lockColumnProperties.setOrder(columnOrder); + } + + /** + * Set working processes column order. + * + * @param columnOrder - new column order + */ + public void setWorkingProcessesColumnOrder(int[] columnOrder) { + wpColumnProperties.setOrder(columnOrder); + } + + /** + * Set working servers column order. + * + * @param columnOrder - new column order + */ + public void setWorkingServersColumnOrder(int[] columnOrder) { + wsColumnProperties.setOrder(columnOrder); + } + + /** + * Init sessions column count. + * + * @param columnCount - new column count + */ + public void initSessionsColumnCount(int columnCount) { + + if (sessionColumnProperties == null) { + sessionColumnProperties = new ColumnProperties(columnCount); + } else { + sessionColumnProperties.updateColumnProperties(columnCount); + } + } + + /** + * Init connection column count. + * + * @param columnCount - new column count + */ + public void initConnectionsColumnCount(int columnCount) { + + if (connectionColumnProperties == null) { + connectionColumnProperties = new ColumnProperties(columnCount); + } else { + connectionColumnProperties.updateColumnProperties(columnCount); + } + } + + /** + * Init lock column count. + * + * @param columnCount - new column count + */ + public void initLocksColumnCount(int columnCount) { + + if (lockColumnProperties == null) { + lockColumnProperties = new ColumnProperties(columnCount); + } else { + lockColumnProperties.updateColumnProperties(columnCount); + } + } + + /** + * Init working processes column count. + * + * @param columnCount - new column count + */ + public void initWorkingProcessesColumnCount(int columnCount) { + + if (wpColumnProperties == null) { + wpColumnProperties = new ColumnProperties(columnCount); + } else { + wpColumnProperties.updateColumnProperties(columnCount); + } + } + + /** + * Init working servers column count. + * + * @param columnCount - new column count + */ + public void initWorkingServersColumnCount(int columnCount) { + + if (wsColumnProperties == null) { + wsColumnProperties = new ColumnProperties(columnCount); + } else { + wsColumnProperties.updateColumnProperties(columnCount); + } + } + + /** + * Set sessions column width. + * + * @param index - index of column + * @param width - column width + */ + public void setSessionsColumnWidth(int index, int width) { + sessionColumnProperties.setWidth(index, width); + } + + /** + * Set connection column width. + * + * @param index - index of column + * @param width - column width + */ + public void setConnectionsColumnWidth(int index, int width) { + connectionColumnProperties.setWidth(index, width); + } + + /** + * Set lock column width. + * + * @param index - index of column + * @param width - column width + */ + public void setLocksColumnWidth(int index, int width) { + lockColumnProperties.setWidth(index, width); + } + + /** + * Set working processes column width. + * + * @param index - index of column + * @param width - column width + */ + public void setWorkingProcessesColumnWidth(int index, int width) { + wpColumnProperties.setWidth(index, width); + } + + /** + * Set working servers column width. + * + * @param index - index of column + * @param width - column width + */ + public void setWorkingServersColumnWidth(int index, int width) { + wsColumnProperties.setWidth(index, width); + } +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java index 7cec347..cbff728 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java @@ -1,97 +1,126 @@ package ru.yanygin.clusterAdminLibrary; +import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; +import com._1c.v8.ibis.admin.IWorkingProcessInfo; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; -import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; -import com._1c.v8.ibis.admin.IWorkingProcessInfo; - +/** Extend info for connection. */ public class ConnectionInfoExtended implements IInfoExtended { - - private static final String TITLE_INFOBASE = Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ - private static final String TITLE_CONNECTION = Messages.getString("ConnectionInfo.Connection"); //$NON-NLS-1$ - private static final String TITLE_SESSION = Messages.getString("ConnectionInfo.Session"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_APPLICATION = Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ - private static final String TITLE_SERVER = Messages.getString("SessionInfo.Server"); //$NON-NLS-1$ - private static final String TITLE_RP_HOST_PORT = Messages.getString("ConnectionInfo.RpHostPort"); //$NON-NLS-1$ - private static final String TITLE_CONNECTED_AT = Messages.getString("ConnectionInfo.ConnectedAt"); //$NON-NLS-1$ -// private static final String TITLE_INFOBASE_CONNECTION_ID = Messages.getString("ConnectionInfo.InfobaseConnectionID"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - UUID infobaseId; - IInfoBaseConnectionShort connectionInfo; - List workingProcesses; - - Map columnsMap = new LinkedHashMap<>(); - - public ConnectionInfoExtended(Server server, UUID clusterId, UUID infobaseId, - IInfoBaseConnectionShort connectionInfo, List workingProcesses, - Map columnsMap) { - - this.server = server; - this.clusterId = clusterId; - this.infobaseId = infobaseId; - this.connectionInfo = connectionInfo; - this.workingProcesses = workingProcesses; - this.columnsMap = columnsMap; - - } - - public static void initColumnsName(Map connectionColumnsMap) { - - connectionColumnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_CONNECTION, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_SESSION, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_SERVER, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_RP_HOST_PORT, ""); //$NON-NLS-1$ - connectionColumnsMap.put(TITLE_CONNECTED_AT, ""); //$NON-NLS-1$ -// connectionColumnsMap.put(TITLE_INFOBASE_CONNECTION_ID, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initConnectionsColumnCount(connectionColumnsMap.size()); - - } - - public String[] getExtendedInfo() { - - String infobaseName = ""; //$NON-NLS-1$ - if (infobaseId == null && !connectionInfo.getInfoBaseId().equals(emptyUuid)) { - infobaseId = connectionInfo.getInfoBaseId(); - infobaseName = server.getInfoBaseName(clusterId, infobaseId); - } - - String[] currentWorkingProcessInfo = getWorkingProcessInfo(connectionInfo.getWorkingProcessId()); - - Map session = new LinkedHashMap<>(); - session.putAll(columnsMap); - - session.put(TITLE_INFOBASE, infobaseName); - session.put(TITLE_CONNECTION, Integer.toString(connectionInfo.getConnId())); - session.put(TITLE_SESSION, Integer.toString(connectionInfo.getSessionNumber())); - session.put(TITLE_COMPUTER, connectionInfo.getHost()); - session.put(TITLE_APPLICATION, server.getApplicationName(connectionInfo.getApplication())); - session.put(TITLE_SERVER, currentWorkingProcessInfo[0]); // $NON-NLS-1$ - session.put(TITLE_RP_HOST_PORT, currentWorkingProcessInfo[1]); - session.put(TITLE_CONNECTED_AT, dateToString(connectionInfo.getConnectedAt())); -// session.put(TITLE_INFOBASE_CONNECTION_ID, convertUuidToString(connectionInfo.getInfoBaseConnectionId())); - - return session.values().toArray(new String[0]); - - } - - private String[] getWorkingProcessInfo(UUID workingProcessId) { - - for (IWorkingProcessInfo workingProcess : workingProcesses) { - if (workingProcess.getWorkingProcessId().equals(workingProcessId)) { - return new String[] { workingProcess.getHostName(), Integer.toString(workingProcess.getMainPort()) }; - } - } - return new String[] { "", "" }; - } - + + private static final String TITLE_INFOBASE = + Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ + private static final String TITLE_CONNECTION = + Messages.getString("ConnectionInfo.Connection"); //$NON-NLS-1$ + private static final String TITLE_SESSION = + Messages.getString("ConnectionInfo.Session"); //$NON-NLS-1$ + private static final String TITLE_COMPUTER = + Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ + private static final String TITLE_APPLICATION = + Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ + private static final String TITLE_SERVER = + Messages.getString("SessionInfo.Server"); //$NON-NLS-1$ + private static final String TITLE_RP_HOST_PORT = + Messages.getString("ConnectionInfo.RpHostPort"); //$NON-NLS-1$ + private static final String TITLE_CONNECTED_AT = + Messages.getString("ConnectionInfo.ConnectedAt"); //$NON-NLS-1$ + // private static final String TITLE_INFOBASE_CONNECTION_ID = + // Messages.getString("ConnectionInfo.InfobaseConnectionID"); //$NON-NLS-1$ + + Server server; + UUID clusterId; + UUID infobaseId; + IInfoBaseConnectionShort connectionInfo; + List workingProcesses; + + Map columnsMap = new LinkedHashMap<>(); + + /** + * Create extended info for working server. + * + * @param server - server + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @param connectionInfo - connection info + * @param workingProcesses - working process info + * @param columnsMap - columns map + */ + public ConnectionInfoExtended( + Server server, + UUID clusterId, + UUID infobaseId, + IInfoBaseConnectionShort connectionInfo, + List workingProcesses, + Map columnsMap) { + + this.server = server; + this.clusterId = clusterId; + this.infobaseId = infobaseId; + this.connectionInfo = connectionInfo; + this.workingProcesses = workingProcesses; + this.columnsMap = columnsMap; + } + + /** + * Init columns name. + * + * @param columnsMap - sample map with columns name + */ + public static void initColumnsName(Map columnsMap) { + + columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CONNECTION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SESSION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SERVER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_RP_HOST_PORT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CONNECTED_AT, ""); //$NON-NLS-1$ + // connectionColumnsMap.put(TITLE_INFOBASE_CONNECTION_ID, ""); //$NON-NLS-1$ + + ClusterProvider.getCommonConfig().initConnectionsColumnCount(columnsMap.size()); + } + + @Override + public String[] getExtendedInfo() { + + String infobaseName = ""; //$NON-NLS-1$ + if (infobaseId == null && !connectionInfo.getInfoBaseId().equals(emptyUuid)) { + infobaseId = connectionInfo.getInfoBaseId(); + infobaseName = server.getInfoBaseName(clusterId, infobaseId); + } + + String[] currentWorkingProcessInfo = + getWorkingProcessInfo(connectionInfo.getWorkingProcessId()); + + Map session = new LinkedHashMap<>(); + session.putAll(columnsMap); + + session.put(TITLE_INFOBASE, infobaseName); + session.put(TITLE_CONNECTION, Integer.toString(connectionInfo.getConnId())); + session.put(TITLE_SESSION, Integer.toString(connectionInfo.getSessionNumber())); + session.put(TITLE_COMPUTER, connectionInfo.getHost()); + session.put(TITLE_APPLICATION, server.getApplicationName(connectionInfo.getApplication())); + session.put(TITLE_SERVER, currentWorkingProcessInfo[0]); //$NON-NLS-1$ + session.put(TITLE_RP_HOST_PORT, currentWorkingProcessInfo[1]); + session.put(TITLE_CONNECTED_AT, dateToString(connectionInfo.getConnectedAt())); + // session.put(TITLE_INFOBASE_CONNECTION_ID, + // convertUuidToString(connectionInfo.getInfoBaseConnectionId())); + + return session.values().toArray(new String[0]); + } + + private String[] getWorkingProcessInfo(UUID workingProcessId) { + + for (IWorkingProcessInfo workingProcess : workingProcesses) { + if (workingProcess.getWorkingProcessId().equals(workingProcessId)) { + return new String[] { + workingProcess.getHostName(), Integer.toString(workingProcess.getMainPort()) + }; + } + } + return new String[] {"", ""}; + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java index a31c0b4..e0b3a79 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java @@ -7,63 +7,128 @@ import java.util.Map; import java.util.UUID; +/** Extend info. */ public interface IInfoExtended { - - UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ - DecimalFormat dFLong = new DecimalFormat("###,###"); //$NON-NLS-1$ - DecimalFormat dFDouble6 = new DecimalFormat("#,##0.000000"); //$NON-NLS-1$ - DecimalFormat dFDouble3 = new DecimalFormat("###,##0.000"); //$NON-NLS-1$ - -// NumberFormat fmt = NumberFormat.getInstance(); -// fmt.setGroupingUsed(false); -// fmt.setMaximumIntegerDigits(999); -// fmt.setMaximumFractionDigits(999); - - public static void initColumnsName(Map columnsMap) { - } - - public static boolean highlightItem(Date startDateItem) { - - Config commonConfig = ClusterProvider.getCommonConfig(); - return commonConfig.highlightNewItems && - (new Date().getTime() - startDateItem.getTime() < commonConfig.highlightNewItemsDuration * 1000); - } - - public String[] getExtendedInfo(); - - default String convertUuidToString(UUID uuid) { - return uuid.equals(emptyUuid) ? "" : uuid.toString(); //$NON-NLS-1$ - } - - default String dateToString(Date date) { - - DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); //$NON-NLS-1$ - Date emptyDate = new Date(0); - - return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ - } - - default String millisecondToString(int value) { - return Double.toString(((double) value) / 1000); - } - - default String millisecondToString(long value) { - return Double.toString(((double) value) / 1000); - } - - default String longToStringGroup(long value) { - return dFLong.format(value); - } - - default String double6ToString(double value) { - return dFDouble6.format(value); - } - - default String double3ToString(double value) { - return dFDouble3.format((double) value / 1000); - } - - default String doubleToString1(double value) { - return String.format ("%.9f", value); - } + + UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ + DecimalFormat dFLong = new DecimalFormat("###,###"); //$NON-NLS-1$ + DecimalFormat dFDouble6 = new DecimalFormat("#,##0.000000"); //$NON-NLS-1$ + DecimalFormat dFDouble3 = new DecimalFormat("###,##0.000"); //$NON-NLS-1$ + + // NumberFormat fmt = NumberFormat.getInstance(); + // fmt.setGroupingUsed(false); + // fmt.setMaximumIntegerDigits(999); + // fmt.setMaximumFractionDigits(999); + + /** + * Init columns name. + * + * @param columnsMap - sample map with columns name + */ + public static void initColumnsName(Map columnsMap) {} + + /** + * Check highlight for new item in list. + * + * @param startDateItem - date of start + * @return true if need highlight + */ + public static boolean highlightItem(Date startDateItem) { + + Config commonConfig = ClusterProvider.getCommonConfig(); + return commonConfig.isHighlightNewItems() + && (new Date().getTime() - startDateItem.getTime() + < commonConfig.getHighlightNewItemsDuration() * 1000); + } + + /** + * Get extended info. + * + * @return extended info + */ + public String[] getExtendedInfo(); + + /** + * Convert UUID to string. + * + * @param uuid - UUID + * @return string + */ + default String convertUuidToString(UUID uuid) { + return uuid.equals(emptyUuid) ? "" : uuid.toString(); //$NON-NLS-1$ + } + + /** + * Cast date to string. + * + * @param date - date + * @return date format to string + */ + default String dateToString(Date date) { + + DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); //$NON-NLS-1$ + Date emptyDate = new Date(0); + + return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ + } + + /** + * Cast millisecond to string. + * + * @param value - millisecond + * @return millisecond to string + */ + default String millisecondToString(int value) { + return Double.toString(((double) value) / 1000); + } + + /** + * Cast millisecond to string. + * + * @param value - millisecond + * @return millisecond to string + */ + default String millisecondToString(long value) { + return Double.toString(((double) value) / 1000); + } + + /** + * Cast long value to string. + * + * @param value - long value + * @return long value to string + */ + default String longToStringGroup(long value) { + return dFLong.format(value); + } + + /** + * Cast double value to string. + * + * @param value - double value + * @return double value to string + */ + default String double6ToString(double value) { + return dFDouble6.format(value); + } + + /** + * Cast double value to string. + * + * @param value - double value + * @return double value to string + */ + default String double3ToString(double value) { + return dFDouble3.format((double) value / 1000); + } + + /** + * Cast double value to string. + * + * @param value - double value + * @return double value to string + */ + default String doubleToString1(double value) { + return String.format("%.9f", value); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java index 32cb61f..3465a45 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java @@ -1,137 +1,167 @@ package ru.yanygin.clusterAdminLibrary; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; import com._1c.v8.ibis.admin.IObjectLockInfo; import com._1c.v8.ibis.admin.ISessionInfo; import com._1c.v8.ibis.admin.IWorkingProcessInfo; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +/** Extend info for lock. */ public class LockInfoExtended implements IInfoExtended { - - private static final String TITLE_DESCRIPTION = Messages.getString("InfoTables.Description"); //$NON-NLS-1$ - private static final String TITLE_INFOBASE = Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ - private static final String TITLE_CONNECTION = Messages.getString("ConnectionInfo.Connection"); //$NON-NLS-1$ - private static final String TITLE_SESSION = Messages.getString("ConnectionInfo.Session"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_APPLICATION = Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ - private static final String TITLE_HOSTNAME = Messages.getString("ConnectionInfo.Hostname"); //$NON-NLS-1$ - private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ - private static final String TITLE_LOCKED_AT = Messages.getString("LockInfo.LockedAt"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - UUID infobaseId; - IObjectLockInfo lockInfo; - List sessionsInfo; - List connections; - - Map columnsMap = new LinkedHashMap<>(); - - public LockInfoExtended(Server server, UUID clusterId, UUID infobaseId, IObjectLockInfo lockInfo, - List sessionsInfo, List connections, - Map columnsMap) { - - this.server = server; - this.clusterId = clusterId; - this.infobaseId = infobaseId; - this.lockInfo = lockInfo; - this.sessionsInfo = sessionsInfo; - this.connections = connections; - this.columnsMap = columnsMap; - - } - - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_DESCRIPTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SESSION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_HOSTNAME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LOCKED_AT, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initLocksColumnCount(columnsMap.size()); - - } - - public String[] getExtendedInfo() { - - var connectionNumber = ""; //$NON-NLS-1$ - var sessionNumber = ""; //$NON-NLS-1$ - var computerName = ""; //$NON-NLS-1$ - var appName = ""; //$NON-NLS-1$ - var hostName = ""; //$NON-NLS-1$ - var hostPort = ""; //$NON-NLS-1$ - var infobaseName = ""; //$NON-NLS-1$ - - if (!lockInfo.getSid().equals(emptyUuid)) { - ISessionInfo session = getSessionInfoFromLockConnectionId(lockInfo, sessionsInfo); - if (session != null) { - sessionNumber = Integer.toString(session.getSessionId()); - appName = session.getAppId(); - computerName = session.getHost(); - infobaseName = server.getInfoBaseName(clusterId, session.getInfoBaseId()); - } - - } else if (!lockInfo.getConnectionId().equals(emptyUuid)) { - IInfoBaseConnectionShort connection = getConnectionInfoFromLockConnectionId(lockInfo, connections); - - if (connection != null) { - connectionNumber = Integer.toString(connection.getConnId()); - appName = connection.getApplication(); - computerName = connection.getHost(); - infobaseName = server.getInfoBaseName(clusterId, connection.getInfoBaseId()); - UUID wpId = connection.getWorkingProcessId(); - - IWorkingProcessInfo wpInfo = server.getWorkingProcessInfo(clusterId, wpId); - if (wpInfo != null) { - hostName = wpInfo.getHostName(); - hostPort = Integer.toString(wpInfo.getMainPort()); - } - } - } - - Map lock = new LinkedHashMap<>(); - lock.putAll(columnsMap); - - lock.put(TITLE_DESCRIPTION, lockInfo.getLockDescr()); - lock.put(TITLE_INFOBASE, infobaseName); - lock.put(TITLE_CONNECTION, connectionNumber); - lock.put(TITLE_SESSION, sessionNumber); - lock.put(TITLE_COMPUTER, computerName); - lock.put(TITLE_APPLICATION, server.getApplicationName(appName)); - lock.put(TITLE_HOSTNAME, hostName); - lock.put(TITLE_PORT, hostPort); - lock.put(TITLE_LOCKED_AT, dateToString(lockInfo.getLockedAt())); - - return lock.values().toArray(new String[0]); - - } - - private ISessionInfo getSessionInfoFromLockConnectionId(IObjectLockInfo lockInfo, List sessionsInfo) { - - for (ISessionInfo session : sessionsInfo) { - if (session.getSid().equals(lockInfo.getSid())) - return session; - } - return null; - } - - private IInfoBaseConnectionShort getConnectionInfoFromLockConnectionId(IObjectLockInfo lockInfo, - List connections) { - - for (IInfoBaseConnectionShort connection : connections) { - if (connection.getInfoBaseConnectionId().equals(lockInfo.getConnectionId())) - return connection; - } - return null; - } - + + private static final String TITLE_DESCRIPTION = + Messages.getString("InfoTables.Description"); //$NON-NLS-1$ + private static final String TITLE_INFOBASE = + Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ + private static final String TITLE_CONNECTION = + Messages.getString("ConnectionInfo.Connection"); //$NON-NLS-1$ + private static final String TITLE_SESSION = + Messages.getString("ConnectionInfo.Session"); //$NON-NLS-1$ + private static final String TITLE_COMPUTER = + Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ + private static final String TITLE_APPLICATION = + Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ + private static final String TITLE_HOSTNAME = + Messages.getString("ConnectionInfo.Hostname"); //$NON-NLS-1$ + private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ + private static final String TITLE_LOCKED_AT = + Messages.getString("LockInfo.LockedAt"); //$NON-NLS-1$ + + Server server; + UUID clusterId; + UUID infobaseId; + IObjectLockInfo lockInfo; + List sessionsInfo; + List connections; + + Map columnsMap = new LinkedHashMap<>(); + + /** + * Create extended info for working server. + * + * @param server - server + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @param lockInfo - lock info + * @param sessionsInfo - sessions info + * @param connections - list of connections + * @param columnsMap - columns map + */ + public LockInfoExtended( + Server server, + UUID clusterId, + UUID infobaseId, + IObjectLockInfo lockInfo, + List sessionsInfo, + List connections, + Map columnsMap) { + + this.server = server; + this.clusterId = clusterId; + this.infobaseId = infobaseId; + this.lockInfo = lockInfo; + this.sessionsInfo = sessionsInfo; + this.connections = connections; + this.columnsMap = columnsMap; + } + + /** + * Init columns name. + * + * @param columnsMap - sample map with columns name + */ + public static void initColumnsName(Map columnsMap) { + + columnsMap.put(TITLE_DESCRIPTION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CONNECTION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SESSION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_HOSTNAME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_LOCKED_AT, ""); //$NON-NLS-1$ + + ClusterProvider.getCommonConfig().initLocksColumnCount(columnsMap.size()); + } + + @Override + public String[] getExtendedInfo() { + + var connectionNumber = ""; //$NON-NLS-1$ + var sessionNumber = ""; //$NON-NLS-1$ + var computerName = ""; //$NON-NLS-1$ + var appName = ""; //$NON-NLS-1$ + var hostName = ""; //$NON-NLS-1$ + var hostPort = ""; //$NON-NLS-1$ + var infobaseName = ""; //$NON-NLS-1$ + + if (!lockInfo.getSid().equals(emptyUuid)) { + ISessionInfo session = getSessionInfoFromLockConnectionId(lockInfo, sessionsInfo); + if (session != null) { + sessionNumber = Integer.toString(session.getSessionId()); + appName = session.getAppId(); + computerName = session.getHost(); + infobaseName = server.getInfoBaseName(clusterId, session.getInfoBaseId()); + } + + } else if (!lockInfo.getConnectionId().equals(emptyUuid)) { + IInfoBaseConnectionShort connection = + getConnectionInfoFromLockConnectionId(lockInfo, connections); + + if (connection != null) { + connectionNumber = Integer.toString(connection.getConnId()); + appName = connection.getApplication(); + computerName = connection.getHost(); + infobaseName = server.getInfoBaseName(clusterId, connection.getInfoBaseId()); + UUID wpId = connection.getWorkingProcessId(); + + IWorkingProcessInfo wpInfo = server.getWorkingProcessInfo(clusterId, wpId); + if (wpInfo != null) { + hostName = wpInfo.getHostName(); + hostPort = Integer.toString(wpInfo.getMainPort()); + } + } + } + + Map lock = new LinkedHashMap<>(); + lock.putAll(columnsMap); + + lock.put(TITLE_DESCRIPTION, lockInfo.getLockDescr()); + lock.put(TITLE_INFOBASE, infobaseName); + lock.put(TITLE_CONNECTION, connectionNumber); + lock.put(TITLE_SESSION, sessionNumber); + lock.put(TITLE_COMPUTER, computerName); + lock.put(TITLE_APPLICATION, server.getApplicationName(appName)); + lock.put(TITLE_HOSTNAME, hostName); + lock.put(TITLE_PORT, hostPort); + lock.put(TITLE_LOCKED_AT, dateToString(lockInfo.getLockedAt())); + + return lock.values().toArray(new String[0]); + } + + private ISessionInfo getSessionInfoFromLockConnectionId( + IObjectLockInfo lockInfo, List sessionsInfo) { + + for (ISessionInfo session : sessionsInfo) { + if (session.getSid().equals(lockInfo.getSid())) { + return session; + } + } + return null; + } + + private IInfoBaseConnectionShort getConnectionInfoFromLockConnectionId( + IObjectLockInfo lockInfo, List connections) { + + for (IInfoBaseConnectionShort connection : connections) { + if (connection.getInfoBaseConnectionId().equals(lockInfo.getConnectionId())) { + return connection; + } + } + return null; + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Messages.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Messages.java index c4b6a1d..d037178 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Messages.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Messages.java @@ -4,23 +4,35 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; +/** Messages. */ public class Messages { - private static final String BUNDLE_NAME = "ru.yanygin.clusterAdminLibrary.messages"; //$NON-NLS-1$ - - private static ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); - - public static void reloadBundle(Locale targetLocale) { - RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, targetLocale); - } - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } + private static final String BUNDLE_NAME = + "ru.yanygin.clusterAdminLibrary.messages"; //$NON-NLS-1$ + + private static ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); + + /** + * Reload localized strings. + * + * @param targetLocale - target locale + */ + public static void reloadBundle(Locale targetLocale) { + RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, targetLocale); + } + + private Messages() {} + + /** + * Get localized string. + * + * @param key - key of string + * @return localized string + */ + public static String getString(String key) { + try { + return RESOURCE_BUNDLE.getString(key); + } catch (MissingResourceException e) { + return '!' + key + '!'; + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java index 25be03d..f8c26c2 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java @@ -1,18 +1,5 @@ package ru.yanygin.clusterAdminLibrary; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.MessageBox; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com._1c.v8.ibis.admin.AgentAdminException; import com._1c.v8.ibis.admin.IAgentAdminConnection; import com._1c.v8.ibis.admin.IAssignmentRuleInfo; @@ -43,2355 +30,2965 @@ import com._1c.v8.ibis.admin.client.IAgentAdminConnectorFactory; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; - +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.MessageBox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import ru.yanygin.clusterAdminLibraryUI.AuthenticateDialog; +/** Server 1C Enterprise parameters. */ public class Server { - - @SerializedName("Description") - @Expose - public String description; - - @SerializedName("AgentHost") - @Expose - public String agentHost; - - @SerializedName("AgentPort") - @Expose - public int agentPort; - - @SerializedName("RasHost") - @Expose - public String rasHost; - - @SerializedName("RasPort") - @Expose - public int rasPort; - - @SerializedName("UseLocalRas") - @Expose - public boolean useLocalRas; - - @SerializedName("LocalRasPort") - @Expose - public int localRasPort; - - @SerializedName("LocalRasV8version") - @Expose - public String localRasV8version; - - @SerializedName("Autoconnect") - @Expose - public boolean autoconnect; - - @SerializedName("SaveCredentials") - @Expose - public boolean saveCredentials; - - @SerializedName("AgentUser") - @Expose - public String agentUserName; - - @SerializedName("AgentPassword") - @Expose - public String agentPassword; - - @SerializedName("ClustersCredentials") - @Expose - public Map credentialsClustersCashe; // TODO Креды инфобаз хранить тут же или в отдельном списке? - - public Map credentialsInfobasesCashe; - - private boolean available; - private Process localRASProcess; - - private String connectionError; - - public String getConnectionError() { - return connectionError; - } - - private static Logger LOGGER = LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ - private static UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ - - private IAgentAdminConnector agentConnector; - private IAgentAdminConnection agentConnection; - private String agentVersion = ""; //$NON-NLS-1$ - - public static final String THIN_CLIENT = "1CV8C"; //$NON-NLS-1$ - public static final String THICK_CLIENT = "1CV8"; //$NON-NLS-1$ - public static final String DESIGNER = "Designer"; //$NON-NLS-1$ - public static final String SERVER_CONSOLE = "SrvrConsole"; //$NON-NLS-1$ - public static final String RAS_CONSOLE = "RAS"; //$NON-NLS-1$ - public static final String JOBSCHEDULER = "JobScheduler"; //$NON-NLS-1$ - - interface IRunAuthenticate { - void performAutenticate(String userName, String password, boolean saveNewUserpass); - } - - interface IGetInfobaseInfo { - IInfoBaseInfo getInfo(String userName, String password); - } - - public String getApplicationName(String appId) { - switch (appId) { - case THIN_CLIENT: - return Messages.getString("Server.ThinClient"); //$NON-NLS-1$ - case THICK_CLIENT: - return Messages.getString("Server.ThickClient"); //$NON-NLS-1$ - case DESIGNER: - return Messages.getString("Server.Designer"); //$NON-NLS-1$ - case SERVER_CONSOLE: - return Messages.getString("Server.ClusterConsole"); //$NON-NLS-1$ - case RAS_CONSOLE: - return Messages.getString("Server.AdministrationServer"); //$NON-NLS-1$ - case JOBSCHEDULER: - return Messages.getString("Server.JobScheduler"); //$NON-NLS-1$ - case "": //$NON-NLS-1$ - return ""; //$NON-NLS-1$ - default: - return String.format(Messages.getString("Server.UnknownClient"), appId); //$NON-NLS-1$ - } - } - - public String getAgentVersion() { - return agentVersion; - } - - public Server(String serverName) { - - calculateServerParams(serverName); - - this.useLocalRas = false; - this.localRasPort = 0; - this.localRasV8version = ""; //$NON-NLS-1$ - this.autoconnect = false; - this.available = false; - this.saveCredentials = false; - this.agentVersion = ""; //$NON-NLS-1$ - - init(); - - } - - public void init() { - - // При чтении конфиг-файла отсутствующие поля, инициализируются значением null - if (agentUserName == null) - agentUserName = ""; //$NON-NLS-1$ - if (agentPassword == null) - agentPassword = ""; //$NON-NLS-1$ - if (description == null) - description = ""; //$NON-NLS-1$ - if (localRasV8version == null) - localRasV8version = ""; //$NON-NLS-1$ - if (agentVersion == null) - agentVersion = Messages.getString("Server.NotConnect"); //$NON-NLS-1$ - - if (this.credentialsClustersCashe == null) - this.credentialsClustersCashe = new HashMap<>(); - - this.connectionError = ""; //$NON-NLS-1$ - - LOGGER.info("Server <{}> init done", this.getServerKey()); //$NON-NLS-1$ - - } - - // Надо определиться что должно являться ключем, агент (Server:1540) или - // менеджер (Server:1541) или RAS (Server:1545) - public String getServerKey() { - return agentHost.concat(":").concat(Integer.toString(agentPort)); //$NON-NLS-1$ - } - - public String getDescription() { - - var commonConfig = ClusterProvider.getCommonConfig(); - - var localRasPatternPart = useLocalRas && commonConfig.showLocalRasConnectInfo ? - String.format("(local-RAS:%s)->", getLocalRasPortAsString()) : ""; //$NON-NLS-1$ //$NON-NLS-2$ - var serverVersionPatternPart = commonConfig.showServerVersion ? - String.format(" (%s)", agentVersion) : ""; //$NON-NLS-1$ //$NON-NLS-2$ - var serverDescriptionPatternPart = commonConfig.showServerDescription && !description.isBlank() ? - String.format(" - <%s>", description) : ""; //$NON-NLS-1$ //$NON-NLS-2$ - - return String.format("%s%s:%s%s%s", //$NON-NLS-1$ - localRasPatternPart, agentHost, getAgentPortAsString(), serverVersionPatternPart, serverDescriptionPatternPart); - - } - - private void readAgentVersion() { - - if (!isConnected()) - return; - - try { - agentVersion = agentConnection.getAgentVersion(); - LOGGER.debug("Agent version of server <{}> is <{}>", this.getServerKey(), agentVersion); //$NON-NLS-1$ - } catch (Exception e) { - agentVersion = Messages.getString("Server.UnknownAgentVersion"); //$NON-NLS-1$ - LOGGER.error("Unknown agent version of server <{}>", this.getServerKey()); //$NON-NLS-1$ - } - } - - private String getLocalisedMessage(Throwable excp) { - - Throwable cause = excp.getCause(); - while (cause.getCause() != null) { - cause = cause.getCause(); - if (cause instanceof java.nio.channels.UnresolvedAddressException) - return Messages.getString("Server.UnresolvedAddress"); //$NON-NLS-1$ - } - return cause.getLocalizedMessage(); - } - - - public boolean isFifteenOrOlderAgentVersion() { - return agentVersion.compareTo("8.3.15") >= 0; //$NON-NLS-1$ - } - - public String getAgentPortAsString() { - return Integer.toString(agentPort); - } - - public String getRasPortAsString() { - return Integer.toString(rasPort); - } - - public String getLocalRasPortAsString() { - return Integer.toString(localRasPort); - } - - public void setServerNewProperties(String agentHost, - int agentPort, - String rasHost, - int rasPort, - boolean useLocalRas, - int localRasPort, - String localRasV8version, - boolean autoconnect, - boolean saveCredentials, - String agentUser, - String agentPassword, - Map credentialsClustersCashe) { - - this.agentHost = agentHost; - this.agentPort = agentPort; - this.rasHost = rasHost; - this.rasPort = rasPort; - this.useLocalRas = useLocalRas; - this.localRasPort = localRasPort; - this.localRasV8version = localRasV8version; - this.autoconnect = autoconnect; - this.saveCredentials = saveCredentials; - this.agentUserName = agentUser; - this.agentPassword = agentPassword; - this.credentialsClustersCashe = credentialsClustersCashe; - -// if (this.autoconnect) -// connectAndAuthenticate(false); - - LOGGER.info("Set new properties for server <{}>", this.getServerKey()); //$NON-NLS-1$ - } - - /** - * Вычисляет имя хоста, на котором запущены процессы кластера - * - * @param serverAddress - Имя инф.базы из списка баз. Может содержать номер - * порта менеджера кластера (Если не указан, то - * по-умолчанию 1541). Примеры: Server1c, Server1c:2541 - * @return Имя хоста, на котором запущены процессы кластера - */ - private String cutHostName(String serverAddress) { - String serverName; - String[] ar = serverAddress.split(":"); //$NON-NLS-1$ - if (ar.length > 0) { - serverName = ar[0]; - } else { - serverName = "localhost"; //$NON-NLS-1$ - } - - return serverName; - } - - private int cutManagerPort(String serverAddress) { - int port; - String[] ar = serverAddress.split(":"); //$NON-NLS-1$ - if (ar.length == 1) { - port = 1541; - } else { - port = Integer.parseInt(ar[1]); - } - return port; - } - - private int cutRemoteRASPort(String serverAddress) { - int port; - String[] ar = serverAddress.split(":"); //$NON-NLS-1$ - if (ar.length == 1) { - port = 1545; - } else { - port = Integer.parseInt(ar[1].substring(0, ar[1].length() - 1).concat("5")); //$NON-NLS-1$ - } - return port; - } - - private void calculateServerParams(String serverAddress) { - - String host; - int newAgentPort; - int newRasPort; - - serverAddress = serverAddress.strip(); - if (serverAddress.isBlank()) - serverAddress = "localhost"; //$NON-NLS-1$ - - String[] ar = serverAddress.split(":"); //$NON-NLS-1$ - host = ar[0]; - - if (ar.length == 1) { - newAgentPort = 1540; - newRasPort = 1545; - } else { - int managerPort = Integer.parseInt(ar[1]); - newAgentPort = managerPort - 1; - newRasPort = managerPort + 4; - } - - this.agentHost = host; - this.rasHost = host; - this.agentPort = newAgentPort; - this.rasPort = newRasPort; - - LOGGER.info("Calculate params for Server <{}> ", this.getServerKey()); //$NON-NLS-1$ - - } - - /** - * Checks whether connection to the administration server is established - * - * @return {@code true} if connected, {@code false} overwise - */ - public boolean isConnected() { - boolean isConnected = (agentConnection != null); -// if (isConnected) -// LOGGER.debug("Server {} is already connected", this.getServerKey()); // засоряет лог - - if (!isConnected) - LOGGER.info("The connection a server <{}> is not established", this.getServerKey()); //$NON-NLS-1$ - - return isConnected; - } - - public boolean connectToServer(boolean disconnectAfter, boolean silentMode) { - LOGGER.debug("<{}> start connection", this.getServerKey()); //$NON-NLS-1$ - - if (isConnected()) - return true; - - if (!checkAndRunLocalRAS()) - return false; - - String currentRasHost = useLocalRas ? "localhost" : this.rasHost; //$NON-NLS-1$ - int currentRasPort = useLocalRas ? localRasPort : this.rasPort; - - try { - connectToAgent(currentRasHost, currentRasPort, 20); - - if (disconnectAfter) { - disconnectFromAgent(); - } - } catch (Exception excp) { - available = false; - disconnectLocalRAS(); - - connectionError = String.format("%s connection error:%n <%s>", this.getServerKey(), getLocalisedMessage(excp)); //$NON-NLS-1$ - LOGGER.error(connectionError); - - if (!silentMode) { - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(connectionError); - messageBox.open(); - } - return false; - } - return true; - - } - - /** - * Проверяет включено ли использование локального RAS и запускает его - * - * @return {@code true} если локальный RAS выключен либо включен и удачно запустился, {@code false} если локальный RAS включен и не удалось его запустить - */ - private boolean checkAndRunLocalRAS() { - - if (!ClusterProvider.getCommonConfig().isWindows()) - return true; - - if (!useLocalRas) - return true; - - if (localRasV8version.isBlank() || localRasPort == 0) { - var message = String.format(Messages.getString("Server.LocalRasParamsIsEmpty"), this.getServerKey()); //$NON-NLS-1$ - LOGGER.error(message); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(message); - messageBox.open(); - - return false; - } - - ///////////////////////////// пока только Windows - var processBuilder = new ProcessBuilder(); - var processOutput = ""; //$NON-NLS-1$ - var localRasPath = ClusterProvider.getInstalledV8Versions().get(localRasV8version); - if (localRasPath == null) { - var message = String.format(Messages.getString("Server.LocalRasNotFound"), this.getServerKey()); //$NON-NLS-1$ - LOGGER.error(message); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(message); - messageBox.open(); - - return false; - } - - Map env = processBuilder.environment(); - - env.put("RAS_PATH", localRasPath); //$NON-NLS-1$ - env.put("RAS_PORT", getLocalRasPortAsString()); //$NON-NLS-1$ - env.put("AGENT_HOST", agentHost); //$NON-NLS-1$ - env.put("AGENT_PORT", getAgentPortAsString()); //$NON-NLS-1$ - - processBuilder.command("cmd.exe", "/c", "\"%RAS_PATH%\" cluster %AGENT_HOST%:%AGENT_PORT% --port=%RAS_PORT%"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - LOGGER.debug("Try launch local RAS <{}> <{} --port={}>", localRasPath, this.getServerKey(), getLocalRasPortAsString()); //$NON-NLS-1$ - try { - localRASProcess = processBuilder.start(); - } catch (Exception excp) { - LOGGER.error("Error launch local RAS for server <{}>", this.getServerKey()); //$NON-NLS-1$ - LOGGER.error("Error: <{}>", processOutput, excp); //$NON-NLS-1$ - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - - try { - Thread.sleep(1000); // Дочерний процесс RAS не сразу стартует и в лог о нем не попадает информация - } catch (InterruptedException excp) { - LOGGER.error("Error: ", excp); //$NON-NLS-1$ - } - - LOGGER.debug("Local RAS runnung = {}", localRASProcess.isAlive()); //$NON-NLS-1$ - if (localRASProcess.isAlive()) { - LOGGER.debug("Local RAS parent CMD pid = {}", localRASProcess.pid()); //$NON-NLS-1$ - Stream ch = localRASProcess.children(); - ch.forEach(ch1 -> { - LOGGER.debug("\tchildren -> {}, pid = {}", ch1.info().command().get(), ch1.pid()); //$NON-NLS-1$ - }); - - return true; - } else { - connectionError = String.format("Local RAS <%s> is shutdown", this.getServerKey()); //$NON-NLS-1$ - LOGGER.error(connectionError); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(connectionError); - messageBox.open(); - - return false; - } - - } - - /** - * Проверяет действительна ли еще авторизация на центральном сервере - * и если нет - запускает процесс авторизации. - * - * @param clusterId cluster ID - * @return boolean истекла/не истекла - */ - private boolean checkAutenticateAgent() { - - var needAuthenticate = false; - try { - LOGGER.debug("Gets the list administrators of server <{}>:<{}>", agentHost, agentPort); //$NON-NLS-1$ - agentConnection.getAgentAdmins(); - return true; - } catch (Exception excp) { - LOGGER.error("Error get the list of of server administrators: <{}>", excp.getLocalizedMessage()); //$NON-NLS-1$ - - String[] rightStrings = { // TODO проверить английские варианты - "Недостаточно прав пользователя на управление центральным сервером", - "Администратор центрального сервера не аутентифицирован", - "The user's rights to manage the central server are insufficient", - "The administrator of the central server is not authenticated" - }; - for (String rightString : rightStrings) { - if (excp.getLocalizedMessage().contains(rightString)) { - needAuthenticate = true; - break; - } - } - } - - if (needAuthenticate) - return authenticateAgent(); - - return false; - } - - /** - * Establishes connection with the administration server of 1C:Enterprise server - * cluster - * - * @param address server address - * @param port IP port - * @param timeout connection timeout (in milliseconds) - * - * @throws AgentAdminException in the case of errors. - */ - public void connectToAgent(String address, int port, long timeout) { - if (isConnected()) { - LOGGER.debug("The connection to server <{}> is already established", this.getServerKey()); //$NON-NLS-1$ - available = true; - return; - } - - LOGGER.debug("Try connect server <{}> to address:port=<{}:{}>", //$NON-NLS-1$ - this.getServerKey(), address, port); - - IAgentAdminConnectorFactory factory = new AgentAdminConnectorFactory(); - agentConnector = factory.createConnector(timeout); - agentConnection = agentConnector.connect(address, port); - - available = true; - connectionError = ""; //$NON-NLS-1$ - readAgentVersion(); - - LOGGER.debug("Server <{}> is connected now", this.getServerKey()); //$NON-NLS-1$ - } - - /** - * Terminates connection to the administration server - * - * @throws AgentAdminException in the case of errors. - */ - public void disconnectFromAgent() { - if (!isConnected()) - return; - - disconnectLocalRAS(); - - try { - agentConnector.shutdown(); - LOGGER.info("Server <{}> disconnected now", this.getServerKey()); //$NON-NLS-1$ - } catch (Exception excp) { - LOGGER.info("Server <{}> disconnect error: <{}>", this.getServerKey(), excp.getLocalizedMessage()); //$NON-NLS-1$ - } finally { - agentConnection = null; - agentConnector = null; - } - } - - private void disconnectLocalRAS() { - if (useLocalRas && localRASProcess.isAlive()) { - Stream ch = localRASProcess.children(); - ch.forEach(ch1 -> ch1.destroy()); - localRASProcess.destroy(); - LOGGER.info("Local RAS of Server <{}> is shutdown now", this.getServerKey()); //$NON-NLS-1$ - } - } - - /** - * Authethicates a central server administrator agent. - * Need call of regCluster, getAgentAdmins, regAgentAdmin, unregAgentAdmin - * - * @return {@code true} if authenticated, {@code false} overwise - */ - public boolean authenticateAgent() { - - if (!isConnected()) - return false; - - IRunAuthenticate authMethod = (String userName, String password, boolean saveNewUserpass) -> { - - LOGGER.debug("Try to autenticate the agent server <{}>", this.getServerKey()); //$NON-NLS-1$ - this.agentConnection.authenticateAgent(userName, password); - LOGGER.debug("Authentication to the agent server <{}> was successful", this.getServerKey()); //$NON-NLS-1$ - - // сохраняем новые user/pass после успешной авторизации - if (saveNewUserpass) { - this.agentUserName = userName; - this.agentPassword = password; - LOGGER.debug("New credentials for the agent server <{}> are saved", this.getServerKey()); //$NON-NLS-1$ - } - - }; - String authDescription = String.format(Messages.getString("Server.AuthenticationOfCentralServerAdministrator"), agentHost, agentPort); //$NON-NLS-1$ - - return runAuthProcessWithRequestToUser(authDescription, agentUserName, agentPassword, authMethod); - } - - /** - * Проверяет действительна ли еще авторизация на кластере - * и если нет - запускает процесс авторизации. - * - * @param clusterId cluster ID - * @return boolean действительна/не действительна - */ - private boolean checkAutenticateCluster(UUID clusterId) { - - var needAuthenticate = false; - try { - LOGGER.debug("Check autenticate of cluster <{}>", clusterId); //$NON-NLS-1$ - agentConnection.getClusterAdmins(clusterId); - LOGGER.debug("Autenticate succesful"); //$NON-NLS-1$ - return true; - } catch (Exception excp) { - LOGGER.error("Error autenticate of cluster: <{}>", excp.getLocalizedMessage()); //$NON-NLS-1$ - - String[] rightStrings = { // TODO проверить английские варианты - "Недостаточно прав пользователя на управление кластером", - "Администратор кластера не аутентифицирован", - "Insufficient user rights to manage the cluster", - "The cluster administrator is not authenticated" - }; - for (String rightString : rightStrings) { - if (excp.getLocalizedMessage().toLowerCase().contains(rightString.toLowerCase())) { - needAuthenticate = true; - break; - } - } - } - - if (needAuthenticate) - return authenticateCluster(clusterId); - - // TODO вывести ошибку пользователю - return false; - } - - /** - * Проверяет действительна ли еще авторизация в инфобазе - * и если нет - запускает процесс авторизации. - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - * @return boolean действительна/не действительна - */ - private boolean checkAutenticateInfobase(UUID clusterId, UUID infobaseId) { - - return (getInfoBaseInfo(clusterId, infobaseId) != null); - - } - - /** - * Authethicates a server cluster administrator - * - * @param clusterId cluster ID - * @param userName cluster administrator name - * @param password cluster administrator password - */ - public boolean authenticateCluster(UUID clusterId) { - - if (!isConnected()) - return false; - - IRunAuthenticate authMethod = (String userName, String password, boolean saveNewUserpass) -> { - - String clusterName = getClusterInfo(clusterId).getName(); - - LOGGER.debug("Try to autenticate to the cluster <{}> of server <{}>", clusterName, this.getServerKey()); //$NON-NLS-1$ - agentConnection.authenticate(clusterId, userName, password); - LOGGER.debug("Authentication to the cluster <{}> of server <{}> was successful", clusterName, //$NON-NLS-1$ - this.getServerKey()); - - // сохраняем новые user/pass после успешной авторизации - if (this.saveCredentials && saveNewUserpass) { // || - this.credentialsClustersCashe.put(clusterId, new String[] { userName, password, clusterName }); - LOGGER.debug("New credentials for the cluster <{}> of server <{}> are saved", clusterName, //$NON-NLS-1$ - this.getServerKey()); - } - - }; - - String[] userAndPassword = credentialsClustersCashe.getOrDefault(clusterId, new String[] { "", "" }); //$NON-NLS-1$ //$NON-NLS-2$ - String authDescription = String.format(Messages.getString("Server.AuthenticationOfClusterAdminnistrator"), getServerKey(), getClusterInfo(clusterId).getName()); //$NON-NLS-1$ - - return runAuthProcessWithRequestToUser(authDescription, userAndPassword[0], userAndPassword[1], authMethod); - - } - - private boolean runAuthProcessWithRequestToUser(String authDescription, String userName, String password, - IRunAuthenticate authMethod) { - try { - // Сперва пытаемся авторизоваться под сохраненной учеткой (она может быть - // инициализирована пустыми строками) - authMethod.performAutenticate(userName, password, false); - - } catch (Exception excp) { - LOGGER.debug("Autenticate to server <{}> error: <{}>", this.getServerKey(), excp.getLocalizedMessage()); //$NON-NLS-1$ - - AuthenticateDialog authenticateDialog; - String authExcpMessage = excp.getLocalizedMessage(); - int dialogResult; - - while (true) { // крутимся, пока не подойдет пароль, или пользователь не нажмет Отмена - - try { - LOGGER.debug("Requesting new user credentials for the server <{}>", this.getServerKey()); //$NON-NLS-1$ - authenticateDialog = new AuthenticateDialog(Display.getDefault().getActiveShell(), userName, - authDescription, authExcpMessage); - dialogResult = authenticateDialog.open(); - } catch (Exception exc) { - LOGGER.debug("Request new user credentials for the server <{}> failed", this.getServerKey()); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(exc.getLocalizedMessage()); - messageBox.open(); - return false; - } - - if (dialogResult == 0) { - LOGGER.debug("The user has provided new credentials for the server <{}>", this.getServerKey()); //$NON-NLS-1$ - userName = authenticateDialog.getUsername(); - password = authenticateDialog.getPassword(); - try { - authMethod.performAutenticate(userName, password, true); - break; - } catch (Exception exc) { - LOGGER.debug("Autenticate to server <{}> error: <{}>", this.getServerKey(), //$NON-NLS-1$ - excp.getLocalizedMessage()); - authExcpMessage = exc.getLocalizedMessage(); - continue; - } - } else { - return false; - } - } - - } - return true; - } - - /** - * Adds infobase authentication parameters to the context of the current - * administration server connection - * - * @param clusterId cluster ID - * @param userName infobase administrator name - * @param password infobase administrator password - */ - public void addInfobaseCredentials(UUID clusterId, String userName, String password) { - if (!isConnected()) - return; - -// String clusterName = getClusterInfo(clusterId).getName(); - - agentConnection.addAuthentication(clusterId, userName, password); - LOGGER.debug("Add new infobase credentials for the cluster <{}> of server <{}>", clusterId, //$NON-NLS-1$ - this.getServerKey()); - - } - - /** - * Gets the list of cluster descriptions registered on the central server - * - * @return list of cluster descriptions - */ - public List getClusters() { - if (!isConnected()) - return new ArrayList<>(); - - LOGGER.debug("Get the list of cluster descriptions registered on the central server <{}>", this.getServerKey()); //$NON-NLS-1$ - - List clusters; - try { - clusters = agentConnection.getClusters(); - } catch (Exception excp) { - LOGGER.error("Error get of the list of cluster descriptions", excp.getLocalizedMessage()); //$NON-NLS-1$ - return new ArrayList<>(); - } - - boolean needSaveConfig = false; - for (IClusterInfo cluster : clusters) { - LOGGER.debug("\tCluster: name=<{}>, ID=<{}>, host:port=<{}:{}>", //$NON-NLS-1$ - cluster.getName(), cluster.getClusterId(), cluster.getHostName(), cluster.getMainPort()); - - // обновление имени кластера в кеше credentials - if (saveCredentials) { - String[] credentialClustersCashe = credentialsClustersCashe.get(cluster.getClusterId()); - if (credentialClustersCashe != null && !credentialClustersCashe[2].equals(cluster.getName())) { - credentialClustersCashe[2] = cluster.getName(); - needSaveConfig = true; - } - } - } - if (needSaveConfig) { - // TODO надо сохранить - } - - return clusters; - } - - /** - * Gets the cluster descriptions - * - * @param clusterId cluster ID - * @return cluster descriptions - */ - public IClusterInfo getClusterInfo(UUID clusterId) { - if (!isConnected()) - return null; - - LOGGER.debug("Get the cluster <{}> descriptions", clusterId); //$NON-NLS-1$ - - IClusterInfo clusterInfo; - try { - clusterInfo = agentConnection.getClusterInfo(clusterId); //TODO debug - } catch (Exception excp) { - LOGGER.error("Error get the cluster descriptions", excp); //$NON-NLS-1$ - return null; - } - - LOGGER.debug("Get the cluster descriptions succesful"); //$NON-NLS-1$ - return clusterInfo; - } - - /** - * Gets the list of cluster manager descriptions. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return cluster descriptions - */ - public List getClusterManagers(UUID clusterId) { - LOGGER.debug("Gets the list of cluster manager descriptions in the cluster <{}>", clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List clusterManagers; - try { //TODO debug - clusterManagers = agentConnection.getClusterManagers(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the cluster manager descriptions", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - LOGGER.debug("Get the cluster manager descriptions succesful"); //$NON-NLS-1$ - return clusterManagers; - } - - /** - * Gets a cluster manager description. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return cluster descriptions - */ - public IClusterManagerInfo getClusterManagerInfo(UUID clusterId, UUID managerId) { - LOGGER.debug("Get the cluster manager <{}> description of cluster <{}>", managerId, clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return null; - - if (!checkAutenticateCluster(clusterId)) - return null; - - IClusterManagerInfo clusterManagerInfo; - try { //TODO debug - clusterManagerInfo = agentConnection.getClusterManagerInfo(clusterId, managerId); - } catch (Exception excp) { - LOGGER.error("Error get the cluster manager description", excp); //$NON-NLS-1$ - return null; - } - - LOGGER.debug("Get the cluster manager descriptions succesful"); //$NON-NLS-1$ - return clusterManagerInfo; - } - - /** - * Creates a cluster or changes the state of an existing one. - * Central server authentication is required - * - * @return cluster descriptions - */ - public boolean regCluster(IClusterInfo clusterInfo) { - if (clusterInfo.getClusterId().equals(emptyUuid)) - LOGGER.debug("Registration new cluster <{}>", clusterInfo.getName()); //$NON-NLS-1$ - else - LOGGER.debug("Registration changes a cluster <{}>", clusterInfo.getClusterId()); //$NON-NLS-1$ - - if (!isConnected()) { - LOGGER.debug("The connection a cluster <{}> is not established", clusterInfo.getClusterId()); //$NON-NLS-1$ - return false; - } - - if (!checkAutenticateAgent()) - return false; - - UUID newClusterId; - try { - newClusterId = agentConnection.regCluster(clusterInfo); - } catch (Exception excp) { - LOGGER.error("Error registraion cluster", excp); //$NON-NLS-1$ - throw excp; - } - - if (clusterInfo.getClusterId().equals(emptyUuid)) - LOGGER.debug("Registration new cluster <{}> succesful", newClusterId); //$NON-NLS-1$ - else - LOGGER.debug("Registration changes a cluster <{}> succesful", clusterInfo.getClusterId()); //$NON-NLS-1$ - return true; - } + + @SerializedName("Description") + @Expose + private String description; + + @SerializedName("AgentHost") + @Expose + private String agentHost; + + @SerializedName("AgentPort") + @Expose + private int agentPort; + + @SerializedName("RasHost") + @Expose + private String rasHost; + + @SerializedName("RasPort") + @Expose + private int rasPort; + + @SerializedName("UseLocalRas") + @Expose + private boolean useLocalRas; + + @SerializedName("LocalRasPort") + @Expose + private int localRasPort; + + @SerializedName("LocalRasV8version") + @Expose + private String localRasV8version; + + @SerializedName("Autoconnect") + @Expose + private boolean autoconnect; + + @SerializedName("SaveCredentials") + @Expose + private boolean saveCredentials; + + @SerializedName("AgentUser") + @Expose + private String agentUserName; + + @SerializedName("AgentPassword") + @Expose + private String agentPassword; + + @SerializedName("ClustersCredentials") + @Expose + private Map + credentialsClustersCashe; // TODO Креды инфобаз хранить тут же или в отдельном списке? + + public Map credentialsInfobasesCashe; + + private boolean available; + private Process localRasProcess; + private String connectionError; + private String agentVersion = ""; //$NON-NLS-1$ + + private IAgentAdminConnector agentConnector; + private IAgentAdminConnection agentConnection; + + private static final Logger LOGGER = + LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ + private static UUID emptyUuid = + UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ + + public static final String THIN_CLIENT = "1CV8C"; //$NON-NLS-1$ + public static final String THICK_CLIENT = "1CV8"; //$NON-NLS-1$ + public static final String DESIGNER = "Designer"; //$NON-NLS-1$ + public static final String SERVER_CONSOLE = "SrvrConsole"; //$NON-NLS-1$ + public static final String RAS_CONSOLE = "RAS"; //$NON-NLS-1$ + public static final String JOBSCHEDULER = "JobScheduler"; //$NON-NLS-1$ + + interface IRunAuthenticate { + void performAutenticate(String userName, String password, boolean saveNewUserpass); + } + + interface IGetInfobaseInfo { + IInfoBaseInfo getInfo(String userName, String password); + } + + /** + * Get the server description. + * + * @return server description + */ + public String getDescription() { + return description; + } + + /** + * Set new server description. + * + * @param description - new server description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Get the application name. + * + * @param appId - application ID + * @return application name + */ + public String getApplicationName(String appId) { + switch (appId) { + case THIN_CLIENT: + return Messages.getString("Server.ThinClient"); //$NON-NLS-1$ + case THICK_CLIENT: + return Messages.getString("Server.ThickClient"); //$NON-NLS-1$ + case DESIGNER: + return Messages.getString("Server.Designer"); //$NON-NLS-1$ + case SERVER_CONSOLE: + return Messages.getString("Server.ClusterConsole"); //$NON-NLS-1$ + case RAS_CONSOLE: + return Messages.getString("Server.AdministrationServer"); //$NON-NLS-1$ + case JOBSCHEDULER: + return Messages.getString("Server.JobScheduler"); //$NON-NLS-1$ + case "": //$NON-NLS-1$ + return ""; //$NON-NLS-1$ + default: + return String.format(Messages.getString("Server.UnknownClient"), appId); //$NON-NLS-1$ + } + } + + /** + * Get the agent host name. + * + * @return agent host name + */ + public String getAgentHost() { + return agentHost; + } + + /** + * Set new agent host. + * + * @param agentHost - agent new host + */ + public void setAgentHost(String agentHost) { + this.agentHost = agentHost; + } + + /** + * Get agent port as string. + * + * @return agent port cast to string + */ + public String getAgentPortAsString() { + return Integer.toString(agentPort); + } + + /** + * Set agent port. + * + * @param agentPort - agent port + */ + public void setAgentPort(int agentPort) { + this.agentPort = agentPort; + } + + /** + * Get RAS host. + * + * @return RAS host + */ + public String getRasHost() { + return rasHost; + } + + /** + * Set RAS host. + * + * @param rasHost - RAS host + */ + public void setRasHost(String rasHost) { + this.rasHost = rasHost; + } + + /** + * Get RAS port as string. + * + * @return RAS port cast to string + */ + public String getRasPortAsString() { + return Integer.toString(rasPort); + } + + /** + * Set RAS port. + * + * @param rasPort - RAS port + */ + public void setRasPort(int rasPort) { + this.rasPort = rasPort; + } + + /** + * Get using local RAS. + * + * @return use local RAS + */ + public boolean getUseLocalRas() { + return useLocalRas; + } + + /** + * Set using local RAS. + * + * @param useLocalRas - use local RAS + */ + public void setUseLocalRas(boolean useLocalRas) { + this.useLocalRas = useLocalRas; + } + + /** + * Get local RAS port as string. + * + * @return local RAS port cast to string + */ + public String getLocalRasPortAsString() { + return Integer.toString(localRasPort); + } + + /** + * Set local RAS port. + * + * @param localRasPort - local RAS port + */ + public void setLocalRasPort(int localRasPort) { + this.localRasPort = localRasPort; + } + + /** + * Get local RAS v8 version. + * + * @return local RAS v8 version + */ + public String getLocalRasV8version() { + return localRasV8version; + } + + /** + * Set local RAS v8 version. + * + * @param localRasV8version - local RAS v8 version + */ + public void setLocalRasV8version(String localRasV8version) { + this.localRasV8version = localRasV8version; + } + + /** + * Get version of agent. + * + * @return version + */ + public String getAgentVersion() { + return agentVersion; + } + + /** + * Get connection error string. + * + * @return connection error + */ + public String getConnectionError() { + return connectionError; + } + + /** + * Returns the server key of the form "Server:1541". + * + * @return server key + */ + public String getServerKey() { + return agentHost.concat(":").concat(Integer.toString(agentPort)); //$NON-NLS-1$ + } + + /** + * Get description of the server. + * + * @return description + */ + public String getTreeDescription() { + + var commonConfig = ClusterProvider.getCommonConfig(); + + var localRasPatternPart = + useLocalRas && commonConfig.isShowLocalRasConnectInfo() + ? String.format("(local-RAS:%s)->", getLocalRasPortAsString()) //$NON-NLS-1$ + : ""; //$NON-NLS-1$ + var serverVersionPatternPart = + commonConfig.isShowServerVersion() + ? String.format(" (%s)", agentVersion) //$NON-NLS-1$ + : ""; //$NON-NLS-1$ + var serverDescriptionPatternPart = + commonConfig.isShowServerDescription() && !description.isBlank() + ? String.format(" - <%s>", description) //$NON-NLS-1$ + : ""; //$NON-NLS-1$ + + return String.format( + "%s%s:%s%s%s", //$NON-NLS-1$ + localRasPatternPart, + agentHost, + getAgentPortAsString(), + serverVersionPatternPart, + serverDescriptionPatternPart); + } + + /** + * Get the autoconnect parameters. + * + * @return autoconnect + */ + public boolean getAutoconnect() { + return autoconnect; + } + + /** + * Set the server to connect automatically when the program starts. + * + * @param autoconnect - connect automatically to server + */ + public void setAutoconnect(boolean autoconnect) { + this.autoconnect = autoconnect; + } + + /** + * Get the flag to save the server credentials. + * + * @return save the server credentials + */ + public boolean getSaveCredentials() { + return saveCredentials; + } + + /** + * Set the flag to save the server credentials. + * + * @param saveCredentials - save the server credentials + */ + public void setSaveCredentials(boolean saveCredentials) { + this.saveCredentials = saveCredentials; + } + + /** + * Get agent user name. + * + * @return agent user name + */ + public String getAgentUserName() { + return agentUserName; + } + + /** + * Set the agent username. + * + * @param agentUser - agent username + */ + public void setAgentUserName(String agentUser) { + this.agentUserName = agentUser; + } + + /** + * Get agent user password. + * + * @return agent user password + */ + public String getAgentPassword() { + return agentPassword; + } + + /** + * Set the agent password. + * + * @param agentPassword - agent password + */ + public void setAgentPassword(String agentPassword) { + this.agentPassword = agentPassword; + } + + /** + * Get credentials. + * + * @return credentials + */ + public Map getCredentials() { + return credentialsClustersCashe; + } + + /** + * Set new server credentials. + * + * @param credentials - new credentials for the server + */ + public void setCredentials(Map credentials) { + this.credentialsClustersCashe = credentials; + } + + /** + * Initialize new server instance. + * + * @param serverName - server name of the form "Server:1541". + */ + public Server(String serverName) { + + calculateServerParams(serverName); + + this.useLocalRas = false; + this.localRasPort = 0; + this.localRasV8version = ""; //$NON-NLS-1$ + this.autoconnect = false; + this.available = false; + this.saveCredentials = false; + this.agentVersion = ""; //$NON-NLS-1$ + + init(); + } + + /** Initializes some server parameters. */ + public void init() { + + // При чтении конфиг-файла отсутствующие поля, инициализируются значением null + if (agentUserName == null) { + agentUserName = ""; //$NON-NLS-1$ + } + if (agentPassword == null) { + agentPassword = ""; //$NON-NLS-1$ + } + if (description == null) { + description = ""; //$NON-NLS-1$ + } + if (localRasV8version == null) { + localRasV8version = ""; //$NON-NLS-1$ + } + if (agentVersion == null) { + agentVersion = Messages.getString("Server.NotConnect"); //$NON-NLS-1$ + } + + if (credentialsClustersCashe == null) { + credentialsClustersCashe = new HashMap<>(); + } + + this.connectionError = ""; //$NON-NLS-1$ + + LOGGER.info("Server <{}> init done", getServerKey()); //$NON-NLS-1$ + } + + private void readAgentVersion() { + + if (!isConnected()) { + return; + } + + try { + agentVersion = agentConnection.getAgentVersion(); + LOGGER.debug( + "Agent version of server <{}> is <{}>", this.getServerKey(), agentVersion); //$NON-NLS-1$ + } catch (Exception e) { + agentVersion = Messages.getString("Server.UnknownAgentVersion"); //$NON-NLS-1$ + LOGGER.error("Unknown agent version of server <{}>", this.getServerKey()); //$NON-NLS-1$ + } + } + + private String getLocalisedMessage(Throwable excp) { + + Throwable cause = excp.getCause(); + while (cause.getCause() != null) { + cause = cause.getCause(); + if (cause instanceof java.nio.channels.UnresolvedAddressException) { + return Messages.getString("Server.UnresolvedAddress"); //$NON-NLS-1$ + } + } + return cause.getLocalizedMessage(); + } + + /** + * Return true if v8 version 8.3.15 or more. + * + * @return {@code true} if v8 version 8.3.15 or more + */ + public boolean isFifteenOrMoreAgentVersion() { + return agentVersion.compareTo("8.3.15") >= 0; //$NON-NLS-1$ + } + + /** + * Вычисляет имя хоста и порты, на которых запущены процессы кластера. + * + * @param serverAddress - Имя сервера из списка баз. Может содержать номер порта менеджера + * кластера (Если не указан, то по-умолчанию 1541). Примеры: Server1c, Server1c:2541 + */ + private void calculateServerParams(String serverAddress) { + + String host; + int newAgentPort; + int newRasPort; + + serverAddress = serverAddress.strip(); + if (serverAddress.isBlank()) { + serverAddress = "localhost"; //$NON-NLS-1$ + } + + String[] adr = serverAddress.split(":"); //$NON-NLS-1$ + host = adr[0]; + + if (adr.length == 1) { + newAgentPort = 1540; + newRasPort = 1545; + } else { + int managerPort = Integer.parseInt(adr[1]); + newAgentPort = managerPort - 1; + newRasPort = managerPort + 4; + } + + this.agentHost = host; + this.rasHost = host; + this.agentPort = newAgentPort; + this.rasPort = newRasPort; + + LOGGER.info("Calculate params for Server <{}> ", this.getServerKey()); //$NON-NLS-1$ + } + + /** + * Checks whether connection to the administration server is established. + * + * @return {@code true} if connected, {@code false} overwise + */ + public boolean isConnected() { + boolean isConnected = (agentConnection != null); + + if (!isConnected) { + LOGGER.info( + "The connection a server <{}> is not established", //$NON-NLS-1$ + this.getServerKey()); + } + + return isConnected; + } + + /** + * Connects to the server. + * + * @param disconnectAfter - disconnect after successful connection + * @param silentMode - do not output an error to the user interactively + * @return {@code true} if connect is succesful + */ + public boolean connectToServer(boolean disconnectAfter, boolean silentMode) { + LOGGER.debug("<{}> start connection", this.getServerKey()); //$NON-NLS-1$ + + if (isConnected()) { + return true; + } + + if (!checkAndRunLocalRas()) { + return false; + } + + String currentRasHost = useLocalRas ? "localhost" : this.rasHost; //$NON-NLS-1$ + + int currentRasPort = useLocalRas ? localRasPort : this.rasPort; + + try { + connectToAgent(currentRasHost, currentRasPort, 20); + + if (disconnectAfter) { + disconnectFromAgent(); + } + } catch (Exception excp) { + available = false; + disconnectLocalRas(); + + connectionError = + String.format( + "%s connection error:%n <%s>", //$NON-NLS-1$ + this.getServerKey(), getLocalisedMessage(excp)); + LOGGER.error(connectionError); + + if (!silentMode) { + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(connectionError); + messageBox.open(); + } + return false; + } + return true; + } + + /** + * Проверяет включено ли использование локального RAS и запускает его. + * + * @return {@code true} если локальный RAS выключен либо включен и удачно запустился, {@code + * false} если локальный RAS включен и не удалось его запустить + */ + private boolean checkAndRunLocalRas() { + + if (!ClusterProvider.getCommonConfig().isWindows()) { + return true; + } + + if (!useLocalRas) { + return true; + } + + if (localRasV8version.isBlank() || localRasPort == 0) { + var message = + String.format( + Messages.getString("Server.LocalRasParamsIsEmpty"), //$NON-NLS-1$ + this.getServerKey()); + LOGGER.error(message); + + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(message); + messageBox.open(); + + return false; + } + + ///////////////////////////// пока только Windows + var processBuilder = new ProcessBuilder(); + var processOutput = ""; //$NON-NLS-1$ + var localRasPath = ClusterProvider.getInstalledV8Versions().get(localRasV8version); + if (localRasPath == null) { + var message = + String.format( + Messages.getString("Server.LocalRasNotFound"), this.getServerKey()); //$NON-NLS-1$ + LOGGER.error(message); + + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(message); + messageBox.open(); + + return false; + } + + Map env = processBuilder.environment(); + + env.put("RAS_PATH", localRasPath); //$NON-NLS-1$ + env.put("RAS_PORT", getLocalRasPortAsString()); //$NON-NLS-1$ + env.put("AGENT_HOST", agentHost); //$NON-NLS-1$ + env.put("AGENT_PORT", getAgentPortAsString()); //$NON-NLS-1$ + + processBuilder.command( + "cmd.exe", //$NON-NLS-1$ + "/c", //$NON-NLS-1$ + "\"%RAS_PATH%\" cluster %AGENT_HOST%:%AGENT_PORT% --port=%RAS_PORT%"); //$NON-NLS-1$ + + LOGGER.debug( + "Try launch local RAS <{}> <{} --port={}>", //$NON-NLS-1$ + localRasPath, + this.getServerKey(), + getLocalRasPortAsString()); + try { + localRasProcess = processBuilder.start(); + } catch (Exception excp) { + LOGGER.error("Error launch local RAS for server <{}>", this.getServerKey()); //$NON-NLS-1$ + LOGGER.error("Error: <{}>", processOutput, excp); //$NON-NLS-1$ + + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + + // Дочерний процесс RAS не сразу стартует и в лог о нем не попадает информация + try { + Thread.sleep(1000); + } catch (InterruptedException excp) { + LOGGER.error("Error: ", excp); //$NON-NLS-1$ + } + + LOGGER.debug("Local RAS runnung = {}", localRasProcess.isAlive()); //$NON-NLS-1$ + if (localRasProcess.isAlive()) { + LOGGER.debug("Local RAS parent CMD pid = {}", localRasProcess.pid()); //$NON-NLS-1$ + Stream ch = localRasProcess.children(); + ch.forEach( + ch1 -> { + LOGGER.debug( + "\tchildren -> {}, pid = {}", ch1.info().command().get(), ch1.pid()); //$NON-NLS-1$ + }); + + return true; + } else { + connectionError = + String.format("Local RAS <%s> is shutdown", this.getServerKey()); //$NON-NLS-1$ + LOGGER.error(connectionError); + + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(connectionError); + messageBox.open(); + + return false; + } + } + + /** + * Проверяет действительна ли еще авторизация на центральном сервере и если нет - запускает + * процесс авторизации. + * + * @param clusterId - cluster ID + * @return boolean истекла/не истекла + */ + private boolean checkAutenticateAgent() { + + var needAuthenticate = false; + try { + LOGGER.debug( + "Gets the list administrators of server <{}>:<{}>", agentHost, agentPort); //$NON-NLS-1$ + agentConnection.getAgentAdmins(); + return true; + } catch (Exception excp) { + LOGGER.error( + "Error get the list of of server administrators: <{}>", //$NON-NLS-1$ + excp.getLocalizedMessage()); + + String[] rightStrings = { // TODO проверить английские варианты + "Недостаточно прав пользователя на управление центральным сервером", + "Администратор центрального сервера не аутентифицирован", + "The user's rights to manage the central server are insufficient", + "The administrator of the central server is not authenticated" + }; + for (String rightString : rightStrings) { + if (excp.getLocalizedMessage().contains(rightString)) { + needAuthenticate = true; + break; + } + } + } + + if (needAuthenticate) { + return authenticateAgent(); + } + + return false; + } + + /** + * Establishes connection with the administration server of 1C:Enterprise server cluster. + * + * @param address - server address + * @param port - IP port + * @param timeout - connection timeout (in milliseconds) + * @throws AgentAdminException in the case of errors. + */ + public void connectToAgent(String address, int port, long timeout) { + if (isConnected()) { + LOGGER.debug( + "The connection to server <{}> is already established", //$NON-NLS-1$ + this.getServerKey()); + available = true; + return; + } + + LOGGER.debug( + "Try connect server <{}> to address:port=<{}:{}>", //$NON-NLS-1$ + this.getServerKey(), + address, + port); + + IAgentAdminConnectorFactory factory = new AgentAdminConnectorFactory(); + agentConnector = factory.createConnector(timeout); + agentConnection = agentConnector.connect(address, port); + + available = true; + connectionError = ""; //$NON-NLS-1$ + readAgentVersion(); + + LOGGER.debug("Server <{}> is connected now", this.getServerKey()); //$NON-NLS-1$ + } + + /** + * Terminates connection to the administration server. + * + * @throws AgentAdminException in the case of errors. + */ + public void disconnectFromAgent() { + if (!isConnected()) { + return; + } + + disconnectLocalRas(); + + try { + agentConnector.shutdown(); + LOGGER.info( + "Server <{}> disconnected now", //$NON-NLS-1$ + this.getServerKey()); + } catch (Exception excp) { + LOGGER.info( + "Server <{}> disconnect error: <{}>", //$NON-NLS-1$ + this.getServerKey(), + excp.getLocalizedMessage()); + } finally { + agentConnection = null; + agentConnector = null; + } + } + + private void disconnectLocalRas() { + if (useLocalRas && localRasProcess.isAlive()) { + Stream ch = localRasProcess.children(); + ch.forEach(ch1 -> ch1.destroy()); + localRasProcess.destroy(); + LOGGER.info( + "Local RAS of Server <{}> is shutdown now", //$NON-NLS-1$ + this.getServerKey()); + } + } + + /** + * Authethicates a central server administrator agent. + * + *

Need call before of regCluster, getAgentAdmins, regAgentAdmin, unregAgentAdmin + * + * @return {@code true} if authenticated, {@code false} overwise + */ + public boolean authenticateAgent() { + + if (!isConnected()) { + return false; + } + + IRunAuthenticate authMethod = + (String userName, String password, boolean saveNewUserpass) -> { + LOGGER.debug( + "Try to autenticate the agent server <{}>", //$NON-NLS-1$ + this.getServerKey()); + this.agentConnection.authenticateAgent(userName, password); + LOGGER.debug( + "Authentication to the agent server <{}> was successful", //$NON-NLS-1$ + this.getServerKey()); + + // сохраняем новые user/pass после успешной авторизации + if (saveNewUserpass) { + this.agentUserName = userName; + this.agentPassword = password; + LOGGER.debug( + "New credentials for the agent server <{}> are saved", //$NON-NLS-1$ + this.getServerKey()); + } + }; + String authDescription = + String.format( + Messages.getString("Server.AuthenticationOfCentralServerAdministrator"), //$NON-NLS-1$ + agentHost, + agentPort); + + return runAuthProcessWithRequestToUser( + authDescription, agentUserName, agentPassword, authMethod); + } + + /** + * Checks whether authentication is still valid on the cluster and if not, starts the + * authentication process. + * + * @param clusterId - cluster ID + * @return boolean valid/not valid + */ + private boolean checkAutenticateCluster(UUID clusterId) { + + var needAuthenticate = false; + try { + LOGGER.debug("Check autenticate of cluster <{}>", clusterId); //$NON-NLS-1$ + agentConnection.getClusterAdmins(clusterId); + LOGGER.debug("Autenticate succesful"); //$NON-NLS-1$ + return true; + } catch (Exception excp) { + LOGGER.error("Error autenticate of cluster: <{}>", excp.getLocalizedMessage()); //$NON-NLS-1$ + + String[] rightStrings = { // TODO проверить английские варианты + "Недостаточно прав пользователя на управление кластером", + "Администратор кластера не аутентифицирован", + "Insufficient user rights to manage the cluster", + "The cluster administrator is not authenticated" + }; + for (String rightString : rightStrings) { + if (excp.getLocalizedMessage().toLowerCase().contains(rightString.toLowerCase())) { + needAuthenticate = true; + break; + } + } + } + + if (needAuthenticate) { + return authenticateCluster(clusterId); + } + + // TODO вывести ошибку пользователю + return false; + } + + /** + * Checks whether the authentication in the infobase is still valid and if not, starts the + * authentication process. + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return boolean valid/not valid + */ + private boolean checkAutenticateInfobase(UUID clusterId, UUID infobaseId) { + + return (getInfoBaseInfo(clusterId, infobaseId) != null); + } + + /** + * Authethicates a server cluster administrator. + * + * @param clusterId - cluster ID + * @return boolean is authentication successful + */ + public boolean authenticateCluster(UUID clusterId) { + + if (!isConnected()) { + return false; + } + + IRunAuthenticate authMethod = + (String userName, String password, boolean saveNewUserpass) -> { + String clusterName = getClusterInfo(clusterId).getName(); + + LOGGER.debug( + "Try to autenticate to the cluster <{}> of server <{}>", //$NON-NLS-1$ + clusterName, + this.getServerKey()); + agentConnection.authenticate(clusterId, userName, password); + LOGGER.debug( + "Authentication to the cluster <{}> of server <{}> was successful", //$NON-NLS-1$ + clusterName, + this.getServerKey()); + + // сохраняем новые user/pass после успешной авторизации + if (this.saveCredentials && saveNewUserpass) { + this.credentialsClustersCashe.put( + clusterId, new String[] {userName, password, clusterName}); + LOGGER.debug( + "New credentials for the cluster <{}> of server <{}> are saved", //$NON-NLS-1$ + clusterName, + this.getServerKey()); + } + }; + + String[] userAndPassword = + credentialsClustersCashe.getOrDefault( + clusterId, new String[] {"", ""}); //$NON-NLS-1$ //$NON-NLS-2$ + String authDescription = + String.format( + Messages.getString("Server.AuthenticationOfClusterAdminnistrator"), //$NON-NLS-1$ + getServerKey(), + getClusterInfo(clusterId).getName()); + + return runAuthProcessWithRequestToUser( + authDescription, userAndPassword[0], userAndPassword[1], authMethod); + } + + private boolean runAuthProcessWithRequestToUser( + String authDescription, String userName, String password, IRunAuthenticate authMethod) { + try { + // Сперва пытаемся авторизоваться под сохраненной учеткой + // (она может быть инициализирована пустыми строками) + authMethod.performAutenticate(userName, password, false); + } catch (Exception excp) { + LOGGER.debug( + "Autenticate to server <{}> error: <{}>", //$NON-NLS-1$ + this.getServerKey(), + excp.getLocalizedMessage()); + + AuthenticateDialog authenticateDialog; + String authExcpMessage = excp.getLocalizedMessage(); + int dialogResult; + + // крутимся, пока не подойдет пароль, или пользователь не нажмет Отмена + while (true) { + + try { + LOGGER.debug( + "Requesting new user credentials for the server <{}>", //$NON-NLS-1$ + this.getServerKey()); + authenticateDialog = + new AuthenticateDialog( + Display.getDefault().getActiveShell(), + userName, + authDescription, + authExcpMessage); + dialogResult = authenticateDialog.open(); + } catch (Exception exc) { + LOGGER.debug( + "Request new user credentials for the server <{}> failed", //$NON-NLS-1$ + this.getServerKey()); + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(exc.getLocalizedMessage()); + messageBox.open(); + return false; + } + + if (dialogResult == 0) { + LOGGER.debug( + "The user has provided new credentials for the server <{}>", //$NON-NLS-1$ + this.getServerKey()); + userName = authenticateDialog.getUsername(); + password = authenticateDialog.getPassword(); + try { + authMethod.performAutenticate(userName, password, true); + break; + } catch (Exception exc) { + LOGGER.debug( + "Autenticate to server <{}> error: <{}>", //$NON-NLS-1$ + this.getServerKey(), + excp.getLocalizedMessage()); + authExcpMessage = exc.getLocalizedMessage(); + continue; + } + } else { + return false; + } + } + } + return true; + } + + /** + * Adds infobase authentication parameters to the context of the current administration server + * connection. + * + * @param clusterId - cluster ID + * @param userName - infobase administrator name + * @param password - infobase administrator password + */ + public void addInfobaseCredentials(UUID clusterId, String userName, String password) { + if (!isConnected()) { + return; + } + + agentConnection.addAuthentication(clusterId, userName, password); + LOGGER.debug( + "Add new infobase credentials for the cluster <{}> of server <{}>", //$NON-NLS-1$ + clusterId, + this.getServerKey()); + } + + /** + * Gets the list of cluster descriptions registered on the central server. + * + * @return list of cluster descriptions + */ + public List getClusters() { + if (!isConnected()) { + return new ArrayList<>(); + } + + LOGGER.debug( + "Get the list of cluster descriptions registered on the central server <{}>", //$NON-NLS-1$ + this.getServerKey()); + + List clusters; + try { + clusters = agentConnection.getClusters(); + } catch (Exception excp) { + LOGGER.error( + "Error get of the list of cluster descriptions", //$NON-NLS-1$ + excp); + return new ArrayList<>(); + } + + boolean needSaveConfig = false; + for (IClusterInfo cluster : clusters) { + LOGGER.debug( + "\tCluster: name=<{}>, ID=<{}>, host:port=<{}:{}>", //$NON-NLS-1$ + cluster.getName(), + cluster.getClusterId(), + cluster.getHostName(), + cluster.getMainPort()); + + // обновление имени кластера в кеше credentials + if (saveCredentials) { + String[] credentialClustersCashe = credentialsClustersCashe.get(cluster.getClusterId()); + if (credentialClustersCashe != null + && !credentialClustersCashe[2].equals(cluster.getName())) { + credentialClustersCashe[2] = cluster.getName(); + needSaveConfig = true; + } + } + } + if (needSaveConfig) { + // TODO надо сохранить + } + + return clusters; + } + + /** + * Gets the cluster descriptions. + * + * @param clusterId - cluster ID + * @return cluster - descriptions + */ + public IClusterInfo getClusterInfo(UUID clusterId) { + if (!isConnected()) { + return null; + } + + LOGGER.debug("Get the cluster <{}> descriptions", clusterId); //$NON-NLS-1$ + + IClusterInfo clusterInfo; + // TODO debug + try { + clusterInfo = agentConnection.getClusterInfo(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the cluster descriptions", excp); //$NON-NLS-1$ + return null; + } + + LOGGER.debug("Get the cluster descriptions succesful"); //$NON-NLS-1$ + return clusterInfo; + } + + /** + * Gets the list of cluster manager descriptions. + * + *

Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return cluster - list of cluster manager descriptions + */ + public List getClusterManagers(UUID clusterId) { + LOGGER.debug( + "Gets the list of cluster manager descriptions in the cluster <{}>", //$NON-NLS-1$ + clusterId); + + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List clusterManagers; + // TODO debug + try { + clusterManagers = agentConnection.getClusterManagers(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the cluster manager descriptions", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + LOGGER.debug("Get the cluster manager descriptions succesful"); //$NON-NLS-1$ + return clusterManagers; + } + + /** + * Gets a cluster manager description. + * + *

Cluster authentication is required. + * + * @param clusterId cluster ID + * @param managerId - manager ID + * @return cluster manager description, or null if the manager with the specified ID does not + * exist + */ + public IClusterManagerInfo getClusterManagerInfo(UUID clusterId, UUID managerId) { + LOGGER.debug( + "Get the cluster manager <{}> description of cluster <{}>", //$NON-NLS-1$ + managerId, + clusterId); + + if (!isConnected()) { + return null; + } + + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + IClusterManagerInfo clusterManagerInfo; + // TODO debug + try { + clusterManagerInfo = agentConnection.getClusterManagerInfo(clusterId, managerId); + } catch (Exception excp) { + LOGGER.error("Error get the cluster manager description", excp); //$NON-NLS-1$ + return null; + } + + LOGGER.debug("Get the cluster manager descriptions succesful"); //$NON-NLS-1$ + return clusterManagerInfo; + } + + /** + * Creates a cluster or changes the state of an existing one. + * + *

Central server authentication is required + * + * @param clusterInfo - cluster description + * @return {@code true} if cluster registration successful + */ + public boolean regCluster(IClusterInfo clusterInfo) { + if (clusterInfo.getClusterId().equals(emptyUuid)) { + LOGGER.debug( + "Registration new cluster <{}>", //$NON-NLS-1$ + clusterInfo.getName()); + } else { + LOGGER.debug( + "Registration changes a cluster <{}>", //$NON-NLS-1$ + clusterInfo.getClusterId()); + } + + if (!isConnected()) { + LOGGER.debug( + "The connection a cluster <{}> is not established", //$NON-NLS-1$ + clusterInfo.getClusterId()); + return false; + } + + if (!checkAutenticateAgent()) { + return false; + } + + UUID newClusterId; + try { + newClusterId = agentConnection.regCluster(clusterInfo); + } catch (Exception excp) { + LOGGER.error( + "Error registraion cluster", //$NON-NLS-1$ + excp); + return false; + } + + if (clusterInfo.getClusterId().equals(emptyUuid)) { + LOGGER.debug( + "Registration new cluster <{}> succesful", //$NON-NLS-1$ + newClusterId); + } else { + LOGGER.debug( + "Registration changes a cluster <{}> succesful", //$NON-NLS-1$ + clusterInfo.getClusterId()); + } + return true; + } + + /** + * Deletes a cluster. + * + *

Cluster authentication is required + * + * @param clusterId - cluster ID + * @return delete a cluster successful + */ + public boolean unregCluster(UUID clusterId) { + LOGGER.debug("Delete a cluster <{}>", clusterId); //$NON-NLS-1$ + + var unregSuccesful = false; + String unregMessage = null; + + if (!isConnected()) { // TODO + unregMessage = + Messages.getString("Server.TheConnectionAClusterIsNotEstablished"); //$NON-NLS-1$ + } + + if (!checkAutenticateCluster(clusterId)) { + unregMessage = Messages.getString("Server.TheClusterAuthenticationError"); //$NON-NLS-1$ + } + + try { + agentConnection.unregCluster(clusterId); + unregSuccesful = true; + } catch (Exception excp) { + LOGGER.error("Error delete a cluster", excp); //$NON-NLS-1$ + unregMessage = excp.getLocalizedMessage(); + } + if (!unregSuccesful) { + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(unregMessage); + messageBox.open(); + } + + return unregSuccesful; + } + + /** + * Gets the list of cluster administrators. + * + *

Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of cluster administrators + */ + public List getClusterAdmins(UUID clusterId) { + LOGGER.debug( + "Gets the list of cluster administrators in the cluster <{}>", //$NON-NLS-1$ + clusterId); + if (!isConnected()) { + return new ArrayList<>(); + } + + // TODO + return null; + } + + /** + * Deletes a cluster administrator. + * + *

Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param name - administrator name + */ + public void unregClusterAdmin(UUID clusterId, String name) { + LOGGER.debug( + "Deletes a cluster administrator in the cluster <{}>", //$NON-NLS-1$ + clusterId); + if (!isConnected()) { + return; + } + + // TODO + return; + } + + /** + * Gets the list of short descriptions of infobases registered in the cluster. + * + *

Cluster authentication is required + * + * @param clusterId -cluster ID + * @return list of short descriptions of cluster infobases + */ + public List getInfoBasesShort(UUID clusterId) { + LOGGER.debug( + "Get the list of short descriptions of infobases registered in the cluster <{}>", //$NON-NLS-1$ + clusterId); + + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List clusterInfoBases; + try { + clusterInfoBases = agentConnection.getInfoBasesShort(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the list of short descriptions of infobases", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + clusterInfoBases.forEach( + ib -> + LOGGER.debug( + "\tInfobase: name=<{}>, desc=<{}>", ib.getName(), ib.getDescr())); //$NON-NLS-1$ + + LOGGER.debug("Get the list of short descriptions of infobases succesful"); //$NON-NLS-1$ + return clusterInfoBases; + } + + /** + * Gets the list of full descriptions of infobases registered in the cluster. + * + *

Cluster authentication is required For each infobase in the cluster, infobase authentication + * is required If infobase authentication is not performed, only fields that correspond to short + * infobase description fields will be filled + * + * @param clusterId - cluster ID + * @return list of full descriptions of cluster infobases + */ + public List getInfoBases(UUID clusterId) { + LOGGER.debug( + "Get the list of descriptions of infobases registered in the cluster <{}>", //$NON-NLS-1$ + clusterId); + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List clusterInfoBases; + try { // TODO For each infobase in the cluster, infobase authentication is required + clusterInfoBases = agentConnection.getInfoBases(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the list of descriptions of infobases", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + clusterInfoBases.forEach( + ib -> { + LOGGER.debug( + "\tInfobase: name=<{}>, desc=<{}>", ib.getName(), ib.getDescr()); //$NON-NLS-1$ + }); + + LOGGER.debug("Get the list of descriptions of infobases succesful"); //$NON-NLS-1$ + return clusterInfoBases; + } + + /** + * Gets a short infobase description. + * + *

Cluster authentication is required + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return short infobase description + */ + public IInfoBaseInfoShort getInfoBaseShortInfo(UUID clusterId, UUID infobaseId) { + LOGGER.debug( + "Get the short description for infobase <{}> of the cluster <{}>", //$NON-NLS-1$ + infobaseId, + clusterId); + if (!isConnected()) { + return null; + } + + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + IInfoBaseInfoShort info; + try { + info = agentConnection.getInfoBaseShortInfo(clusterId, infobaseId); + } catch (Exception excp) { + LOGGER.error("Error get the short info for infobase", excp); //$NON-NLS-1$ + return null; + } + + LOGGER.debug( + "Get the short description for infobase <{}> succesful", //$NON-NLS-1$ + info.getName()); + return info; + } + + /** + * Gets the full infobase description. + * + *

Cluster authentication is required. Infobase authentication is required. + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return infobase full infobase description + */ + public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { + LOGGER.debug( + "Get the description for infobase <{}> of the cluster <{}>", //$NON-NLS-1$ + infobaseId, + clusterId); + if (!isConnected()) { + return null; + } + + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + // addInfoBaseCredentials(clusterID, "", ""); // в добавлении пустых кредов нет необходимости + + IInfoBaseInfo infobaseInfo; + + try { + infobaseInfo = agentConnection.getInfoBaseInfo(clusterId, infobaseId); + } catch (Exception excp) { + + AuthenticateDialog authenticateDialog; + String authExcpMessage = excp.getLocalizedMessage(); + int dialogResult; + + var userName = ""; //$NON-NLS-1$ + var authDescription = Messages.getString("Server.AuthenticationOfInfobase"); //$NON-NLS-1$ + + // пока не подойдет пароль, или пользователь не нажмет Отмена + while (true) { + + try { + LOGGER.debug( + "Requesting new user credentials for the infobase <{}>", //$NON-NLS-1$ + infobaseId); + authenticateDialog = + new AuthenticateDialog( + Display.getDefault().getActiveShell(), + userName, + authDescription, + authExcpMessage); + dialogResult = authenticateDialog.open(); + } catch (Exception exc) { + LOGGER.debug( + "Request new user credentials for the infobase failed: <{}>", //$NON-NLS-1$ + exc.getLocalizedMessage()); + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(exc.getLocalizedMessage()); + messageBox.open(); + return null; + } + + if (dialogResult == 0) { + LOGGER.debug( + "The user has provided new credentials for the infobase <{}>", //$NON-NLS-1$ + infobaseId); + userName = authenticateDialog.getUsername(); + String password = authenticateDialog.getPassword(); + try { + addInfobaseCredentials(clusterId, userName, password); + infobaseInfo = agentConnection.getInfoBaseInfo(clusterId, infobaseId); + break; + } catch (Exception exc) { + authExcpMessage = exc.getLocalizedMessage(); + LOGGER.debug( + "Autenticate to infobase <{}> error: <{}>", //$NON-NLS-1$ + this.getServerKey(), + authExcpMessage); + continue; + } + } else { + LOGGER.debug( + "Autenticate to infobase <{}> abort by the user", //$NON-NLS-1$ + this.getServerKey()); + return null; + } + } + } + + return infobaseInfo; + } + + /** + * Gets the infobase name. + * + *

Cluster authentication is required + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return infobase full infobase description + */ + public String getInfoBaseName(UUID clusterId, UUID infobaseId) { + LOGGER.debug( + "Get the name for infobase <{}> of the cluster <{}>", //$NON-NLS-1$ + infobaseId, + clusterId); + + if (infobaseId.equals(emptyUuid)) { + LOGGER.debug("Infobase ID is empty"); //$NON-NLS-1$ + return ""; //$NON-NLS-1$ + } + + IInfoBaseInfoShort infobaseShortInfo = getInfoBaseShortInfo(clusterId, infobaseId); + return infobaseShortInfo == null ? "" : infobaseShortInfo.getName(); //$NON-NLS-1$ + } + + /** + * Creates an infobase in a cluster. + * + *

Cluster authentication is required + * + * @param clusterId - cluster ID + * @param info - infobase parameters + * @param infobaseCreationMode - infobase creation mode: •0 - do not create a database •1 - create + * a database + * @return ID of the created infobase + */ + public UUID createInfoBase(UUID clusterId, IInfoBaseInfo info, int infobaseCreationMode) { + LOGGER.debug( + "Creates an infobase <{}> in a cluster <{}>", //$NON-NLS-1$ + info.getName(), + clusterId); - /** - * Deletes a cluster. - * Cluster authentication is required - * - * @param clusterId cluster ID - * - */ - public boolean unregCluster(UUID clusterId) { - LOGGER.debug("Delete a cluster <{}>", clusterId); //$NON-NLS-1$ - - var unregSuccesful = false; - String unregMessage = null; - - if (!isConnected()) - unregMessage = Messages.getString("Server.TheConnectionAClusterIsNotEstablished"); //$NON-NLS-1$ - - if (!checkAutenticateCluster(clusterId)) - unregMessage = Messages.getString("Server.TheClusterAuthenticationError"); //$NON-NLS-1$ - - try { - agentConnection.unregCluster(clusterId); - unregSuccesful = true; - } catch (Exception excp) { - LOGGER.error("Error delete a cluster", excp); //$NON-NLS-1$ - unregMessage = excp.getLocalizedMessage(); - } - if (!unregSuccesful) { - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(unregMessage); - messageBox.open(); - } - - return unregSuccesful; - } - - /** - * Gets the list of cluster administrators. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return list of cluster administrators - */ - public List getClusterAdmins(UUID clusterId) { - LOGGER.debug("Get the list of short descriptions of infobases registered in the cluster <{}>", clusterId); //$NON-NLS-1$ - if (!isConnected()) - return new ArrayList<>(); - - // TODO - return null; - - } - - /** - * Deletes a cluster administrator. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return list of cluster administrators - */ - public void unregClusterAdmin(UUID clusterId, String name) { - LOGGER.debug("Get the list of short descriptions of infobases registered in the cluster <{}>", clusterId); //$NON-NLS-1$ - if (!isConnected()) - return; - - // TODO - return; - - } - - /** - * Gets the list of short descriptions of infobases registered in the cluster - * Cluster authentication is required - * - * @param clusterId cluster ID - * @return list of short descriptions of cluster infobases - */ - public List getInfoBasesShort(UUID clusterId) { - LOGGER.debug("Get the list of short descriptions of infobases registered in the cluster <{}>", clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List clusterInfoBases; - try { - clusterInfoBases = agentConnection.getInfoBasesShort(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the list of short descriptions of infobases", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - clusterInfoBases.forEach(ib -> LOGGER.debug("\tInfobase: name=<{}>, desc=<{}>", ib.getName(), ib.getDescr())); //$NON-NLS-1$ - - LOGGER.debug("Get the list of short descriptions of infobases succesful"); //$NON-NLS-1$ - return clusterInfoBases; - } - - /** - * Gets the list of full descriptions of infobases registered in the cluster - * Cluster authentication is required - * For each infobase in the cluster, infobase authentication is required - * If infobase authentication is not performed, only - * fields that correspond to short infobase description fields will be filled - * - * @param clusterId cluster ID - * @return list of full descriptions of cluster infobases - */ - public List getInfoBases(UUID clusterId) { - LOGGER.debug("Get the list of descriptions of infobases registered in the cluster <{}>", clusterId); //$NON-NLS-1$ - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List clusterInfoBases; - try { // TODO For each infobase in the cluster, infobase authentication is required - clusterInfoBases = agentConnection.getInfoBases(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the list of descriptions of infobases", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - clusterInfoBases.forEach(ib -> { - LOGGER.debug("\tInfobase: name=<{}>, desc=<{}>", ib.getName(), ib.getDescr()); //$NON-NLS-1$ - }); - - LOGGER.debug("Get the list of descriptions of infobases succesful"); //$NON-NLS-1$ - return clusterInfoBases; - } - - /** - * Gets a short infobase description. - * Cluster authentication is required - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - * @return infobase full infobase description - */ - public IInfoBaseInfoShort getInfoBaseShortInfo(UUID clusterId, UUID infobaseId) { - LOGGER.debug("Get the short description for infobase <{}> of the cluster <{}>", infobaseId, clusterId); //$NON-NLS-1$ - if (!isConnected()) - return null; - - if (!checkAutenticateCluster(clusterId)) - return null; - - IInfoBaseInfoShort info; - try { - info = agentConnection.getInfoBaseShortInfo(clusterId, infobaseId); - } catch (Exception excp) { - LOGGER.error("Error get the short info for infobase", excp); //$NON-NLS-1$ - return null; - } - - LOGGER.debug("Get the short description for infobase <{}> succesful", info.getName()); //$NON-NLS-1$ - return info; - } - - /** - * Gets the full infobase description. - * Cluster authentication is required. - * Infobase authentication is required. - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - * @return infobase full infobase description - */ - public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { - LOGGER.debug("Get the description for infobase <{}> of the cluster <{}>", infobaseId, clusterId); //$NON-NLS-1$ - if (!isConnected()) - return null; - - if (!checkAutenticateCluster(clusterId)) - return null; - -// addInfoBaseCredentials(clusterID, "", ""); // в добавлении пустых кредов нет необходимости - - IInfoBaseInfo infobaseInfo; - - try { - infobaseInfo = agentConnection.getInfoBaseInfo(clusterId, infobaseId); - } catch (Exception excp) { - - AuthenticateDialog authenticateDialog; - String authExcpMessage = excp.getLocalizedMessage(); - int dialogResult; - - var userName = ""; //$NON-NLS-1$ - var authDescription = Messages.getString("Server.AuthenticationOfInfobase"); //$NON-NLS-1$ - while (true) { // пока не подойдет пароль, или пользователь не нажмет Отмена - - try { - LOGGER.debug("Requesting new user credentials for the infobase <{}>", infobaseId); //$NON-NLS-1$ - authenticateDialog = new AuthenticateDialog(Display.getDefault().getActiveShell(), userName, - authDescription, authExcpMessage); - dialogResult = authenticateDialog.open(); - } catch (Exception exc) { - LOGGER.debug("Request new user credentials for the infobase failed: <{}>", exc.getLocalizedMessage()); //$NON-NLS-1$ - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(exc.getLocalizedMessage()); - messageBox.open(); - return null; - } - - if (dialogResult == 0) { - LOGGER.debug("The user has provided new credentials for the infobase <{}>", infobaseId); //$NON-NLS-1$ - userName = authenticateDialog.getUsername(); - String password = authenticateDialog.getPassword(); - try { - addInfobaseCredentials(clusterId, userName, password); - infobaseInfo = agentConnection.getInfoBaseInfo(clusterId, infobaseId); - break; - } catch (Exception exc) { - authExcpMessage = exc.getLocalizedMessage(); - LOGGER.debug("Autenticate to infobase <{}> error: <{}>", this.getServerKey(), authExcpMessage); //$NON-NLS-1$ - continue; - } - } else { - LOGGER.debug("Autenticate to infobase <{}> abort by the user", this.getServerKey()); //$NON-NLS-1$ - return null; - } - } - } - - return infobaseInfo; - } - - /** - * Gets the infobase name. - * Cluster authentication is required - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - * @return infobase full infobase description - */ - public String getInfoBaseName(UUID clusterId, UUID infobaseId) { - LOGGER.debug("Get the name for infobase <{}> of the cluster <{}>", infobaseId, clusterId); //$NON-NLS-1$ - - if (infobaseId.equals(emptyUuid)) { - LOGGER.debug("Infobase ID is empty"); //$NON-NLS-1$ - return ""; //$NON-NLS-1$ - } - - IInfoBaseInfoShort infobaseShortInfo = getInfoBaseShortInfo(clusterId, infobaseId); - return infobaseShortInfo == null ? "" : infobaseShortInfo.getName(); //$NON-NLS-1$ - - } - - /** - * Creates an infobase in a cluster. - * Cluster authentication is required - * - * @param clusterId cluster ID - * @param info infobase parameters - */ - public UUID createInfoBase(UUID clusterId, IInfoBaseInfo info, int infobaseCreationMode) { - LOGGER.debug("Creates an infobase <{}> in a cluster <{}>", info.getName(), clusterId); //$NON-NLS-1$ - if (!isConnected()) - return emptyUuid; - - if (!checkAutenticateCluster(clusterId)) - return emptyUuid; - - UUID uuid; - try { - uuid = agentConnection.createInfoBase(clusterId, info, infobaseCreationMode); - } catch (Exception excp) { - LOGGER.error("Error creates an infobase", excp); //$NON-NLS-1$ - throw excp; - } - - LOGGER.debug("Creates an infobase succesful"); //$NON-NLS-1$ - return uuid; - } - - /** - * Changes short infobase description. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param info infobase parameters - */ - public void updateInfoBaseShort(UUID clusterId, IInfoBaseInfoShort info) { - LOGGER.debug("Changes short description infobase <{}> in the cluster <{}>", info.getInfoBaseId(), clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return; - - if (!checkAutenticateCluster(clusterId)) - return; - - try { // TODO debug - agentConnection.updateInfoBaseShort(clusterId, info); - } catch (Exception excp) { - LOGGER.error("Error changes short description infobase", excp); //$NON-NLS-1$ - throw excp; - } - } - - /** - * Changes infobase parameters. - *

    - * Infobase authentication is required - * (Здесь не нужно авторизоваться в базе, метод необходимо вызывать сразу после getInfoBaseInfo) - * - * @param clusterId cluster ID - * @param info infobase parameters - */ - public boolean updateInfoBase(UUID clusterId, IInfoBaseInfo info) { - - try { // TODO debug - agentConnection.updateInfoBase(clusterId, info); - } catch (Exception excp) { - LOGGER.error("Error changes description infobase", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - return true; - } - - /** - * Deletes an infobase. - *
      - * Infobase authentication is required - * - * @param clusterId cluster ID - * @param infobaseId infobase parameters - * @param dropMode - infobase drop mode: - *
        0 - do not delete the database - *

        1 - delete the database - *

        2 - clear the database - */ - public boolean dropInfoBase(UUID clusterId, UUID infobaseId, int dropMode) { - - if (!checkAutenticateInfobase(clusterId, infobaseId)) - return false; - - try { // TODO debug - agentConnection.dropInfoBase(clusterId, infobaseId, dropMode); - } catch (Exception excp) { - LOGGER.error("Error deletes an infobase", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - return true; - } - - /** - * Gets the list of cluster session descriptions. - * Cluster authentication is required - * - * @param clusterId cluster ID - * @return List of session descriptions - */ - public List getSessions(UUID clusterId) { - LOGGER.debug("Gets the list of cluster session descriptions in the cluster <{}>", clusterId); //$NON-NLS-1$ - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List sessions; - try { - sessions = agentConnection.getSessions(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the list of cluster session descriptions", excp); //$NON-NLS-1$ - return new ArrayList<>(); -// throw new IllegalStateException("Error get list of cluster session descriptions"); - } - sessions.forEach(s -> { - LOGGER.debug("\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ - getApplicationName(s.getAppId()), s.getSessionId()); - }); - - LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ - return sessions; - - } - - /** - * Gets a session description. - * Cluster authentication is required - * - * @param clusterId cluster ID - * @return List of session descriptions - */ - public ISessionInfo getSessionInfo(UUID clusterId, UUID sid) { - LOGGER.debug("Gets a session <{}> description in the cluster <{}>", sid, clusterId); //$NON-NLS-1$ - if (!isConnected()) - return null; - - if (!checkAutenticateCluster(clusterId)) - return null; - - ISessionInfo sessionInfo; - try { // TODO debug - sessionInfo = agentConnection.getSessionInfo(clusterId, sid); - } catch (Exception excp) { - LOGGER.error("Error get the list of cluster session descriptions", excp); //$NON-NLS-1$ - return null; -// throw new IllegalStateException("Error get list of cluster session descriptions"); - } - LOGGER.debug("\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ - getApplicationName(sessionInfo.getAppId()), sessionInfo.getSessionId()); - - LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ - return sessionInfo; - - } - - /** - * Gets the list of infobase session descriptions. - * Cluster authentication is required - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - * @return Infobase sessions - */ - public List getInfoBaseSessions(UUID clusterId, UUID infobaseId) { - LOGGER.debug("Gets the list of infobase <{}> session descriptions in the cluster <{}>", infobaseId, clusterId); //$NON-NLS-1$ - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - - List sessions; - try { - sessions = agentConnection.getInfoBaseSessions(clusterId, infobaseId); - } catch (Exception excp) { - LOGGER.error("Error get the list of infobase session descriptions", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - sessions.forEach(s -> { - LOGGER.debug("\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ - getApplicationName(s.getAppId()), s.getSessionId()); - }); - - LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ - return sessions; - - } - - public List getWorkingProcessSessions(UUID clusterId, UUID workingProcessId) { - if (isConnected()) { - List clusterSessions = agentConnection.getSessions(clusterId); - List wpSessions = new ArrayList<>(); -// clusterSessions.forEach(session -> { -// if (session.getWorkingProcessId().equals(workingProcessId)) -// wpSessions.add(session); -// }); - - wpSessions = clusterSessions - .stream() - .filter(s -> s.getWorkingProcessId().equals(workingProcessId)) - .collect(Collectors.toList()); - - return wpSessions; - } - - return new ArrayList<>(); - } - - /** - * Terminates a session in the cluster with default message. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param sessionId infobase ID - * @param message error message for user - */ - public boolean terminateSession(UUID clusterId, UUID sessionId) { - return terminateSession(clusterId, sessionId, Messages.getString("Server.TerminateSessionMessage")); //$NON-NLS-1$ - } - - /** - * Terminates a session in the cluster. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param sessionId infobase ID - * @param message error message for user - */ - public boolean terminateSession(UUID clusterId, UUID sessionId, String message) { - LOGGER.debug("Terminates a session <{}> in the cluster <{}>", sessionId, clusterId); //$NON-NLS-1$ - if (!isConnected()) - return false; - - if (!checkAutenticateCluster(clusterId)) - return false; - - try { - agentConnection.terminateSession(clusterId, sessionId, message); - } catch (Exception excp) { - LOGGER.error("Error terminate a session", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - LOGGER.debug("Terminates a session succesful"); //$NON-NLS-1$ - return true; - } - - /** - * Terminates all sessions for all infobases in the cluster - * - * @param clusterId cluster ID - */ - public void terminateAllSessions(UUID clusterId) { - - agentConnection.getSessions(clusterId) - .forEach(session -> terminateSession(clusterId, session.getSid())); - - } - - /** - * Terminates all sessions for infobase in the cluster - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - */ - public void terminateAllSessionsOfInfobase(UUID clusterId, UUID infobaseId, boolean onlyUsersSession) { - - List sessions = agentConnection.getInfoBaseSessions(clusterId, infobaseId); - for (ISessionInfo session : sessions) { - if (onlyUsersSession && !isUserSession(session)) - continue; - - agentConnection.terminateSession(clusterId, session.getSid()); - } - } - - private boolean isUserSession(ISessionInfo session) { - String appName = session.getAppId(); - return appName.equals(THIN_CLIENT) || appName.equals(THICK_CLIENT); - } - - /** - * Gets the list of short descriptions of cluster connections. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getConnectionsShort(UUID clusterId) { - if (isConnected()) - return agentConnection.getConnectionsShort(clusterId); - // TODO - return new ArrayList<>(); - } - - /** - * Gets a short description of a connection. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param connectionId connection ID - * @return short connection description - */ - public IInfoBaseConnectionShort getConnectionInfoShort(UUID clusterId, UUID connectionId) { - if (isConnected()) - return agentConnection.getConnectionInfoShort(clusterId, connectionId); - // TODO - return null; - } - - /** - * Gets the list of short descriptions of infobase connections. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param infobaseId infobase ID - * @return list of short infobase connection descriptions - */ - public List getInfoBaseConnectionsShort(UUID clusterId, UUID infobaseId) { - if (isConnected()) - return agentConnection.getInfoBaseConnectionsShort(clusterId, infobaseId); - // TODO - return new ArrayList<>(); - } - - /** - * Gets the list of infobase connection descriptions for a working process. - * Cluster authentication is required. - * Infobase authentication is required. - * - * @param clusterId cluster ID - * @param processId process ID - * @param infobaseId infobase ID - * @return list of infobase connection descriptions - */ - public List getInfoBaseConnections(UUID clusterId, UUID processId, UUID infobaseId) { - if (isConnected()) - return agentConnection.getInfoBaseConnections(clusterId, processId, infobaseId); - // TODO - return new ArrayList<>(); - } - - /** - * Closes an infobase connection. - * Cluster authentication is required. - * Infobase authentication is required. - * - * @param clusterId cluster ID - * @param processId working process ID - * @param connectionId connection ID - */ - public boolean disconnectConnection(UUID clusterId, UUID processId, UUID connectionId, UUID infobaseId) { - LOGGER.debug("Close connection in the cluster <{}>, processId <{}>, connectionId <{}>", //$NON-NLS-1$ - clusterId, processId, connectionId); - - if (!isConnected()) - return false; - - if (!checkAutenticateCluster(clusterId)) - return false; - - if (!checkAutenticateInfobase(clusterId, infobaseId)) - return false; - - - try { - agentConnection.disconnect(clusterId, processId, connectionId); - } catch (Exception excp) { - LOGGER.error("Error close connection", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - LOGGER.debug("Close connection succesful"); //$NON-NLS-1$ - return true; - } - - /** - * Interrupt current server call. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param processId working process ID - * @param connectionId connection ID - * @return infobase full infobase description - */ - public void interruptCurrentServerCall(UUID clusterId, UUID sid, String message) { - if (isConnected()) - agentConnection.interruptCurrentServerCall(clusterId, sid, message); - // TODO - } - - public List getWorkingProcessConnectionsShort(UUID clusterId, UUID workingProcessId) { - if (isConnected()) { - - return agentConnection.getConnectionsShort(clusterId) - .stream() - .filter(c -> c.getWorkingProcessId().equals(workingProcessId)) - .collect(Collectors.toList()); - - } - - return new ArrayList<>(); - } - - /** - * Gets the list of object locks. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getLocks(UUID clusterId) { - LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List locks; - try { // TODO debug - locks = agentConnection.getLocks(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - return locks; - } - - /** - * Gets the list of infobase object locks. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getInfoBaseLocks(UUID clusterId, UUID infobaseId) { - LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List locks; - try { // TODO debug - locks = agentConnection.getInfoBaseLocks(clusterId, infobaseId); - } catch (Exception excp) { - LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - return locks; - } - - /** - * Gets the list of connection object locks. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getConnectionLocks(UUID clusterId, UUID connectionId) { - LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List locks; - try { // TODO debug - locks = agentConnection.getConnectionLocks(clusterId, connectionId); - } catch (Exception excp) { - LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - return locks; - } - - /** - * Gets the list of session object locks. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getSessionLocks(UUID clusterId, UUID infobaseId, UUID sid) { - LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List locks; - try { // TODO debug - locks = agentConnection.getSessionLocks(clusterId, infobaseId, sid); - } catch (Exception excp) { - LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ - return new ArrayList<>(); - } - - return locks; - } - - /** - * Gets the list of descriptions of working processes registered in the cluster. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getWorkingProcesses(UUID clusterId) { - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List workingProcesses; - try { // TODO debug - LOGGER.debug("Gets the list of descriptions of working processes registered in the cluster <{}>", clusterId); //$NON-NLS-1$ - workingProcesses = agentConnection.getWorkingProcesses(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the list of short descriptions of working processes", excp); //$NON-NLS-1$ - throw new IllegalStateException("Error get working processes"); //$NON-NLS-1$ - } - workingProcesses.forEach(wp -> { - LOGGER.debug("\tWorking process: host name=<{}>, main port=<{}>", //$NON-NLS-1$ - wp.getHostName(), wp.getMainPort()); - }); - - LOGGER.debug("Get the list of short descriptions of working processes succesful"); //$NON-NLS-1$ - return workingProcesses; - } - - /** - * Gets a working process description. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public IWorkingProcessInfo getWorkingProcessInfo(UUID clusterId, UUID processId) { - LOGGER.debug("Gets a working process <{}> description in the cluster <{}>", processId, clusterId); //$NON-NLS-1$ - - if (!isConnected()) - return null; - - if (!checkAutenticateCluster(clusterId)) - return null; - - IWorkingProcessInfo workingProcessInfo; - try { - workingProcessInfo = agentConnection.getWorkingProcessInfo(clusterId, processId); - } catch (Exception excp) { - LOGGER.error("Error get a working process description", excp); //$NON-NLS-1$ - return null; - } - - return workingProcessInfo; - } - - /** - * Gets the list of descriptions of working processes of a working server. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getServerWorkingProcesses(UUID clusterId, UUID serverId) { - if (isConnected()) - return agentConnection.getServerWorkingProcesses(clusterId, serverId); - // TODO - return new ArrayList<>(); - } - - /** - * Gets the list of descriptions of working servers registered in the cluster. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public List getWorkingServers(UUID clusterId) { - if (!isConnected()) - return new ArrayList<>(); - - if (!checkAutenticateCluster(clusterId)) - return new ArrayList<>(); - - List workingServers; - try { // TODO debug - LOGGER.debug("Gets the list of descriptions of working servers registered in the cluster <{}>", clusterId); //$NON-NLS-1$ - workingServers = agentConnection.getWorkingServers(clusterId); - } catch (Exception excp) { - LOGGER.error("Error get the list of descriptions of working servers", excp); //$NON-NLS-1$ - throw new IllegalStateException("Error get working servers"); //$NON-NLS-1$ - } - workingServers.forEach(ws -> { - LOGGER.debug("\tWorking server: host name=<{}>, main port=<{}>", //$NON-NLS-1$ - ws.getHostName(), ws.getMainPort()); - }); - - LOGGER.debug("Get the list of descriptions of working servers succesful"); //$NON-NLS-1$ - return workingServers; - } - - /** - * Gets a description of a working server registered in the cluster. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public IWorkingServerInfo getWorkingServerInfo(UUID clusterId, UUID serverId) { - if (!isConnected()) - return null; - - if (!checkAutenticateCluster(clusterId)) - return null; - - IWorkingServerInfo workingServerInfo; - try { // TODO debug - LOGGER.debug("Gets the description of working server <{}> registered in the cluster <{}>", serverId, clusterId); //$NON-NLS-1$ - workingServerInfo = agentConnection.getWorkingServerInfo(clusterId, serverId); - } catch (Exception excp) { - LOGGER.error("Error get the list of descriptions of working server", excp); //$NON-NLS-1$ - throw new IllegalStateException("Error get working server"); //$NON-NLS-1$ - } - - LOGGER.debug("\tWorking server: host name=<{}>, main port=<{}>", //$NON-NLS-1$ - workingServerInfo.getHostName(), workingServerInfo.getMainPort()); - - LOGGER.debug("Get the list of short descriptions of working processes succesful"); //$NON-NLS-1$ - return workingServerInfo; - } - - /** - * Creates a working server or changes the description of an existing one. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @return infobase full infobase description - */ - public boolean regWorkingServer(UUID clusterId, IWorkingServerInfo serverInfo, boolean createNew) { - if (!isConnected()) - return false; - - if (!checkAutenticateCluster(clusterId)) - return false; - - if (createNew) - LOGGER.debug("Registration NEW working server"); //$NON-NLS-1$ - - try { // TODO debug - LOGGER.debug("Registration working server <{}> registered in the cluster <{}>", serverInfo.getName(), clusterId); //$NON-NLS-1$ - agentConnection.regWorkingServer(clusterId, serverInfo); - } catch (Exception excp) { - LOGGER.error("Error registration working server", excp); //$NON-NLS-1$ - throw excp; - } - - LOGGER.debug("\tRegistration working server: name=<{}>, host name=<{}>, main port=<{}>", //$NON-NLS-1$ - serverInfo.getName(), serverInfo.getHostName(), serverInfo.getMainPort()); - - LOGGER.debug("Registration working server succesful"); //$NON-NLS-1$ - return true; - } - - /** - * Deletes a working server and removes its cluster registration. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public boolean unregWorkingServer(UUID clusterId, UUID serverId) { - if (!isConnected()) - return false; - - if (!checkAutenticateCluster(clusterId)) - return false; - - try { // TODO debug - LOGGER.debug("Deletes a working server <{}> from the cluster <{}>", serverId, clusterId); //$NON-NLS-1$ - agentConnection.unregWorkingServer(clusterId, serverId); - } catch (Exception excp) { - LOGGER.error("Error registration working server", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - - LOGGER.debug("Unregistration working server succesful"); //$NON-NLS-1$ - return true; - } - - /** - * Gets the list of cluster service descriptions. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getClusterServices(UUID clusterId) { - return null; //TODO - - } - - /** - * Applies assignment rules. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void applyAssignmentRules(UUID clusterId, int full) { - return; //TODO - } - - /** - * Gets the list of descriptions of working server assignment rules. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getAssignmentRules(UUID clusterId, UUID serverId) { - return null; //TODO - } - - /** - * Creates an assignment rule, changes an existing one, or moves an existing rule to a new position. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public UUID regAssignmentRule(UUID clusterId, UUID serverId, IAssignmentRuleInfo info, int position) { - return null; //TODO - } - - /** - * Deletes an assignment rule from the list of working server rules. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void unregAssignmentRule(UUID clusterId, UUID serverId, UUID ruleId) { - return; //TODO - } - - /** - * Gets an assignment rule description. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public IAssignmentRuleInfo getAssignmentRuleInfo(UUID clusterId, UUID serverId, UUID ruleId) { - return null; //TODO - } - - /** - * Gets the list of cluster security profiles. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfiles(UUID clusterId) { - return null; //TODO - } - - /** - * Creates or updates a cluster security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfile(UUID clusterId, ISecurityProfile profile) { - return; //TODO - } - - /** - * Deletes a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfile(UUID clusterId, String spName) { - return; //TODO - } - - /** - * Gets the list of virtual directories of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfileVirtualDirectories(UUID clusterId, String spName) { - return null; //TODO - } - - /** - * Creates or updates a virtual directory of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfileVirtualDirectory(UUID clusterId, ISecurityProfileVirtualDirectory directory) { - return; //TODO - } - - /** - * Deletes a virtual directory of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfileVirtualDirectory(UUID clusterId, String spName, String alias) { - return; //TODO - } - - - /** - * Gets the list of allowed COM classes of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfileComClasses(UUID clusterId, String spName) { - return null; //TODO - } - - /** - * Creates or updates an allowed COM class of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfileComClass(UUID clusterId, ISecurityProfileCOMClass comClass) { - return; //TODO - } - - /** - * Deletes an allowed COM class of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfileComClass(UUID clusterId, String spName, String name) { - return; //TODO - } - - /** - * Gets the list of allowed add-ins of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfileAddIns(UUID clusterId, String spName) { - return null; //TODO - } - - /** - * Creates or updates an allowed add-in of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfileAddIn(UUID clusterId, ISecurityProfileAddIn addIn) { - return; //TODO - } - - /** - * Deletes an allowed add-in of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfileAddIn(UUID clusterId, String spName, String name) { - return; //TODO - } - - /** - * Gets the list of allowed unsafe external modules of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfileUnsafeExternalModules(UUID clusterId, String spName) { - return null; //TODO - } - - /** - * Creates or updates an allowed unsafe external module of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfileUnsafeExternalModule(UUID clusterId, ISecurityProfileExternalModule module) { - return; //TODO - } - - /** - * Deletes an allowed unsafe external module of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfileUnsafeExternalModule(UUID clusterId, String spName, String name) { - return; //TODO - } - - /** - * Gets the list of allowed applications of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfileApplications(UUID clusterId, String spName) { - return null; //TODO - } - - /** - * Creates or updates an allowed application of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfileApplication(UUID clusterId, ISecurityProfileApplication app) { - return; //TODO - } - - /** - * Deletes an allowed application of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfileApplication(UUID clusterId, String spName, String name) { - return; //TODO - } - - /** - * Gets the list of Internet resources of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getSecurityProfileInternetResources(UUID clusterId, String spName) { - return null; //TODO - } - - /** - * Creates or updates an Internet resource of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void createSecurityProfileInternetResource(UUID clusterId, ISecurityProfileInternetResource resource) { - return; //TODO - } - - /** - * Deletes an Internet resource of a security profile. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void dropSecurityProfileInternetResource(UUID clusterId, String spName, String name) { - return; //TODO - } - - /** - * Gets the list of resource counters. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getResourceConsumptionCounters(UUID clusterId) { - return null; //TODO - } - - /** - * Gets resource counters description. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public IResourceConsumptionCounter getResourceConsumptionCounterInfo(UUID clusterId, String counterName) { - return null; //TODO - } - - /** - * Creates or updates a resource counter. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void regResourceConsumptionCounter(UUID clusterId, IResourceConsumptionCounter counter) { - return; //TODO - } - - /** - * Deletes a resource counter - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void unregResourceConsumptionCounter(UUID clusterId, String counterName) { - return; //TODO - } - - /** - * Gets the list of resource limits. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public List getResourceConsumptionLimits(UUID clusterId) { - return null; //TODO - } - - /** - * Gets resource limits description - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public IResourceConsumptionLimit getResourceConsumptionLimitInfo(UUID clusterId, String limitName) { - return null; //TODO - } - - /** - * Creates or updates a resource limit. - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param serverId server ID - * @return infobase full infobase description - */ - public void regResourceConsumptionLimit(UUID clusterId, IResourceConsumptionLimit limit) { - return; //TODO - } - - /** - * Deletes a resource limits - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param limitName limit name - */ - public void unregResourceConsumptionLimit(UUID clusterId, String limitName) { - return; //TODO - } - - /** - * Gets the list of resource counter values - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param counterName counterName - * @param object object - * @return list of resource counter values - */ - public List getResourceConsumptionCounterValues(UUID clusterId, String counterName, String object) { - return null; //TODO - } - - /** - * Deletes a resource counter values - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param counterName counterName - * @param object object - */ - public void clearResourceConsumptionCounterAccumulatedValues(UUID clusterId, String counterName, String object) { - return; //TODO - } - - /** - * Gets the list of resource counter accumulated values - * Cluster authentication is required. - * - * @param clusterId cluster ID - * @param counterName counterName - * @param object object - * @return ist of resource counter accumulated values - */ - public List getResourceConsumptionCounterAccumulatedValues(UUID clusterId, String counterName, String object) { - return null; //TODO - } - - - - - - - - - - + if (!isConnected()) { + return emptyUuid; + } + if (!checkAutenticateCluster(clusterId)) { + return emptyUuid; + } + + UUID uuid; + try { + uuid = agentConnection.createInfoBase(clusterId, info, infobaseCreationMode); + } catch (Exception excp) { + LOGGER.error("Error creates an infobase", excp); //$NON-NLS-1$ + throw excp; + } + + LOGGER.debug("Creates an infobase succesful"); //$NON-NLS-1$ + return uuid; + } + + /** + * Changes short infobase description. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param info - infobase parameters + */ + public void updateInfoBaseShort(UUID clusterId, IInfoBaseInfoShort info) { + LOGGER.debug( + "Changes short description infobase <{}> in the cluster <{}>", //$NON-NLS-1$ + info.getInfoBaseId(), + clusterId); + + if (!isConnected()) { + return; + } + if (!checkAutenticateCluster(clusterId)) { + return; + } + + try { // TODO debug + agentConnection.updateInfoBaseShort(clusterId, info); + } catch (Exception excp) { + LOGGER.error("Error changes short description infobase", excp); //$NON-NLS-1$ + return; + } + } + + /** + * Changes infobase parameters. + * + *

        Infobase authentication is required (Здесь не нужно авторизоваться в базе, метод необходимо + * вызывать сразу после getInfoBaseInfo) + * + * @param clusterId - cluster ID + * @param info - infobase parameters + * @return {@code true} if update succesful + */ + public boolean updateInfoBase(UUID clusterId, IInfoBaseInfo info) { + + try { // TODO debug + agentConnection.updateInfoBase(clusterId, info); + } catch (Exception excp) { + LOGGER.error("Error changes description infobase", excp); //$NON-NLS-1$ + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + return true; + } + + /** + * Deletes an infobase. + * + *

        Infobase authentication is required + * + * @param clusterId - cluster ID + * @param infobaseId - infobase parameters + * @param dropMode - infobase drop mode: 0 - do not delete the database 1 - delete the database 2 + * - clear the database + * @return {@code true} if drop succesful + */ + public boolean dropInfoBase(UUID clusterId, UUID infobaseId, int dropMode) { + + if (!checkAutenticateInfobase(clusterId, infobaseId)) { + return false; + } + + try { // TODO debug + agentConnection.dropInfoBase(clusterId, infobaseId, dropMode); + } catch (Exception excp) { + LOGGER.error("Error deletes an infobase", excp); //$NON-NLS-1$ + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + return true; + } + + /** + * Gets the list of cluster session descriptions. + * + *

        Cluster authentication is required + * + * @param clusterId - cluster ID + * @return List of session descriptions + */ + public List getSessions(UUID clusterId) { + LOGGER.debug( + "Gets the list of cluster session descriptions in the cluster <{}>", //$NON-NLS-1$ + clusterId); + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List sessions; + try { + sessions = agentConnection.getSessions(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the list of cluster session descriptions", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + sessions.forEach( + s -> { + LOGGER.debug( + "\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ + getApplicationName(s.getAppId()), + s.getSessionId()); + }); + + LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ + return sessions; + } + + /** + * Gets a session description. + * + *

        Cluster authentication is required + * + * @param clusterId - cluster ID + * @param sid - session ID + * @return session description + */ + public ISessionInfo getSessionInfo(UUID clusterId, UUID sid) { + LOGGER.debug( + "Gets a session <{}> description in the cluster <{}>", sid, clusterId); //$NON-NLS-1$ + if (!isConnected()) { + return null; + } + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + ISessionInfo sessionInfo; + try { // TODO debug + sessionInfo = agentConnection.getSessionInfo(clusterId, sid); + } catch (Exception excp) { + LOGGER.error("Error get the list of cluster session descriptions", excp); //$NON-NLS-1$ + return null; + } + LOGGER.debug( + "\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ + getApplicationName(sessionInfo.getAppId()), + sessionInfo.getSessionId()); + + LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ + return sessionInfo; + } + + /** + * Gets the list of infobase session descriptions. + * + *

        Cluster authentication is required + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return Infobase sessions + */ + public List getInfoBaseSessions(UUID clusterId, UUID infobaseId) { + LOGGER.debug( + "Gets the list of infobase <{}> session descriptions in the cluster <{}>", //$NON-NLS-1$ + infobaseId, + clusterId); + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List sessions; + try { + sessions = agentConnection.getInfoBaseSessions(clusterId, infobaseId); + } catch (Exception excp) { + LOGGER.error("Error get the list of infobase session descriptions", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + sessions.forEach( + s -> { + LOGGER.debug( + "\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ + getApplicationName(s.getAppId()), + s.getSessionId()); + }); + + LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ + return sessions; + } + + /** + * Gets the list of infobase session descriptions. + * + *

        Cluster authentication is required + * + * @param clusterId - cluster ID + * @param workingProcessId - Working process ID + * @return Working process sessions + */ + public List getWorkingProcessSessions(UUID clusterId, UUID workingProcessId) { + + return getSessions(clusterId).stream() + .filter(s -> s.getWorkingProcessId().equals(workingProcessId)) + .collect(Collectors.toList()); + } + + /** + * Terminates a session in the cluster with default message. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param sessionId - infobase ID + * @return sucess terminate session + */ + public boolean terminateSession(UUID clusterId, UUID sessionId) { + return terminateSession( + clusterId, sessionId, Messages.getString("Server.TerminateSessionMessage")); //$NON-NLS-1$ + } + + /** + * Terminates a session in the cluster. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param sessionId - infobase ID + * @param message - error message for user + * @return sucess terminate session + */ + public boolean terminateSession(UUID clusterId, UUID sessionId, String message) { + LOGGER.debug( + "Terminates a session <{}> in the cluster <{}>", //$NON-NLS-1$ + sessionId, + clusterId); + if (!isConnected()) { + return false; + } + + if (!checkAutenticateCluster(clusterId)) { + return false; + } + + try { + agentConnection.terminateSession(clusterId, sessionId, message); + } catch (Exception excp) { + LOGGER.error("Error terminate a session", excp); //$NON-NLS-1$ + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + LOGGER.debug("Terminates a session succesful"); //$NON-NLS-1$ + return true; + } + + /** + * Terminates all sessions for all infobases in the cluster. + * + * @param clusterId - cluster ID + */ + public void terminateAllSessions(UUID clusterId) { + + getSessions(clusterId).forEach(session -> terminateSession(clusterId, session.getSid())); + } + + /** + * Terminates all sessions for infobase in the cluster. + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @param onlyUsersSession - terminate only users sessions + */ + public void terminateAllSessionsOfInfobase( + UUID clusterId, UUID infobaseId, boolean onlyUsersSession) { + + List sessions = agentConnection.getInfoBaseSessions(clusterId, infobaseId); + for (ISessionInfo session : sessions) { + if (onlyUsersSession && !isUserSession(session)) { + continue; + } + + terminateSession(clusterId, session.getSid()); + } + } + + private boolean isUserSession(ISessionInfo session) { + String appName = session.getAppId(); + return appName.equals(THIN_CLIENT) || appName.equals(THICK_CLIENT); + } + + /** + * Gets the list of short descriptions of cluster connections. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of short cluster connection descriptions + */ + public List getConnectionsShort(UUID clusterId) { + if (isConnected()) { + return agentConnection.getConnectionsShort(clusterId); + } + // TODO + return new ArrayList<>(); + } + + /** + * Gets a short description of a connection. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param connectionId - connection ID + * @return short connection description + */ + public IInfoBaseConnectionShort getConnectionInfoShort(UUID clusterId, UUID connectionId) { + if (isConnected()) { + return agentConnection.getConnectionInfoShort(clusterId, connectionId); + } + // TODO + return null; + } + + /** + * Gets the list of short descriptions of infobase connections. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return list of short infobase connection descriptions + */ + public List getInfoBaseConnectionsShort( + UUID clusterId, UUID infobaseId) { + if (isConnected()) { + return agentConnection.getInfoBaseConnectionsShort(clusterId, infobaseId); + } + // TODO + return new ArrayList<>(); + } + + /** + * Gets the list of infobase connection descriptions for a working process. + * + *

        Cluster authentication is required. Infobase authentication is required. + * + * @param clusterId - cluster ID + * @param workingProcessId - working process ID + * @param infobaseId - infobase ID + * @return list of infobase connection descriptions + */ + public List getInfoBaseConnections( + UUID clusterId, UUID workingProcessId, UUID infobaseId) { + if (isConnected()) { + return agentConnection.getInfoBaseConnections(clusterId, workingProcessId, infobaseId); + } + // TODO + return new ArrayList<>(); + } + + /** + * Gets the list of connection descriptions for a working process. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param workingProcessId - working process ID + * @return list of connection descriptions for a working process + */ + public List getWorkingProcessConnectionsShort( + UUID clusterId, UUID workingProcessId) { + if (isConnected()) { + + return agentConnection.getConnectionsShort(clusterId).stream() + .filter(c -> c.getWorkingProcessId().equals(workingProcessId)) + .collect(Collectors.toList()); + } + + return new ArrayList<>(); + } + + /** + * Closes an infobase connection. + * + *

        Cluster authentication is required. Infobase authentication is required. + * + * @param clusterId - cluster ID + * @param processId - working process ID + * @param connectionId - connection ID + * @param infobaseId - infobase ID + * @return {@code true} if successful shutdown + */ + public boolean disconnectConnection( + UUID clusterId, UUID processId, UUID connectionId, UUID infobaseId) { + LOGGER.debug( + "Close connection in the cluster <{}>, processId <{}>, connectionId <{}>", //$NON-NLS-1$ + clusterId, + processId, + connectionId); + + if (!isConnected()) { + return false; + } + if (!checkAutenticateCluster(clusterId)) { + return false; + } + if (!checkAutenticateInfobase(clusterId, infobaseId)) { + return false; + } + + try { + agentConnection.disconnect(clusterId, processId, connectionId); + } catch (Exception excp) { + LOGGER.error("Error close connection", excp); //$NON-NLS-1$ + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + LOGGER.debug("Close connection succesful"); //$NON-NLS-1$ + return true; + } + + /** + * Interrupt current server call. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param sid - session ID + * @param message - interrupt message + */ + public void interruptCurrentServerCall(UUID clusterId, UUID sid, String message) { + if (isConnected()) { + agentConnection.interruptCurrentServerCall(clusterId, sid, message); + } + // TODO + } + + /** + * Gets the list of object locks. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of object lock descriptions + */ + public List getLocks(UUID clusterId) { + LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ + + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List locks; + try { // TODO debug + locks = agentConnection.getLocks(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return locks; + } + + /** + * Gets the list of infobase object locks. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @return list of object lock descriptions + */ + public List getInfoBaseLocks(UUID clusterId, UUID infobaseId) { + LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ + + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List locks; + try { // TODO debug + locks = agentConnection.getInfoBaseLocks(clusterId, infobaseId); + } catch (Exception excp) { + LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return locks; + } + + /** + * Gets the list of connection object locks. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param connectionId - connection ID + * @return list of object lock descriptions + */ + public List getConnectionLocks(UUID clusterId, UUID connectionId) { + LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ + + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List locks; + try { // TODO debug + locks = agentConnection.getConnectionLocks(clusterId, connectionId); + } catch (Exception excp) { + LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return locks; + } + + /** + * Gets the list of session object locks. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @param sid - session ID + * @return list of object lock descriptions + */ + public List getSessionLocks(UUID clusterId, UUID infobaseId, UUID sid) { + LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ + + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List locks; + try { // TODO debug + locks = agentConnection.getSessionLocks(clusterId, infobaseId, sid); + } catch (Exception excp) { + LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return locks; + } + + /** + * Gets the list of descriptions of working processes registered in the cluster. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of working processes descriptions + */ + public List getWorkingProcesses(UUID clusterId) { + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List workingProcesses; + try { // TODO debug + LOGGER.debug( + "Gets the list of descriptions of working processes in the cluster <{}>", //$NON-NLS-1$ + clusterId); + workingProcesses = agentConnection.getWorkingProcesses(clusterId); + } catch (Exception excp) { + LOGGER.error( + "Error get the list of short descriptions of working processes", //$NON-NLS-1$ + excp); + return new ArrayList<>(); + } + workingProcesses.forEach( + wp -> { + LOGGER.debug( + "\tWorking process: host name=<{}>, main port=<{}>", //$NON-NLS-1$ + wp.getHostName(), + wp.getMainPort()); + }); + + LOGGER.debug( + "Get the list of short descriptions of working processes succesful"); //$NON-NLS-1$ + return workingProcesses; + } + + /** + * Gets a working process description. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param processId - working process ID + * @return working process description, or null if the working process with the specified ID does + * not exist + */ + public IWorkingProcessInfo getWorkingProcessInfo(UUID clusterId, UUID processId) { + LOGGER.debug( + "Gets a working process <{}> description in the cluster <{}>", //$NON-NLS-1$ + processId, + clusterId); + + if (!isConnected()) { + return null; + } + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + IWorkingProcessInfo workingProcessInfo; + try { + workingProcessInfo = agentConnection.getWorkingProcessInfo(clusterId, processId); + } catch (Exception excp) { + LOGGER.error("Error get a working process description", excp); //$NON-NLS-1$ + return null; + } + + return workingProcessInfo; + } + + /** + * Gets the list of descriptions of working processes of a working server. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - working server ID + * @return list of working process descriptions + */ + public List getServerWorkingProcesses(UUID clusterId, UUID serverId) { + if (isConnected()) { + return agentConnection.getServerWorkingProcesses(clusterId, serverId); + } + // TODO + return new ArrayList<>(); + } + + /** + * Gets the list of descriptions of working servers registered in the cluster. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of working server descriptions + */ + public List getWorkingServers(UUID clusterId) { + if (!isConnected()) { + return new ArrayList<>(); + } + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List workingServers; + try { // TODO debug + LOGGER.debug( + "Gets the list of descriptions of working servers in the cluster <{}>", //$NON-NLS-1$ + clusterId); + workingServers = agentConnection.getWorkingServers(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the list of descriptions of working servers", excp); //$NON-NLS-1$ + throw new IllegalStateException("Error get working servers"); //$NON-NLS-1$ + } + workingServers.forEach( + ws -> { + LOGGER.debug( + "\tWorking server: host name=<{}>, main port=<{}>", //$NON-NLS-1$ + ws.getHostName(), + ws.getMainPort()); + }); + + LOGGER.debug("Get the list of descriptions of working servers succesful"); //$NON-NLS-1$ + return workingServers; + } + + /** + * Gets a description of a working server registered in the cluster. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - server ID + * @return working server description, or null if the working server with the specified ID does + * not exist + */ + public IWorkingServerInfo getWorkingServerInfo(UUID clusterId, UUID serverId) { + if (!isConnected()) { + return null; + } + + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + IWorkingServerInfo workingServerInfo; + try { // TODO debug + LOGGER.debug( + "Gets the description of working server <{}> in the cluster <{}>", //$NON-NLS-1$ + serverId, + clusterId); + workingServerInfo = agentConnection.getWorkingServerInfo(clusterId, serverId); + } catch (Exception excp) { + LOGGER.error("Error get the list of descriptions of working server", excp); //$NON-NLS-1$ + throw new IllegalStateException("Error get working server"); //$NON-NLS-1$ + } + + LOGGER.debug( + "\tWorking server: host name=<{}>, main port=<{}>", //$NON-NLS-1$ + workingServerInfo.getHostName(), + workingServerInfo.getMainPort()); + + LOGGER.debug( + "Get the list of short descriptions of working processes succesful"); //$NON-NLS-1$ + return workingServerInfo; + } + + /** + * Creates a working server or changes the description of an existing one. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverInfo - working server description + * @param createNew - if create new working server + * @return {@code true} if succes reg working server + */ + public boolean regWorkingServer( + UUID clusterId, IWorkingServerInfo serverInfo, boolean createNew) { + if (!isConnected()) { + return false; + } + + if (!checkAutenticateCluster(clusterId)) { + return false; + } + + if (createNew) { + LOGGER.debug("Registration NEW working server"); //$NON-NLS-1$ + } + + try { // TODO debug + LOGGER.debug( + "Registration working server <{}> registered in the cluster <{}>", //$NON-NLS-1$ + serverInfo.getName(), + clusterId); + agentConnection.regWorkingServer(clusterId, serverInfo); + } catch (Exception excp) { + LOGGER.error("Error registration working server", excp); //$NON-NLS-1$ + return false; + } + + LOGGER.debug( + "\tRegistration working server: name=<{}>, host name=<{}>, main port=<{}>", //$NON-NLS-1$ + serverInfo.getName(), + serverInfo.getHostName(), + serverInfo.getMainPort()); + + LOGGER.debug("Registration working server succesful"); //$NON-NLS-1$ + return true; + } + + /** + * Deletes a working server and removes its cluster registration. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - server ID + * @return infobase full infobase description + */ + public boolean unregWorkingServer(UUID clusterId, UUID serverId) { + if (!isConnected()) { + return false; + } + + if (!checkAutenticateCluster(clusterId)) { + return false; + } + + try { // TODO debug + LOGGER.debug( + "Deletes a working server <{}> from the cluster <{}>", //$NON-NLS-1$ + serverId, + clusterId); + agentConnection.unregWorkingServer(clusterId, serverId); + } catch (Exception excp) { + LOGGER.error("Error registration working server", excp); //$NON-NLS-1$ + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + + LOGGER.debug("Unregistration working server succesful"); //$NON-NLS-1$ + return true; + } + + /** + * Gets the list of cluster service descriptions. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of cluster service descriptions + */ + public List getClusterServices(UUID clusterId) { + // TODO + return agentConnection.getClusterServices(clusterId); + } + + /** + * Applies assignment rules. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param full - assigment rule application mode: 0 - partial 1 - full + */ + public void applyAssignmentRules(UUID clusterId, int full) { + // TODO + agentConnection.applyAssignmentRules(clusterId, full); + } + + /** + * Gets the list of descriptions of working server assignment rules. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - server ID + * @return infobase full infobase description + */ + public List getAssignmentRules(UUID clusterId, UUID serverId) { + // TODO + return agentConnection.getAssignmentRules(clusterId, serverId); + } + + /** + * Creates an assignment rule, changes an existing one, or moves an existing rule to a new + * position. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - server ID + * @param info - assignment rule description + * @param position - position in the rule list (starts from 0) + * @return ID of the created rule, or null if an existing assignment rule was changed + */ + public UUID regAssignmentRule( + UUID clusterId, UUID serverId, IAssignmentRuleInfo info, int position) { + // TODO + return agentConnection.regAssignmentRule(clusterId, serverId, info, position); + } + + /** + * Deletes an assignment rule from the list of working server rules. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - working server ID + * @param ruleId - assignment rule ID + */ + public void unregAssignmentRule(UUID clusterId, UUID serverId, UUID ruleId) { + // TODO + agentConnection.unregAssignmentRule(clusterId, serverId, ruleId); + } + + /** + * Gets an assignment rule description. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param serverId - server ID + * @param ruleId - assignment rule ID + * @return assignment rule description + */ + public IAssignmentRuleInfo getAssignmentRuleInfo(UUID clusterId, UUID serverId, UUID ruleId) { + // TODO + return agentConnection.getAssignmentRuleInfo(clusterId, serverId, ruleId); + } + + /** + * Gets the list of cluster security profiles. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of cluster security profiles + */ + public List getSecurityProfiles(UUID clusterId) { + // TODO + return agentConnection.getSecurityProfiles(clusterId); + } + + /** + * Creates or updates a cluster security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param profile -security profile + */ + public void createSecurityProfile(UUID clusterId, ISecurityProfile profile) { + // TODO + agentConnection.createSecurityProfile(clusterId, profile); + } + + /** + * Deletes a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + */ + public void dropSecurityProfile(UUID clusterId, String spName) { + // TODO + agentConnection.dropSecurityProfile(clusterId, spName); + } + + /** + * Gets the list of virtual directories of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @return list of virtual directories + */ + public List getSecurityProfileVirtualDirectories( + UUID clusterId, String spName) { + // TODO + return agentConnection.getSecurityProfileVirtualDirectories(clusterId, spName); + } + + /** + * Creates or updates a virtual directory of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param directory - virtual directory + */ + public void createSecurityProfileVirtualDirectory( + UUID clusterId, ISecurityProfileVirtualDirectory directory) { + // TODO + agentConnection.createSecurityProfileVirtualDirectory(clusterId, directory); + } + + /** + * Deletes a virtual directory of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @param alias - virtual directory alias + */ + public void dropSecurityProfileVirtualDirectory(UUID clusterId, String spName, String alias) { + // TODO + agentConnection.dropSecurityProfileVirtualDirectory(clusterId, spName, alias); + } + + /** + * Gets the list of allowed COM classes of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @return infobase full infobase description + */ + public List getSecurityProfileComClasses( + UUID clusterId, String spName) { + // TODO + return agentConnection.getSecurityProfileComClasses(clusterId, spName); + } + + /** + * Creates or updates an allowed COM class of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param comClass - allowed COM class + */ + public void createSecurityProfileComClass(UUID clusterId, ISecurityProfileCOMClass comClass) { + // TODO + agentConnection.createSecurityProfileComClass(clusterId, comClass); + } + + /** + * Deletes an allowed COM class of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @param name - COM class name + */ + public void dropSecurityProfileComClass(UUID clusterId, String spName, String name) { + // TODO + agentConnection.dropSecurityProfileComClass(clusterId, spName, name); + } + + /** + * Gets the list of allowed add-ins of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @return list of allowed add-ins + */ + public List getSecurityProfileAddIns(UUID clusterId, String spName) { + // TODO + return agentConnection.getSecurityProfileAddIns(clusterId, spName); + } + + /** + * Creates or updates an allowed add-in of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param addIn - allowed add-in + */ + public void createSecurityProfileAddIn(UUID clusterId, ISecurityProfileAddIn addIn) { + // TODO + agentConnection.createSecurityProfileAddIn(clusterId, addIn); + } + + /** + * Deletes an allowed add-in of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName -security profile name + * @param name -add-in name + */ + public void dropSecurityProfileAddIn(UUID clusterId, String spName, String name) { + // TODO + agentConnection.dropSecurityProfileAddIn(clusterId, spName, name); + } + + /** + * Gets the list of allowed unsafe external modules of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @return list of allowed external modules + */ + public List getSecurityProfileUnsafeExternalModules( + UUID clusterId, String spName) { + // TODO + return agentConnection.getSecurityProfileUnsafeExternalModules(clusterId, spName); + } + + /** + * Creates or updates an allowed unsafe external module of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param module - allowed external module + */ + public void createSecurityProfileUnsafeExternalModule( + UUID clusterId, ISecurityProfileExternalModule module) { + // TODO + agentConnection.createSecurityProfileUnsafeExternalModule(clusterId, module); + } + + /** + * Deletes an allowed unsafe external module of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @param name - external module name + */ + public void dropSecurityProfileUnsafeExternalModule(UUID clusterId, String spName, String name) { + // TODO + agentConnection.dropSecurityProfileUnsafeExternalModule(clusterId, spName, name); + } + + /** + * Gets the list of allowed applications of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @return list of allowed applications + */ + public List getSecurityProfileApplications( + UUID clusterId, String spName) { + // TODO + return agentConnection.getSecurityProfileApplications(clusterId, spName); + } + + /** + * Creates or updates an allowed application of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param app - allowed application + */ + public void createSecurityProfileApplication(UUID clusterId, ISecurityProfileApplication app) { + // TODO + agentConnection.createSecurityProfileApplication(clusterId, app); + } + + /** + * Deletes an allowed application of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @param name - application name + */ + public void dropSecurityProfileApplication(UUID clusterId, String spName, String name) { + // TODO + agentConnection.dropSecurityProfileApplication(clusterId, spName, name); + } + + /** + * Gets the list of Internet resources of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @return infobase full infobase description + */ + public List getSecurityProfileInternetResources( + UUID clusterId, String spName) { + // TODO + return agentConnection.getSecurityProfileInternetResources(clusterId, spName); + } + + /** + * Creates or updates an Internet resource of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param resource - Internet resource + */ + public void createSecurityProfileInternetResource( + UUID clusterId, ISecurityProfileInternetResource resource) { + // TODO + agentConnection.createSecurityProfileInternetResource(clusterId, resource); + } + + /** + * Deletes an Internet resource of a security profile. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param spName - security profile name + * @param name - Internet resource name + */ + public void dropSecurityProfileInternetResource(UUID clusterId, String spName, String name) { + // TODO + agentConnection.dropSecurityProfileInternetResource(clusterId, spName, name); + } + + /** + * Gets the list of resource counters. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of cluster resource counters + */ + public List getResourceConsumptionCounters(UUID clusterId) { + // TODO + return agentConnection.getResourceConsumptionCounters(clusterId); + } + + /** + * Gets resource counters description. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param counterName - resource counter name + * @return cluster resource counter info + */ + public IResourceConsumptionCounter getResourceConsumptionCounterInfo( + UUID clusterId, String counterName) { + // TODO + return agentConnection.getResourceConsumptionCounterInfo(clusterId, counterName); + } + + /** + * Creates or updates a resource counter. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param counter - resource counter info + */ + public void regResourceConsumptionCounter(UUID clusterId, IResourceConsumptionCounter counter) { + // TODO + agentConnection.regResourceConsumptionCounter(clusterId, counter); + } + + /** + * Deletes a resource counter. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param counterName - resource counter name + */ + public void unregResourceConsumptionCounter(UUID clusterId, String counterName) { + // TODO + agentConnection.unregResourceConsumptionCounter(clusterId, counterName); + } + + /** + * Gets the list of resource limits. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @return list of cluster resource limits + */ + public List getResourceConsumptionLimits(UUID clusterId) { + // TODO + return agentConnection.getResourceConsumptionLimits(clusterId); + } + + /** + * Gets resource limits description. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param limitName - resource limit name + * @return cluster resource counter info + */ + public IResourceConsumptionLimit getResourceConsumptionLimitInfo( + UUID clusterId, String limitName) { + // TODO + return agentConnection.getResourceConsumptionLimitInfo(clusterId, limitName); + } + + /** + * Creates or updates a resource limit. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param limit - cluster resource limit info + */ + public void regResourceConsumptionLimit(UUID clusterId, IResourceConsumptionLimit limit) { + // TODO + agentConnection.regResourceConsumptionLimit(clusterId, limit); + } + + /** + * Deletes a resource limits. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param limitName - resource limit name + */ + public void unregResourceConsumptionLimit(UUID clusterId, String limitName) { + // TODO + agentConnection.unregResourceConsumptionLimit(clusterId, limitName); + } + + /** + * Gets the list of resource counter values. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param counterName - resource counter name + * @param object - object name + * @return list of resource counter values + */ + public List getResourceConsumptionCounterValues( + UUID clusterId, String counterName, String object) { + // TODO + return agentConnection.getResourceConsumptionCounterValues(clusterId, counterName, object); + } + + /** + * Deletes a resource counter values. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param counterName - resource counter name + * @param object - object name + */ + public void clearResourceConsumptionCounterAccumulatedValues( + UUID clusterId, String counterName, String object) { + // TODO + agentConnection.clearResourceConsumptionCounterAccumulatedValues( + clusterId, counterName, object); + } + + /** + * Gets the list of resource counter accumulated values. + * + *

        Cluster authentication is required. + * + * @param clusterId - cluster ID + * @param counterName - resource counter name + * @param object - object name + * @return ist of resource counter accumulated values + */ + public List getResourceConsumptionCounterAccumulatedValues( + UUID clusterId, String counterName, String object) { + // TODO + return agentConnection.getResourceConsumptionCounterAccumulatedValues( + clusterId, counterName, object); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java index ded9749..8caba40 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java @@ -1,249 +1,327 @@ package ru.yanygin.clusterAdminLibrary; +import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; +import com._1c.v8.ibis.admin.ISessionInfo; +import com._1c.v8.ibis.admin.IWorkingProcessInfo; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; -import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; -import com._1c.v8.ibis.admin.ISessionInfo; -import com._1c.v8.ibis.admin.IWorkingProcessInfo; - +/** Extend info for session. */ public class SessionInfoExtended implements IInfoExtended { - - private static final String TITLE_USERNAME = Messages.getString("SessionInfo.Username"); //$NON-NLS-1$ - private static final String TITLE_INFOBASE = Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ - private static final String TITLE_SESSION_N = Messages.getString("SessionInfo.SessionN"); //$NON-NLS-1$ - private static final String TITLE_CONNECTION_N = Messages.getString("SessionInfo.ConnectionN"); //$NON-NLS-1$ - private static final String TITLE_STARTED_AT = Messages.getString("SessionInfo.StartedAt"); //$NON-NLS-1$ - private static final String TITLE_LAST_ACTIVE_AT = Messages.getString("SessionInfo.LastActiveAt"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_APPLICATION = Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ - private static final String TITLE_SERVER = Messages.getString("SessionInfo.Server"); //$NON-NLS-1$ - private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ - private static final String TITLE_PID = Messages.getString("SessionInfo.PID"); //$NON-NLS-1$ - private static final String TITLE_DB_PROC_INFO = Messages.getString("SessionInfo.DbProcInfo"); //$NON-NLS-1$ - private static final String TITLE_DB_PROC_TOOK = Messages.getString("SessionInfo.DbProcTook"); //$NON-NLS-1$ - private static final String TITLE_DB_PROC_TOOK_AT = Messages.getString("SessionInfo.DbProcTookAt"); //$NON-NLS-1$ - private static final String TITLE_BLOCKED_BY_DBMS = Messages.getString("SessionInfo.BlockedByDbms"); //$NON-NLS-1$ - private static final String TITLE_BLOCKED_BY_LS = Messages.getString("SessionInfo.BlockedByLs"); //$NON-NLS-1$ - private static final String TITLE_DURATION_CURRENT_DBMS = Messages.getString("SessionInfo.DurationCurrentDbms"); //$NON-NLS-1$ - private static final String TITLE_DURATION_LAST_5_MIN_DBMS = Messages.getString("SessionInfo.DurationLast5MinDbms"); //$NON-NLS-1$ - private static final String TITLE_DURATION_ALL_DBMS = Messages.getString("SessionInfo.DurationAllDbms"); //$NON-NLS-1$ - private static final String TITLE_DBMS_BYTES_LAST_5_MIN = Messages.getString("SessionInfo.DbmsBytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_DBMS_BYTES_ALL = Messages.getString("SessionInfo.DbmsBytesAll"); //$NON-NLS-1$ - private static final String TITLE_DURATION_CURRENT = Messages.getString("SessionInfo.DurationCurrent"); //$NON-NLS-1$ - private static final String TITLE_DURATION_LAST_5_MIN = Messages.getString("SessionInfo.DurationLast5Min"); //$NON-NLS-1$ - private static final String TITLE_DURATION_ALL = Messages.getString("SessionInfo.DurationAll"); //$NON-NLS-1$ - private static final String TITLE_CALLS_LAST_5_MIN = Messages.getString("SessionInfo.CallsLast5Min"); //$NON-NLS-1$ - private static final String TITLE_CALLS_ALL = Messages.getString("SessionInfo.CallsAll"); //$NON-NLS-1$ - private static final String TITLE_BYTES_LAST_5_MIN = Messages.getString("SessionInfo.BytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_BYTES_ALL = Messages.getString("SessionInfo.BytesAll"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_CURRENT = Messages.getString("SessionInfo.MemoryCurrent"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_LAST_5_MIN = Messages.getString("SessionInfo.MemoryLast5Min"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_TOTAL = Messages.getString("SessionInfo.MemoryTotal"); //$NON-NLS-1$ - private static final String TITLE_READ_BYTES_CURRENT = Messages.getString("SessionInfo.ReadBytesCurrent"); //$NON-NLS-1$ - private static final String TITLE_READ_BYTES_LAST_5_MIN = Messages.getString("SessionInfo.ReadBytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_READ_BYTES_TOTAL = Messages.getString("SessionInfo.ReadBytesTotal"); //$NON-NLS-1$ - private static final String TITLE_WRITE_BYTES_CURRENT = Messages.getString("SessionInfo.WriteBytesCurrent"); //$NON-NLS-1$ - private static final String TITLE_WRITE_BYTES_LAST_5_MIN = Messages.getString("SessionInfo.WriteBytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_WRITE_BYTES_TOTAL = Messages.getString("SessionInfo.WriteBytesTotal"); //$NON-NLS-1$ - private static final String TITLE_LICENSE = Messages.getString("SessionInfo.License"); //$NON-NLS-1$ - private static final String TITLE_IS_SLEEP = Messages.getString("SessionInfo.IsSleep"); //$NON-NLS-1$ - private static final String TITLE_SLEEP_AFTER = Messages.getString("SessionInfo.SleepAfter"); //$NON-NLS-1$ - private static final String TITLE_KILL_AFTER = Messages.getString("SessionInfo.KillAfter"); //$NON-NLS-1$ - private static final String TITLE_CLIENT_IP_ADDRESS = Messages.getString("SessionInfo.ClientIPAddress"); //$NON-NLS-1$ - private static final String TITLE_DATA_SEPARATION = Messages.getString("SessionInfo.DataSeparation"); //$NON-NLS-1$ - private static final String TITLE_CURRRENT_SERVICE_NAME = Messages.getString("SessionInfo.CurrentServiceName"); //$NON-NLS-1$ - private static final String TITLE_DURATION_CURRENT_SERVICE = Messages.getString("SessionInfo.DurationCurrentService"); //$NON-NLS-1$ - private static final String TITLE_DURATION_LAST_5_MIN_SERVICE = Messages.getString("SessionInfo.DurationLast5MinService"); //$NON-NLS-1$ - private static final String TITLE_DURATION_ALL_SERVICE = Messages.getString("SessionInfo.DurationAllService"); //$NON-NLS-1$ - private static final String TITLE_CPU_TIME_CURRENT = Messages.getString("SessionInfo.CpuTimeCurrent"); //$NON-NLS-1$ - private static final String TITLE_CPU_TIME_LAST_5_MIN = Messages.getString("SessionInfo.CpuTimeLast5Min"); //$NON-NLS-1$ - private static final String TITLE_CPU_TIME_ALL = Messages.getString("SessionInfo.CpuTimeAll"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - UUID infobaseId; - ISessionInfo sessionInfo; - List connections; - - Map columnsMap = new LinkedHashMap<>(); - - public SessionInfoExtended(Server server, UUID clusterId, UUID infobaseId, ISessionInfo sessionInfo, - List connections, Map columnsMap) { - - this.server = server; - this.clusterId = clusterId; - this.infobaseId = infobaseId; - this.sessionInfo = sessionInfo; - this.connections = connections; - this.columnsMap = columnsMap; - - } - - public static void initColumnsName(Map sessionColumnsMap) { - - sessionColumnsMap.put(TITLE_USERNAME, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_SESSION_N, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_CONNECTION_N, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_STARTED_AT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_LAST_ACTIVE_AT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_SERVER, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_PID, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_DB_PROC_INFO, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DB_PROC_TOOK, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DB_PROC_TOOK_AT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_BLOCKED_BY_DBMS, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_BLOCKED_BY_LS, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_DURATION_CURRENT_DBMS, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_LAST_5_MIN_DBMS, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_ALL_DBMS, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DBMS_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DBMS_BYTES_ALL, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_DURATION_CURRENT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_ALL, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_CALLS_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_CALLS_ALL, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_BYTES_ALL, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_MEMORY_CURRENT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_MEMORY_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_MEMORY_TOTAL, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_READ_BYTES_CURRENT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_READ_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_READ_BYTES_TOTAL, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_WRITE_BYTES_CURRENT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_WRITE_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_WRITE_BYTES_TOTAL, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_LICENSE, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_IS_SLEEP, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_SLEEP_AFTER, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_KILL_AFTER, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_CLIENT_IP_ADDRESS, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DATA_SEPARATION, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_CURRRENT_SERVICE_NAME, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_CURRENT_SERVICE, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_LAST_5_MIN_SERVICE, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_DURATION_ALL_SERVICE, ""); //$NON-NLS-1$ - - sessionColumnsMap.put(TITLE_CPU_TIME_CURRENT, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_CPU_TIME_LAST_5_MIN, ""); //$NON-NLS-1$ - sessionColumnsMap.put(TITLE_CPU_TIME_ALL, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initSessionsColumnCount(sessionColumnsMap.size()); - - } - - public String[] getExtendedInfo() { - - if (this.infobaseId == null) - this.infobaseId = sessionInfo.getInfoBaseId(); - - String infobaseName = server.getInfoBaseName(clusterId, infobaseId); - - // connection - var connectionNumber = ""; //$NON-NLS-1$ - if (!sessionInfo.getConnectionId().equals(emptyUuid)) { - IInfoBaseConnectionShort connectionInfoShort = server.getConnectionInfoShort(clusterId, sessionInfo.getConnectionId()); - connectionNumber = String.valueOf(connectionInfoShort.getConnId()); - } - - // Working Process - var wpHostName = ""; //$NON-NLS-1$ - var wpMainPort = ""; //$NON-NLS-1$ - var wpPid = ""; //$NON-NLS-1$ - if (!sessionInfo.getWorkingProcessId().equals(emptyUuid)) { - IWorkingProcessInfo wpInfo = server.getWorkingProcessInfo(clusterId, sessionInfo.getWorkingProcessId()); - wpHostName = wpInfo.getHostName(); - wpMainPort = Integer.toString(wpInfo.getMainPort()); - wpPid = wpInfo.getPid(); - } - - // license - var license = sessionInfo.getLicenses().isEmpty() ? "" : sessionInfo.getLicenses().get(0).getFullPresentation(); //$NON-NLS-1$ - - Map session = new LinkedHashMap<>(); - session.putAll(columnsMap); - - session.put(TITLE_USERNAME, sessionInfo.getUserName()); - session.put(TITLE_INFOBASE, infobaseName); - session.put(TITLE_SESSION_N, Integer.toString(sessionInfo.getSessionId())); - session.put(TITLE_CONNECTION_N, connectionNumber); - session.put(TITLE_STARTED_AT, dateToString(sessionInfo.getStartedAt())); - session.put(TITLE_LAST_ACTIVE_AT, dateToString(sessionInfo.getLastActiveAt())); - session.put(TITLE_COMPUTER, sessionInfo.getHost()); - session.put(TITLE_APPLICATION, server.getApplicationName(sessionInfo.getAppId())); - session.put(TITLE_SERVER, wpHostName); - session.put(TITLE_PORT, wpMainPort); - session.put(TITLE_PID, wpPid); - - session.put(TITLE_DB_PROC_INFO, sessionInfo.getDbProcInfo()); - session.put(TITLE_DB_PROC_TOOK, double3ToString(sessionInfo.getDbProcTook())); - session.put(TITLE_DB_PROC_TOOK_AT, dateToString(sessionInfo.getDbProcTookAt())); - session.put(TITLE_BLOCKED_BY_DBMS, Integer.toString(sessionInfo.getBlockedByDbms())); - session.put(TITLE_BLOCKED_BY_LS, Integer.toString(sessionInfo.getBlockedByLs())); - - session.put(TITLE_DURATION_CURRENT_DBMS, millisecondToString(sessionInfo.getDurationCurrentDbms())); - session.put(TITLE_DURATION_LAST_5_MIN_DBMS, millisecondToString(sessionInfo.getDurationLast5MinDbms())); - session.put(TITLE_DURATION_ALL_DBMS, millisecondToString(sessionInfo.getDurationAllDbms())); - - session.put(TITLE_DBMS_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getDbmsBytesLast5Min())); - session.put(TITLE_DBMS_BYTES_ALL, longToStringGroup(sessionInfo.getDbmsBytesAll())); - - session.put(TITLE_DURATION_CURRENT, millisecondToString(sessionInfo.getDurationCurrent())); - session.put(TITLE_DURATION_LAST_5_MIN, millisecondToString(sessionInfo.getDurationLast5Min())); - session.put(TITLE_DURATION_ALL, millisecondToString(sessionInfo.getDurationAll())); - - session.put(TITLE_CALLS_LAST_5_MIN, Long.toString(sessionInfo.getCallsLast5Min())); - session.put(TITLE_CALLS_ALL, Integer.toString(sessionInfo.getCallsAll())); - - session.put(TITLE_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getBytesLast5Min())); - session.put(TITLE_BYTES_ALL, longToStringGroup(sessionInfo.getBytesAll())); - - session.put(TITLE_MEMORY_CURRENT, longToStringGroup(sessionInfo.getMemoryCurrent())); - session.put(TITLE_MEMORY_LAST_5_MIN, longToStringGroup(sessionInfo.getMemoryLast5Min())); - session.put(TITLE_MEMORY_TOTAL, longToStringGroup(sessionInfo.getMemoryTotal())); - - session.put(TITLE_READ_BYTES_CURRENT, longToStringGroup(sessionInfo.getReadBytesCurrent())); - session.put(TITLE_READ_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getReadBytesLast5Min())); - session.put(TITLE_READ_BYTES_TOTAL, longToStringGroup(sessionInfo.getReadBytesTotal())); - session.put(TITLE_WRITE_BYTES_CURRENT, longToStringGroup(sessionInfo.getWriteBytesCurrent())); - session.put(TITLE_WRITE_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getWriteBytesLast5Min())); - session.put(TITLE_WRITE_BYTES_TOTAL, longToStringGroup(sessionInfo.getWriteBytesTotal())); - - session.put(TITLE_LICENSE, license); - session.put(TITLE_IS_SLEEP, Boolean.toString(sessionInfo.getHibernate())); - session.put(TITLE_SLEEP_AFTER, Integer.toString(sessionInfo.getPassiveSessionHibernateTime())); - session.put(TITLE_KILL_AFTER, Integer.toString(sessionInfo.getHibernateSessionTerminationTime())); - session.put(TITLE_CLIENT_IP_ADDRESS, sessionInfo.getClientIPAddress()); - session.put(TITLE_DATA_SEPARATION, sessionInfo.getDataSeparation()); - - session.put(TITLE_CURRRENT_SERVICE_NAME, sessionInfo.getCurrentServiceName()); - session.put(TITLE_DURATION_CURRENT_SERVICE, millisecondToString(sessionInfo.getDurationCurrentService())); - session.put(TITLE_DURATION_LAST_5_MIN_SERVICE, millisecondToString(sessionInfo.getDurationLast5MinService())); - session.put(TITLE_DURATION_ALL_SERVICE, millisecondToString(sessionInfo.getDurationAllService())); - - session.put(TITLE_CPU_TIME_CURRENT, millisecondToString(sessionInfo.getCpuTimeCurrent())); - session.put(TITLE_CPU_TIME_LAST_5_MIN, millisecondToString(sessionInfo.getCpuTimeLast5Min())); - session.put(TITLE_CPU_TIME_ALL, millisecondToString(sessionInfo.getCpuTimeAll())); - - return session.values().toArray(new String[0]); - - } - + + private static final String TITLE_USERNAME = + Messages.getString("SessionInfo.Username"); //$NON-NLS-1$ + private static final String TITLE_INFOBASE = + Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ + private static final String TITLE_SESSION_N = + Messages.getString("SessionInfo.SessionN"); //$NON-NLS-1$ + private static final String TITLE_CONNECTION_N = + Messages.getString("SessionInfo.ConnectionN"); //$NON-NLS-1$ + private static final String TITLE_STARTED_AT = + Messages.getString("SessionInfo.StartedAt"); //$NON-NLS-1$ + private static final String TITLE_LAST_ACTIVE_AT = + Messages.getString("SessionInfo.LastActiveAt"); //$NON-NLS-1$ + private static final String TITLE_COMPUTER = + Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ + private static final String TITLE_APPLICATION = + Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ + private static final String TITLE_SERVER = + Messages.getString("SessionInfo.Server"); //$NON-NLS-1$ + private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ + private static final String TITLE_PID = Messages.getString("SessionInfo.PID"); //$NON-NLS-1$ + private static final String TITLE_DB_PROC_INFO = + Messages.getString("SessionInfo.DbProcInfo"); //$NON-NLS-1$ + private static final String TITLE_DB_PROC_TOOK = + Messages.getString("SessionInfo.DbProcTook"); //$NON-NLS-1$ + private static final String TITLE_DB_PROC_TOOK_AT = + Messages.getString("SessionInfo.DbProcTookAt"); //$NON-NLS-1$ + private static final String TITLE_BLOCKED_BY_DBMS = + Messages.getString("SessionInfo.BlockedByDbms"); //$NON-NLS-1$ + private static final String TITLE_BLOCKED_BY_LS = + Messages.getString("SessionInfo.BlockedByLs"); //$NON-NLS-1$ + private static final String TITLE_DURATION_CURRENT_DBMS = + Messages.getString("SessionInfo.DurationCurrentDbms"); //$NON-NLS-1$ + private static final String TITLE_DURATION_LAST_5_MIN_DBMS = + Messages.getString("SessionInfo.DurationLast5MinDbms"); //$NON-NLS-1$ + private static final String TITLE_DURATION_ALL_DBMS = + Messages.getString("SessionInfo.DurationAllDbms"); //$NON-NLS-1$ + private static final String TITLE_DBMS_BYTES_LAST_5_MIN = + Messages.getString("SessionInfo.DbmsBytesLast5Min"); //$NON-NLS-1$ + private static final String TITLE_DBMS_BYTES_ALL = + Messages.getString("SessionInfo.DbmsBytesAll"); //$NON-NLS-1$ + private static final String TITLE_DURATION_CURRENT = + Messages.getString("SessionInfo.DurationCurrent"); //$NON-NLS-1$ + private static final String TITLE_DURATION_LAST_5_MIN = + Messages.getString("SessionInfo.DurationLast5Min"); //$NON-NLS-1$ + private static final String TITLE_DURATION_ALL = + Messages.getString("SessionInfo.DurationAll"); //$NON-NLS-1$ + private static final String TITLE_CALLS_LAST_5_MIN = + Messages.getString("SessionInfo.CallsLast5Min"); //$NON-NLS-1$ + private static final String TITLE_CALLS_ALL = + Messages.getString("SessionInfo.CallsAll"); //$NON-NLS-1$ + private static final String TITLE_BYTES_LAST_5_MIN = + Messages.getString("SessionInfo.BytesLast5Min"); //$NON-NLS-1$ + private static final String TITLE_BYTES_ALL = + Messages.getString("SessionInfo.BytesAll"); //$NON-NLS-1$ + private static final String TITLE_MEMORY_CURRENT = + Messages.getString("SessionInfo.MemoryCurrent"); //$NON-NLS-1$ + private static final String TITLE_MEMORY_LAST_5_MIN = + Messages.getString("SessionInfo.MemoryLast5Min"); //$NON-NLS-1$ + private static final String TITLE_MEMORY_TOTAL = + Messages.getString("SessionInfo.MemoryTotal"); //$NON-NLS-1$ + private static final String TITLE_READ_BYTES_CURRENT = + Messages.getString("SessionInfo.ReadBytesCurrent"); //$NON-NLS-1$ + private static final String TITLE_READ_BYTES_LAST_5_MIN = + Messages.getString("SessionInfo.ReadBytesLast5Min"); //$NON-NLS-1$ + private static final String TITLE_READ_BYTES_TOTAL = + Messages.getString("SessionInfo.ReadBytesTotal"); //$NON-NLS-1$ + private static final String TITLE_WRITE_BYTES_CURRENT = + Messages.getString("SessionInfo.WriteBytesCurrent"); //$NON-NLS-1$ + private static final String TITLE_WRITE_BYTES_LAST_5_MIN = + Messages.getString("SessionInfo.WriteBytesLast5Min"); //$NON-NLS-1$ + private static final String TITLE_WRITE_BYTES_TOTAL = + Messages.getString("SessionInfo.WriteBytesTotal"); //$NON-NLS-1$ + private static final String TITLE_LICENSE = + Messages.getString("SessionInfo.License"); //$NON-NLS-1$ + private static final String TITLE_IS_SLEEP = + Messages.getString("SessionInfo.IsSleep"); //$NON-NLS-1$ + private static final String TITLE_SLEEP_AFTER = + Messages.getString("SessionInfo.SleepAfter"); //$NON-NLS-1$ + private static final String TITLE_KILL_AFTER = + Messages.getString("SessionInfo.KillAfter"); //$NON-NLS-1$ + private static final String TITLE_CLIENT_IP_ADDRESS = + Messages.getString("SessionInfo.ClientIPAddress"); //$NON-NLS-1$ + private static final String TITLE_DATA_SEPARATION = + Messages.getString("SessionInfo.DataSeparation"); //$NON-NLS-1$ + private static final String TITLE_CURRRENT_SERVICE_NAME = + Messages.getString("SessionInfo.CurrentServiceName"); //$NON-NLS-1$ + private static final String TITLE_DURATION_CURRENT_SERVICE = + Messages.getString("SessionInfo.DurationCurrentService"); //$NON-NLS-1$ + private static final String TITLE_DURATION_LAST_5_MIN_SERVICE = + Messages.getString("SessionInfo.DurationLast5MinService"); //$NON-NLS-1$ + private static final String TITLE_DURATION_ALL_SERVICE = + Messages.getString("SessionInfo.DurationAllService"); //$NON-NLS-1$ + private static final String TITLE_CPU_TIME_CURRENT = + Messages.getString("SessionInfo.CpuTimeCurrent"); //$NON-NLS-1$ + private static final String TITLE_CPU_TIME_LAST_5_MIN = + Messages.getString("SessionInfo.CpuTimeLast5Min"); //$NON-NLS-1$ + private static final String TITLE_CPU_TIME_ALL = + Messages.getString("SessionInfo.CpuTimeAll"); //$NON-NLS-1$ + + Server server; + UUID clusterId; + UUID infobaseId; + ISessionInfo sessionInfo; + List connections; + + Map columnsMap = new LinkedHashMap<>(); + + /** + * Create extended info for working server. + * + * @param server - server + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + * @param sessionInfo - session info + * @param connections - list of connections + * @param columnsMap - columns map + */ + public SessionInfoExtended( + Server server, + UUID clusterId, + UUID infobaseId, + ISessionInfo sessionInfo, + List connections, + Map columnsMap) { + + this.server = server; + this.clusterId = clusterId; + this.infobaseId = infobaseId; + this.sessionInfo = sessionInfo; + this.connections = connections; + this.columnsMap = columnsMap; + } + + /** + * Init columns name. + * + * @param columnsMap - sample map with columns name + */ + public static void initColumnsName(Map columnsMap) { + + columnsMap.put(TITLE_USERNAME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SESSION_N, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CONNECTION_N, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_STARTED_AT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_LAST_ACTIVE_AT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SERVER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_PID, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_DB_PROC_INFO, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DB_PROC_TOOK, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DB_PROC_TOOK_AT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_BLOCKED_BY_DBMS, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_BLOCKED_BY_LS, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_DURATION_CURRENT_DBMS, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_LAST_5_MIN_DBMS, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_ALL_DBMS, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DBMS_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DBMS_BYTES_ALL, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_DURATION_CURRENT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_ALL, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_CALLS_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CALLS_ALL, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_BYTES_ALL, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_MEMORY_CURRENT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_MEMORY_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_MEMORY_TOTAL, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_READ_BYTES_CURRENT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_READ_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_READ_BYTES_TOTAL, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_WRITE_BYTES_CURRENT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_WRITE_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_WRITE_BYTES_TOTAL, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_LICENSE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_IS_SLEEP, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SLEEP_AFTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_KILL_AFTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CLIENT_IP_ADDRESS, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DATA_SEPARATION, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_CURRRENT_SERVICE_NAME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_CURRENT_SERVICE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_LAST_5_MIN_SERVICE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DURATION_ALL_SERVICE, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_CPU_TIME_CURRENT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CPU_TIME_LAST_5_MIN, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CPU_TIME_ALL, ""); //$NON-NLS-1$ + + ClusterProvider.getCommonConfig().initSessionsColumnCount(columnsMap.size()); + } + + @Override + public String[] getExtendedInfo() { + + if (this.infobaseId == null) { + this.infobaseId = sessionInfo.getInfoBaseId(); + } + + // connection + var connectionNumber = ""; //$NON-NLS-1$ + if (!sessionInfo.getConnectionId().equals(emptyUuid)) { + IInfoBaseConnectionShort connectionInfoShort = + server.getConnectionInfoShort(clusterId, sessionInfo.getConnectionId()); + connectionNumber = String.valueOf(connectionInfoShort.getConnId()); + } + + // Working Process + var wpHostName = ""; //$NON-NLS-1$ + var wpMainPort = ""; //$NON-NLS-1$ + var wpPid = ""; //$NON-NLS-1$ + if (!sessionInfo.getWorkingProcessId().equals(emptyUuid)) { + IWorkingProcessInfo wpInfo = + server.getWorkingProcessInfo(clusterId, sessionInfo.getWorkingProcessId()); + wpHostName = wpInfo.getHostName(); + wpMainPort = Integer.toString(wpInfo.getMainPort()); + wpPid = wpInfo.getPid(); + } + + // license + var license = + sessionInfo.getLicenses().isEmpty() + ? "" //$NON-NLS-1$ + : sessionInfo.getLicenses().get(0).getFullPresentation(); + + Map session = new LinkedHashMap<>(); + session.putAll(columnsMap); + + session.put(TITLE_USERNAME, sessionInfo.getUserName()); + session.put(TITLE_INFOBASE, server.getInfoBaseName(clusterId, infobaseId)); + session.put(TITLE_SESSION_N, Integer.toString(sessionInfo.getSessionId())); + session.put(TITLE_CONNECTION_N, connectionNumber); + session.put(TITLE_STARTED_AT, dateToString(sessionInfo.getStartedAt())); + session.put(TITLE_LAST_ACTIVE_AT, dateToString(sessionInfo.getLastActiveAt())); + session.put(TITLE_COMPUTER, sessionInfo.getHost()); + session.put(TITLE_APPLICATION, server.getApplicationName(sessionInfo.getAppId())); + session.put(TITLE_SERVER, wpHostName); + session.put(TITLE_PORT, wpMainPort); + session.put(TITLE_PID, wpPid); + + session.put(TITLE_DB_PROC_INFO, sessionInfo.getDbProcInfo()); + session.put(TITLE_DB_PROC_TOOK, double3ToString(sessionInfo.getDbProcTook())); + session.put(TITLE_DB_PROC_TOOK_AT, dateToString(sessionInfo.getDbProcTookAt())); + session.put(TITLE_BLOCKED_BY_DBMS, Integer.toString(sessionInfo.getBlockedByDbms())); + session.put(TITLE_BLOCKED_BY_LS, Integer.toString(sessionInfo.getBlockedByLs())); + + session.put( + TITLE_DURATION_CURRENT_DBMS, millisecondToString(sessionInfo.getDurationCurrentDbms())); + session.put( + TITLE_DURATION_LAST_5_MIN_DBMS, millisecondToString(sessionInfo.getDurationLast5MinDbms())); + session.put(TITLE_DURATION_ALL_DBMS, millisecondToString(sessionInfo.getDurationAllDbms())); + + session.put(TITLE_DBMS_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getDbmsBytesLast5Min())); + session.put(TITLE_DBMS_BYTES_ALL, longToStringGroup(sessionInfo.getDbmsBytesAll())); + + session.put(TITLE_DURATION_CURRENT, millisecondToString(sessionInfo.getDurationCurrent())); + session.put(TITLE_DURATION_LAST_5_MIN, millisecondToString(sessionInfo.getDurationLast5Min())); + session.put(TITLE_DURATION_ALL, millisecondToString(sessionInfo.getDurationAll())); + + session.put(TITLE_CALLS_LAST_5_MIN, Long.toString(sessionInfo.getCallsLast5Min())); + session.put(TITLE_CALLS_ALL, Integer.toString(sessionInfo.getCallsAll())); + + session.put(TITLE_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getBytesLast5Min())); + session.put(TITLE_BYTES_ALL, longToStringGroup(sessionInfo.getBytesAll())); + + session.put(TITLE_MEMORY_CURRENT, longToStringGroup(sessionInfo.getMemoryCurrent())); + session.put(TITLE_MEMORY_LAST_5_MIN, longToStringGroup(sessionInfo.getMemoryLast5Min())); + session.put(TITLE_MEMORY_TOTAL, longToStringGroup(sessionInfo.getMemoryTotal())); + + session.put(TITLE_READ_BYTES_CURRENT, longToStringGroup(sessionInfo.getReadBytesCurrent())); + session.put(TITLE_READ_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getReadBytesLast5Min())); + session.put(TITLE_READ_BYTES_TOTAL, longToStringGroup(sessionInfo.getReadBytesTotal())); + session.put(TITLE_WRITE_BYTES_CURRENT, longToStringGroup(sessionInfo.getWriteBytesCurrent())); + session.put( + TITLE_WRITE_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getWriteBytesLast5Min())); + session.put(TITLE_WRITE_BYTES_TOTAL, longToStringGroup(sessionInfo.getWriteBytesTotal())); + + session.put(TITLE_LICENSE, license); + session.put(TITLE_IS_SLEEP, Boolean.toString(sessionInfo.getHibernate())); + session.put(TITLE_SLEEP_AFTER, Integer.toString(sessionInfo.getPassiveSessionHibernateTime())); + session.put( + TITLE_KILL_AFTER, Integer.toString(sessionInfo.getHibernateSessionTerminationTime())); + session.put(TITLE_CLIENT_IP_ADDRESS, sessionInfo.getClientIPAddress()); + session.put(TITLE_DATA_SEPARATION, sessionInfo.getDataSeparation()); + + session.put(TITLE_CURRRENT_SERVICE_NAME, sessionInfo.getCurrentServiceName()); + session.put( + TITLE_DURATION_CURRENT_SERVICE, + millisecondToString(sessionInfo.getDurationCurrentService())); + session.put( + TITLE_DURATION_LAST_5_MIN_SERVICE, + millisecondToString(sessionInfo.getDurationLast5MinService())); + session.put( + TITLE_DURATION_ALL_SERVICE, millisecondToString(sessionInfo.getDurationAllService())); + + session.put(TITLE_CPU_TIME_CURRENT, millisecondToString(sessionInfo.getCpuTimeCurrent())); + session.put(TITLE_CPU_TIME_LAST_5_MIN, millisecondToString(sessionInfo.getCpuTimeLast5Min())); + session.put(TITLE_CPU_TIME_ALL, millisecondToString(sessionInfo.getCpuTimeAll())); + + return session.values().toArray(new String[0]); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java index 09133a0..57379ba 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java @@ -1,141 +1,169 @@ package ru.yanygin.clusterAdminLibrary; +import com._1c.v8.ibis.admin.IWorkingProcessInfo; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; -import com._1c.v8.ibis.admin.IWorkingProcessInfo; - +/** Extend info for working process. */ public class WorkingProcessInfoExtended implements IInfoExtended { - - private static final String TITLE_COMPUTER = Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ - private static final String TITLE_USING = Messages.getString("WPInfo.Using"); //$NON-NLS-1$ - private static final String TITLE_ENABLES = Messages.getString("WPInfo.Enabled"); //$NON-NLS-1$ - private static final String TITLE_ACTIVE = Messages.getString("WPInfo.Active"); //$NON-NLS-1$ - private static final String TITLE_PID = Messages.getString("SessionInfo.PID"); //$NON-NLS-1$ - private static final String TITLE_MEMORY = Messages.getString("WPInfo.Memory"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_EXCEEDED = Messages.getString("WPInfo.MemoryExceeded"); //$NON-NLS-1$ - private static final String TITLE_AVAILABLE_PERFORMANCE = Messages.getString("WPInfo.AvailablePerformance"); //$NON-NLS-1$ - private static final String TITLE_LICENSE = Messages.getString("SessionInfo.License"); //$NON-NLS-1$ - private static final String TITLE_STARTED_AT = Messages.getString("SessionInfo.StartedAt"); //$NON-NLS-1$ - private static final String TITLE_CONNECTIONS_COUNT = Messages.getString("WPInfo.ConnectionsCount"); //$NON-NLS-1$ - private static final String TITLE_BACK_CALL_TIME = Messages.getString("WPInfo.BackCallTime"); //$NON-NLS-1$ - private static final String TITLE_SERVER_CALL_TIME = Messages.getString("WPInfo.ServerCallTime"); //$NON-NLS-1$ - private static final String TITLE_DB_CALL_TIME = Messages.getString("WPInfo.DBCallTime"); //$NON-NLS-1$ - private static final String TITLE_CALL_TIME = Messages.getString("WPInfo.CallTime"); //$NON-NLS-1$ - private static final String TITLE_LOCK_CALL_TIME = Messages.getString("WPInfo.LockCallTime"); //$NON-NLS-1$ - private static final String TITLE_CLIENT_THREADS = Messages.getString("WPInfo.ClientThreads"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - IWorkingProcessInfo workingProcess; - - Map columnsMap = new LinkedHashMap<>(); - - public WorkingProcessInfoExtended(Server server, UUID clusterId, IWorkingProcessInfo workingProcess, - Map columnsMap) { - - this.server = server; - this.clusterId = clusterId; - this.workingProcess = workingProcess; - this.columnsMap = columnsMap; - - } - - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_USING, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_ENABLES, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_ACTIVE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PID, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MEMORY, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MEMORY_EXCEEDED, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_AVAILABLE_PERFORMANCE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LICENSE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_STARTED_AT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTIONS_COUNT, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_BACK_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SERVER_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DB_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LOCK_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CLIENT_THREADS, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initWorkingProcessesColumnCount(columnsMap.size()); - - } - - public String[] getExtendedInfo() { - - Map wp = new LinkedHashMap<>(); - wp.putAll(columnsMap); - - // license - var license = workingProcess.getLicense().isEmpty() ? "" : workingProcess.getLicense().get(0).getFullPresentation(); //$NON-NLS-1$ - - wp.put(TITLE_COMPUTER, workingProcess.getHostName()); - wp.put(TITLE_PORT, Integer.toString(workingProcess.getMainPort())); - wp.put(TITLE_USING, isUse()); - wp.put(TITLE_ENABLES, Boolean.toString(workingProcess.isEnable())); - wp.put(TITLE_ACTIVE, isRunning()); - wp.put(TITLE_PID, workingProcess.getPid()); - wp.put(TITLE_MEMORY, longToStringGroup(workingProcess.getMemorySize())); - wp.put(TITLE_MEMORY_EXCEEDED, Long.toString(workingProcess.getMemoryExcessTime())); - wp.put(TITLE_AVAILABLE_PERFORMANCE, Integer.toString(workingProcess.getAvailablePerfomance())); - wp.put(TITLE_LICENSE, license); - wp.put(TITLE_STARTED_AT, dateToString(workingProcess.getStartedAt())); - wp.put(TITLE_CONNECTIONS_COUNT, Integer.toString(workingProcess.getConnections())); - - wp.put(TITLE_BACK_CALL_TIME, double6ToString(workingProcess.getAvgBackCallTime())); - wp.put(TITLE_SERVER_CALL_TIME, double6ToString(workingProcess.getAvgServerCallTime())); - wp.put(TITLE_DB_CALL_TIME, double6ToString(workingProcess.getAvgDBCallTime())); - wp.put(TITLE_CALL_TIME, double6ToString(workingProcess.getAvgCallTime())); - wp.put(TITLE_LOCK_CALL_TIME, double6ToString(workingProcess.getAvgLockCallTime())); - wp.put(TITLE_CLIENT_THREADS, double6ToString(workingProcess.getAvgThreads())); - - return wp.values().toArray(new String[0]); - - } - - private String isUse() { - - String isUse; - switch (workingProcess.getUse()) { - case 0: - isUse = Messages.getString("WPInfo.NotUsed"); //$NON-NLS-1$ - break; - case 1: - isUse = Messages.getString("WPInfo.Used"); //$NON-NLS-1$ - break; - case 2: - isUse = Messages.getString("WPInfo.UsedAsReserve"); //$NON-NLS-1$ - break; - default: - isUse = Messages.getString("WPInfo.NotUsed"); //$NON-NLS-1$ - break; - } - return isUse; - } - - private String isRunning() { - - String isRunning; - switch (workingProcess.getRunning()) { - case 0: - isRunning = Messages.getString("WPInfo.ProcessIsStopped"); //$NON-NLS-1$ - break; - case 1: - isRunning = Messages.getString("WPInfo.ProcessIsRunning"); //$NON-NLS-1$ - break; - default: - isRunning = Messages.getString("WPInfo.ProcessIsStopped"); //$NON-NLS-1$ - break; - } - return isRunning; - } - + + private static final String TITLE_COMPUTER = + Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ + private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ + private static final String TITLE_USING = Messages.getString("WPInfo.Using"); //$NON-NLS-1$ + private static final String TITLE_ENABLES = Messages.getString("WPInfo.Enabled"); //$NON-NLS-1$ + private static final String TITLE_ACTIVE = Messages.getString("WPInfo.Active"); //$NON-NLS-1$ + private static final String TITLE_PID = Messages.getString("SessionInfo.PID"); //$NON-NLS-1$ + private static final String TITLE_MEMORY = Messages.getString("WPInfo.Memory"); //$NON-NLS-1$ + private static final String TITLE_MEMORY_EXCEEDED = + Messages.getString("WPInfo.MemoryExceeded"); //$NON-NLS-1$ + private static final String TITLE_AVAILABLE_PERFORMANCE = + Messages.getString("WPInfo.AvailablePerformance"); //$NON-NLS-1$ + private static final String TITLE_LICENSE = + Messages.getString("SessionInfo.License"); //$NON-NLS-1$ + private static final String TITLE_STARTED_AT = + Messages.getString("SessionInfo.StartedAt"); //$NON-NLS-1$ + private static final String TITLE_CONNECTIONS_COUNT = + Messages.getString("WPInfo.ConnectionsCount"); //$NON-NLS-1$ + private static final String TITLE_BACK_CALL_TIME = + Messages.getString("WPInfo.BackCallTime"); //$NON-NLS-1$ + private static final String TITLE_SERVER_CALL_TIME = + Messages.getString("WPInfo.ServerCallTime"); //$NON-NLS-1$ + private static final String TITLE_DB_CALL_TIME = + Messages.getString("WPInfo.DBCallTime"); //$NON-NLS-1$ + private static final String TITLE_CALL_TIME = + Messages.getString("WPInfo.CallTime"); //$NON-NLS-1$ + private static final String TITLE_LOCK_CALL_TIME = + Messages.getString("WPInfo.LockCallTime"); //$NON-NLS-1$ + private static final String TITLE_CLIENT_THREADS = + Messages.getString("WPInfo.ClientThreads"); //$NON-NLS-1$ + + Server server; + UUID clusterId; + IWorkingProcessInfo workingProcess; + + Map columnsMap = new LinkedHashMap<>(); + + /** + * Create extended info for working process. + * + * @param server - server + * @param clusterId - cluster ID + * @param workingProcess - working process + * @param columnsMap - columns map + */ + public WorkingProcessInfoExtended( + Server server, + UUID clusterId, + IWorkingProcessInfo workingProcess, + Map columnsMap) { + + this.server = server; + this.clusterId = clusterId; + this.workingProcess = workingProcess; + this.columnsMap = columnsMap; + } + + /** + * Init columns name. + * + * @param columnsMap - sample map with columns name + */ + public static void initColumnsName(Map columnsMap) { + + columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_USING, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_ENABLES, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_ACTIVE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_PID, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_MEMORY, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_MEMORY_EXCEEDED, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_AVAILABLE_PERFORMANCE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_LICENSE, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_STARTED_AT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CONNECTIONS_COUNT, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_BACK_CALL_TIME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SERVER_CALL_TIME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DB_CALL_TIME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CALL_TIME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_LOCK_CALL_TIME, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CLIENT_THREADS, ""); //$NON-NLS-1$ + + ClusterProvider.getCommonConfig().initWorkingProcessesColumnCount(columnsMap.size()); + } + + @Override + public String[] getExtendedInfo() { + + Map wp = new LinkedHashMap<>(); + wp.putAll(columnsMap); + + // license + var license = + workingProcess.getLicense().isEmpty() + ? "" //$NON-NLS-1$ + : workingProcess.getLicense().get(0).getFullPresentation(); + + wp.put(TITLE_COMPUTER, workingProcess.getHostName()); + wp.put(TITLE_PORT, Integer.toString(workingProcess.getMainPort())); + wp.put(TITLE_USING, isUse()); + wp.put(TITLE_ENABLES, Boolean.toString(workingProcess.isEnable())); + wp.put(TITLE_ACTIVE, isRunning()); + wp.put(TITLE_PID, workingProcess.getPid()); + wp.put(TITLE_MEMORY, longToStringGroup(workingProcess.getMemorySize())); + wp.put(TITLE_MEMORY_EXCEEDED, Long.toString(workingProcess.getMemoryExcessTime())); + wp.put(TITLE_AVAILABLE_PERFORMANCE, Integer.toString(workingProcess.getAvailablePerfomance())); + wp.put(TITLE_LICENSE, license); + wp.put(TITLE_STARTED_AT, dateToString(workingProcess.getStartedAt())); + wp.put(TITLE_CONNECTIONS_COUNT, Integer.toString(workingProcess.getConnections())); + + wp.put(TITLE_BACK_CALL_TIME, double6ToString(workingProcess.getAvgBackCallTime())); + wp.put(TITLE_SERVER_CALL_TIME, double6ToString(workingProcess.getAvgServerCallTime())); + wp.put(TITLE_DB_CALL_TIME, double6ToString(workingProcess.getAvgDBCallTime())); + wp.put(TITLE_CALL_TIME, double6ToString(workingProcess.getAvgCallTime())); + wp.put(TITLE_LOCK_CALL_TIME, double6ToString(workingProcess.getAvgLockCallTime())); + wp.put(TITLE_CLIENT_THREADS, double6ToString(workingProcess.getAvgThreads())); + + return wp.values().toArray(new String[0]); + } + + private String isUse() { + + String isUse; + switch (workingProcess.getUse()) { + case 0: + isUse = Messages.getString("WPInfo.NotUsed"); //$NON-NLS-1$ + break; + case 1: + isUse = Messages.getString("WPInfo.Used"); //$NON-NLS-1$ + break; + case 2: + isUse = Messages.getString("WPInfo.UsedAsReserve"); //$NON-NLS-1$ + break; + default: + isUse = Messages.getString("WPInfo.NotUsed"); //$NON-NLS-1$ + break; + } + return isUse; + } + + private String isRunning() { + + String isRunning; + switch (workingProcess.getRunning()) { + case 0: + isRunning = Messages.getString("WPInfo.ProcessIsStopped"); //$NON-NLS-1$ + break; + case 1: + isRunning = Messages.getString("WPInfo.ProcessIsRunning"); //$NON-NLS-1$ + break; + default: + isRunning = Messages.getString("WPInfo.ProcessIsStopped"); //$NON-NLS-1$ + break; + } + return isRunning; + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java index af892db..52b5bb3 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java @@ -1,108 +1,141 @@ package ru.yanygin.clusterAdminLibrary; +import com._1c.v8.ibis.admin.IPortRangeInfo; +import com._1c.v8.ibis.admin.IWorkingServerInfo; import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; -import com._1c.v8.ibis.admin.IPortRangeInfo; -import com._1c.v8.ibis.admin.IWorkingServerInfo; - +/** Extend info for working server. */ public class WorkingServerInfoExtended implements IInfoExtended { - - private static final String TITLE_DESCRIPTION = Messages.getString("InfoTables.Description"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_IP_PORT = Messages.getString("WSInfo.IPPort"); //$NON-NLS-1$ - private static final String TITLE_RANGE_IP_PORTS = Messages.getString("WSInfo.RangeIPPorts"); //$NON-NLS-1$ - private static final String TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT = Messages - .getString("WSInfo.SafeWorkingProcessesMemoryLimit"); //$NON-NLS-1$ - private static final String TITLE_SAFE_CALL_MEMORY_LIMIT = Messages.getString("WSInfo.SafeCallMemoryLimit"); //$NON-NLS-1$ - private static final String TITLE_WORKING_PROCESS_MEMORY_LIMIT = Messages - .getString("WSInfo.WorkingProcessMemoryLimit"); //$NON-NLS-1$ - private static final String TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY = Messages - .getString("WSInfo.CriticalProcessesTotalMemory"); //$NON-NLS-1$ - private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY = Messages - .getString("WSInfo.TemporaryAllowedProcessesTotalMemory"); //$NON-NLS-1$ - private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT = Messages - .getString("WSInfo.TemporaryAllowedProcessesTotalMemoryTimeLimit"); //$NON-NLS-1$ - private static final String TITLE_IB_PER_PROCESS_LIMIT = Messages.getString("WSInfo.IBPerProcessLimit"); //$NON-NLS-1$ - private static final String TITLE_CONN_PER_PROCESS_LIMIT = Messages.getString("WSInfo.ConnPerProcessLimit"); //$NON-NLS-1$ - private static final String TITLE_IP_PORT_MAIN_MANAGER = Messages.getString("WSInfo.IPPortMainManager"); //$NON-NLS-1$ - private static final String TITLE_DEDICATED_MANAGERS = Messages.getString("WSInfo.DedicatedManagers"); //$NON-NLS-1$ - private static final String TITLE_MAIN_SERVER = Messages.getString("WSInfo.MainServer"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - IWorkingServerInfo workingServer; - - Map columnsMap = new LinkedHashMap<>(); - - public WorkingServerInfoExtended(Server server, UUID clusterId, IWorkingServerInfo workingServer, - Map columnsMap) { - - this.server = server; - this.clusterId = clusterId; - this.workingServer = workingServer; - this.columnsMap = columnsMap; - - } - - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_DESCRIPTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_IP_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_RANGE_IP_PORTS, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SAFE_CALL_MEMORY_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_WORKING_PROCESS_MEMORY_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_IB_PER_PROCESS_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONN_PER_PROCESS_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_IP_PORT_MAIN_MANAGER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DEDICATED_MANAGERS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MAIN_SERVER, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initWorkingServersColumnCount(columnsMap.size()); - - } - - public String[] getExtendedInfo() { - - Map ws = new LinkedHashMap<>(); - ws.putAll(columnsMap); - - ws.put(TITLE_DESCRIPTION, workingServer.getName()); // $NON-NLS-1$ - ws.put(TITLE_COMPUTER, workingServer.getHostName()); // $NON-NLS-1$ - ws.put(TITLE_IP_PORT, Integer.toString(workingServer.getMainPort())); // $NON-NLS-1$ - ws.put(TITLE_RANGE_IP_PORTS, getPortRange()); // $NON-NLS-1$ - ws.put(TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, - longToStringGroup(workingServer.getSafeWorkingProcessesMemoryLimit())); // $NON-NLS-1$ - ws.put(TITLE_SAFE_CALL_MEMORY_LIMIT, longToStringGroup(workingServer.getSafeCallMemoryLimit())); // $NON-NLS-1$ - ws.put(TITLE_WORKING_PROCESS_MEMORY_LIMIT, longToStringGroup(workingServer.getWorkingProcessMemoryLimit())); // $NON-NLS-1$ - ws.put(TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, - longToStringGroup(workingServer.getCriticalProcessesTotalMemory())); // $NON-NLS-1$ - ws.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, - longToStringGroup(workingServer.getTemporaryAllowedProcessesTotalMemory())); // $NON-NLS-1$ - ws.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, - longToStringGroup(workingServer.getTemporaryAllowedProcessesTotalMemoryTimeLimit())); // $NON-NLS-1$ - ws.put(TITLE_IB_PER_PROCESS_LIMIT, Integer.toString(workingServer.getInfoBasesPerWorkingProcessLimit())); // $NON-NLS-1$ - ws.put(TITLE_CONN_PER_PROCESS_LIMIT, Integer.toString(workingServer.getConnectionsPerWorkingProcessLimit())); // $NON-NLS-1$ - ws.put(TITLE_IP_PORT_MAIN_MANAGER, Integer.toString(workingServer.getClusterMainPort())); // $NON-NLS-1$ - ws.put(TITLE_DEDICATED_MANAGERS, Boolean.toString(workingServer.isDedicatedManagers())); // $NON-NLS-1$ - ws.put(TITLE_MAIN_SERVER, Boolean.toString(workingServer.isMainServer())); // $NON-NLS-1$ - - return ws.values().toArray(new String[0]); - - } - - private String getPortRange() { - IPortRangeInfo portRangesInfo = workingServer.getPortRanges().get(0); - return Integer.toString(portRangesInfo.getLowBound()).concat(":") //$NON-NLS-1$ - .concat(Integer.toString(portRangesInfo.getHighBound())); - } - + + private static final String TITLE_DESCRIPTION = + Messages.getString("InfoTables.Description"); //$NON-NLS-1$ + private static final String TITLE_COMPUTER = + Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ + private static final String TITLE_IP_PORT = Messages.getString("WSInfo.IPPort"); //$NON-NLS-1$ + private static final String TITLE_RANGE_IP_PORTS = + Messages.getString("WSInfo.RangeIPPorts"); //$NON-NLS-1$ + private static final String TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT = + Messages.getString("WSInfo.SafeWorkingProcessesMemoryLimit"); //$NON-NLS-1$ + private static final String TITLE_SAFE_CALL_MEMORY_LIMIT = + Messages.getString("WSInfo.SafeCallMemoryLimit"); //$NON-NLS-1$ + private static final String TITLE_WORKING_PROCESS_MEMORY_LIMIT = + Messages.getString("WSInfo.WorkingProcessMemoryLimit"); //$NON-NLS-1$ + private static final String TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY = + Messages.getString("WSInfo.CriticalProcessesTotalMemory"); //$NON-NLS-1$ + private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY = + Messages.getString("WSInfo.TemporaryAllowedProcessesTotalMemory"); //$NON-NLS-1$ + private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT = + Messages.getString("WSInfo.TemporaryAllowedProcessesTotalMemoryTimeLimit"); //$NON-NLS-1$ + private static final String TITLE_IB_PER_PROCESS_LIMIT = + Messages.getString("WSInfo.IBPerProcessLimit"); //$NON-NLS-1$ + private static final String TITLE_CONN_PER_PROCESS_LIMIT = + Messages.getString("WSInfo.ConnPerProcessLimit"); //$NON-NLS-1$ + private static final String TITLE_IP_PORT_MAIN_MANAGER = + Messages.getString("WSInfo.IPPortMainManager"); //$NON-NLS-1$ + private static final String TITLE_DEDICATED_MANAGERS = + Messages.getString("WSInfo.DedicatedManagers"); //$NON-NLS-1$ + private static final String TITLE_MAIN_SERVER = + Messages.getString("WSInfo.MainServer"); //$NON-NLS-1$ + + Server server; + UUID clusterId; + IWorkingServerInfo workingServer; + + Map columnsMap = new LinkedHashMap<>(); + + /** + * Create extended info for working server. + * + * @param server - server + * @param clusterId - cluster ID + * @param workingServer - working server info + * @param columnsMap - columns map + */ + public WorkingServerInfoExtended( + Server server, + UUID clusterId, + IWorkingServerInfo workingServer, + Map columnsMap) { + + this.server = server; + this.clusterId = clusterId; + this.workingServer = workingServer; + this.columnsMap = columnsMap; + } + + /** + * Init columns name. + * + * @param columnsMap - sample map with columns name + */ + public static void initColumnsName(Map columnsMap) { + + columnsMap.put(TITLE_DESCRIPTION, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_IP_PORT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_RANGE_IP_PORTS, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_SAFE_CALL_MEMORY_LIMIT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_WORKING_PROCESS_MEMORY_LIMIT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, ""); //$NON-NLS-1$ + + columnsMap.put(TITLE_IB_PER_PROCESS_LIMIT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_CONN_PER_PROCESS_LIMIT, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_IP_PORT_MAIN_MANAGER, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_DEDICATED_MANAGERS, ""); //$NON-NLS-1$ + columnsMap.put(TITLE_MAIN_SERVER, ""); //$NON-NLS-1$ + + ClusterProvider.getCommonConfig().initWorkingServersColumnCount(columnsMap.size()); + } + + @Override + public String[] getExtendedInfo() { + + Map ws = new LinkedHashMap<>(); + ws.putAll(columnsMap); + + ws.put(TITLE_DESCRIPTION, workingServer.getName()); + ws.put(TITLE_COMPUTER, workingServer.getHostName()); + ws.put(TITLE_IP_PORT, Integer.toString(workingServer.getMainPort())); + ws.put(TITLE_RANGE_IP_PORTS, getPortRange()); + ws.put( + TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, + longToStringGroup(workingServer.getSafeWorkingProcessesMemoryLimit())); + ws.put(TITLE_SAFE_CALL_MEMORY_LIMIT, longToStringGroup(workingServer.getSafeCallMemoryLimit())); + ws.put( + TITLE_WORKING_PROCESS_MEMORY_LIMIT, + longToStringGroup(workingServer.getWorkingProcessMemoryLimit())); + ws.put( + TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, + longToStringGroup(workingServer.getCriticalProcessesTotalMemory())); + ws.put( + TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, + longToStringGroup(workingServer.getTemporaryAllowedProcessesTotalMemory())); + ws.put( + TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, + longToStringGroup(workingServer.getTemporaryAllowedProcessesTotalMemoryTimeLimit())); + ws.put( + TITLE_IB_PER_PROCESS_LIMIT, + Integer.toString(workingServer.getInfoBasesPerWorkingProcessLimit())); + ws.put( + TITLE_CONN_PER_PROCESS_LIMIT, + Integer.toString(workingServer.getConnectionsPerWorkingProcessLimit())); + ws.put(TITLE_IP_PORT_MAIN_MANAGER, Integer.toString(workingServer.getClusterMainPort())); + ws.put(TITLE_DEDICATED_MANAGERS, Boolean.toString(workingServer.isDedicatedManagers())); + ws.put(TITLE_MAIN_SERVER, Boolean.toString(workingServer.isMainServer())); + + return ws.values().toArray(new String[0]); + } + + private String getPortRange() { + IPortRangeInfo portRangesInfo = workingServer.getPortRanges().get(0); + return Integer.toString(portRangesInfo.getLowBound()) + .concat(":") //$NON-NLS-1$ + .concat(Integer.toString(portRangesInfo.getHighBound())); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java index aff9d5c..a1a7350 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java @@ -3,6 +3,9 @@ import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Button; @@ -12,91 +15,97 @@ import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import org.eclipse.wb.swt.SWTResourceManager; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; +/** About dialog. */ public class AboutDialog extends Dialog { - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public AboutDialog(Shell parentShell) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - } - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { + /** + * Create the dialog. + * + * @param parentShell - parent shell + */ + public AboutDialog(Shell parentShell) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + + Label lblMainTitle = new Label(container, SWT.NONE); + lblMainTitle.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); + lblMainTitle.setFont(SWTResourceManager.getFont("Segoe UI", 20, SWT.BOLD)); //$NON-NLS-1$ + lblMainTitle.setText(Messages.getString("AboutDialog.MainTitle")); + + Label lblDescription = new Label(container, SWT.NONE); + lblDescription.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); + lblDescription.setText(Messages.getString("AboutDialog.Description")); //$NON-NLS-1$ + lblDescription.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL)); + + Label lblAutor = new Label(container, SWT.NONE); + lblAutor.setText(Messages.getString("AboutDialog.Autor")); + lblAutor.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL)); + + Link linkGitHub = new Link(container, SWT.NONE); + linkGitHub.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Program.launch("https://github.com/YanSergey/OneS_ClusterAdmin"); + } + }); + linkGitHub.setText(Messages.getString("AboutDialog.GitHub")); + + Link linkTelegram = new Link(container, 0); + linkTelegram.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Program.launch("https://t.me/YanSergey"); + } + }); + linkTelegram.setText(Messages.getString("AboutDialog.Telegram")); + + Link linkEmail = new Link(container, 0); + linkEmail.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Program.launch("mailto:yanyginsa@gmail.com"); + } + }); + linkEmail.setText(Messages.getString("AboutDialog.Email")); + + return container; + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + close(); + } + }); + } - Composite container = (Composite) super.createDialogArea(parent); - - Label lblMainTitle = new Label(container, SWT.NONE); - lblMainTitle.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); - lblMainTitle.setFont(SWTResourceManager.getFont("Segoe UI", 20, SWT.BOLD)); //$NON-NLS-1$ - lblMainTitle.setText(Messages.getString("AboutDialog.MainTitle")); - - Label lblDescription = new Label(container, SWT.NONE); - lblDescription.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); - lblDescription.setText(Messages.getString("AboutDialog.Description")); //$NON-NLS-1$ - lblDescription.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL)); - - Label lblAutor = new Label(container, SWT.NONE); - lblAutor.setText(Messages.getString("AboutDialog.Autor")); - lblAutor.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL)); - - Link linkGitHub = new Link(container, SWT.NONE); - linkGitHub.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Program.launch("https://github.com/YanSergey/OneS_ClusterAdmin"); - } - }); - linkGitHub.setText(Messages.getString("AboutDialog.GitHub")); - - Link linkTelegram = new Link(container, 0); - linkTelegram.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Program.launch("https://t.me/YanSergey"); - } - }); - linkTelegram.setText(Messages.getString("AboutDialog.Telegram")); - - Link linkEmail = new Link(container, 0); - linkEmail.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Program.launch("mailto:yanyginsa@gmail.com"); - } - }); - linkEmail.setText(Messages.getString("AboutDialog.Email")); - - return container; - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - close(); - } - }); - } - @Override - protected Point getInitialSize() { - return new Point(500, 330); - } + @Override + protected Point getInitialSize() { + return new Point(500, 330); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java index c0b491f..831f280 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java @@ -2,121 +2,125 @@ import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; - +/** Authenticate dialog. */ public class AuthenticateDialog extends Dialog { - - private Text txtUsername; - private Text txtPassword; - - private String username; - private String password; - private String authExcpMessage; - private String authDescription; - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public AuthenticateDialog(Shell parentShell, String username, String authDescription, String authExcpMessage) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.username = username; - this.authDescription = authDescription; - this.authExcpMessage = authExcpMessage; - - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.numColumns = 2; - - Label lblAuthenticateInfo = new Label(container, SWT.WRAP); - lblAuthenticateInfo.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, true, 2, 1)); - lblAuthenticateInfo.setText(authDescription); - - Label lblUsername = new Label(container, SWT.NONE); - lblUsername.setText(Messages.getString("Dialogs.Username")); //$NON-NLS-1$ - - txtUsername = new Text(container, SWT.BORDER); - txtUsername.setToolTipText(Messages.getString("Dialogs.Username")); //$NON-NLS-1$ - txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblPassword = new Label(container, SWT.NONE); - lblPassword.setText(Messages.getString("Dialogs.Password")); //$NON-NLS-1$ - - txtPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); - txtPassword.setToolTipText(Messages.getString("Dialogs.Password")); //$NON-NLS-1$ - txtPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblAuthExcpMessage = new Label(container, SWT.WRAP); - lblAuthExcpMessage.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, true, 2, 1)); - lblAuthExcpMessage.setText(authExcpMessage); - - initProperties(); - - return container; - } - - private void initProperties() { - this.txtUsername.setText(username); - } - - private void extractVariablesFromControls() { - - username = txtUsername.getText(); - password = txtPassword.getText(); - - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - extractVariablesFromControls(); - close(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } + private Text txtUsername; + private Text txtPassword; + + private String username; + private String password; + private String authExcpMessage; + private String authDescription; + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param username - username + * @param authDescription - authenticate description + * @param authExcpMessage - authenticate exception message + */ + public AuthenticateDialog( + Shell parentShell, String username, String authDescription, String authExcpMessage) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.username = username; + this.authDescription = authDescription; + this.authExcpMessage = authExcpMessage; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.numColumns = 2; + + Label lblAuthenticateInfo = new Label(container, SWT.WRAP); + lblAuthenticateInfo.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, true, 2, 1)); + lblAuthenticateInfo.setText(authDescription); + + Label lblUsername = new Label(container, SWT.NONE); + lblUsername.setText(Messages.getString("Dialogs.Username")); //$NON-NLS-1$ + + txtUsername = new Text(container, SWT.BORDER); + txtUsername.setToolTipText(Messages.getString("Dialogs.Username")); //$NON-NLS-1$ + txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblPassword = new Label(container, SWT.NONE); + lblPassword.setText(Messages.getString("Dialogs.Password")); //$NON-NLS-1$ + + txtPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); + txtPassword.setToolTipText(Messages.getString("Dialogs.Password")); //$NON-NLS-1$ + txtPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblAuthExcpMessage = new Label(container, SWT.WRAP); + lblAuthExcpMessage.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, true, 2, 1)); + lblAuthExcpMessage.setText(authExcpMessage); + + initProperties(); + + return container; + } + + private void initProperties() { + this.txtUsername.setText(username); + } + + private void extractVariablesFromControls() { + + username = txtUsername.getText(); + password = txtPassword.getText(); + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + extractVariablesFromControls(); + close(); + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java index 2d00bfe..64b6f7d 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java @@ -1,9 +1,10 @@ package ru.yanygin.clusterAdminLibraryUI; +import com._1c.v8.ibis.admin.ClusterInfo; +import com._1c.v8.ibis.admin.IClusterInfo; import java.util.ArrayList; import java.util.List; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -23,401 +24,462 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.SWTResourceManager; - -import com._1c.v8.ibis.admin.ClusterInfo; -import com._1c.v8.ibis.admin.IClusterInfo; - import ru.yanygin.clusterAdminLibrary.Server; +/** Dialog for сreate and edit cluster. */ public class CreateEditClusterDialog extends Dialog { - - private UUID clusterId; - private Server server; - - private Button btnClusterRecyclingKillProblemProcesses; - private Text txtClusterName; - private Text txtComputerName; - private Text txtIPPort; - private Combo comboSecurityLevel; - private Text txtLifeTimeLimit; - private Text txtMaxMemorySize; - private Text txtMaxMemoryTimeLimit; - private Text txtClusterRecyclingErrorsCountThreshold; - private Text txtExpirationTimeout; - private Text txtSessionFaultToleranceLevel; - private Combo comboLoadBalancingMode; - private Button btnClusterRecyclingKillByMemoryWithDump; - - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public CreateEditClusterDialog(Shell parentShell, Server server, UUID clusterId) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.server = server; - this.clusterId = clusterId; - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.makeColumnsEqualWidth = true; - gridLayout.marginWidth = 10; - gridLayout.marginHeight = 12; - gridLayout.numColumns = 2; - - Label lblClusterName = new Label(container, SWT.NONE); - lblClusterName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblClusterName.setText(Messages.getString("ClusterDialog.ClusterName")); //$NON-NLS-1$ - - txtClusterName = new Text(container, SWT.BORDER); - txtClusterName.setToolTipText(Messages.getString("ClusterDialog.ClusterName")); - GridData gdtxtClusterName = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtClusterName.widthHint = 200; - txtClusterName.setLayoutData(gdtxtClusterName); - - Label lblComputerName = new Label(container, SWT.NONE); - lblComputerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblComputerName.setText(Messages.getString("ClusterDialog.ComputerName")); //$NON-NLS-1$ - - txtComputerName = new Text(container, SWT.BORDER); - txtComputerName.setToolTipText(Messages.getString("ClusterDialog.ComputerName")); - GridData gdtxtComputerName = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtComputerName.widthHint = 200; - txtComputerName.setLayoutData(gdtxtComputerName); - - Label lblIPPort = new Label(container, SWT.NONE); - lblIPPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblIPPort.setText(Messages.getString("ClusterDialog.IPPort")); //$NON-NLS-1$ - - txtIPPort = new Text(container, SWT.BORDER); - txtIPPort.setToolTipText(Messages.getString("ClusterDialog.IPPort")); - GridData gdtxtIPPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtIPPort.widthHint = 200; - txtIPPort.setLayoutData(gdtxtIPPort); - - Label lblSecurityLevel = new Label(container, SWT.NONE); - lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ - - comboSecurityLevel = new Combo(container, SWT.READ_ONLY); - comboSecurityLevel.setVisibleItemCount(3); - comboSecurityLevel.setTouchEnabled(true); - comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); - GridData gdcomboSecurityLevel = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdcomboSecurityLevel.widthHint = 200; - comboSecurityLevel.setLayoutData(gdcomboSecurityLevel); - - comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ - comboSecurityLevel.select(0); - - Group groupWorkProcessesParams = new Group(container, SWT.NONE); - groupWorkProcessesParams.setText(Messages.getString("ClusterDialog.RestartWorkProcesses")); //$NON-NLS-1$ - GridLayout glgroupWorkProcessesParams = new GridLayout(2, true); - glgroupWorkProcessesParams.verticalSpacing = 8; - groupWorkProcessesParams.setLayout(glgroupWorkProcessesParams); - groupWorkProcessesParams.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); - - Label lblLifeTimeLimit = new Label(groupWorkProcessesParams, SWT.NONE); - lblLifeTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLifeTimeLimit.setText(Messages.getString("ClusterDialog.RestartInterval")); //$NON-NLS-1$ - - txtLifeTimeLimit = new Text(groupWorkProcessesParams, SWT.BORDER); - GridData gdtxtLifeTimeLimit = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); - gdtxtLifeTimeLimit.widthHint = 200; - txtLifeTimeLimit.setLayoutData(gdtxtLifeTimeLimit); - txtLifeTimeLimit.setToolTipText(Messages.getString("ClusterDialog.RestartInterval")); //$NON-NLS-1$ - - Label lblMaxMemorySize = new Label(groupWorkProcessesParams, SWT.NONE); - lblMaxMemorySize.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblMaxMemorySize.setText(Messages.getString("ClusterDialog.AllowedAmountOfMemoryWithLineBreak")); //$NON-NLS-1$ - - txtMaxMemorySize = new Text(groupWorkProcessesParams, SWT.BORDER); - GridData gdtxtMaxMemorySize = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); - gdtxtMaxMemorySize.widthHint = 200; - txtMaxMemorySize.setLayoutData(gdtxtMaxMemorySize); - txtMaxMemorySize.setToolTipText(Messages.getString("ClusterDialog.AllowedAmountOfMemory")); //$NON-NLS-1$ - - Label lblMaxMemoryTimeLimit = new Label(groupWorkProcessesParams, SWT.WRAP); - lblMaxMemoryTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, true, 1, 1)); - lblMaxMemoryTimeLimit.setText(Messages.getString("ClusterDialog.IntervalExceedingAllowedAmountOfMemoryWithLineBreak")); //$NON-NLS-1$ - - txtMaxMemoryTimeLimit = new Text(groupWorkProcessesParams, SWT.BORDER); - GridData gdtxtMaxMemoryTimeLimit = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); - gdtxtMaxMemoryTimeLimit.widthHint = 200; - txtMaxMemoryTimeLimit.setLayoutData(gdtxtMaxMemoryTimeLimit); - txtMaxMemoryTimeLimit.setToolTipText(Messages.getString("ClusterDialog.IntervalExceedingAllowedAmountOfMemory")); //$NON-NLS-1$ - - Label lblAcceptableDeviationOfNumberOfServerErrors = new Label(groupWorkProcessesParams, SWT.WRAP); - lblAcceptableDeviationOfNumberOfServerErrors.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, true, 1, 1)); - lblAcceptableDeviationOfNumberOfServerErrors.setText(Messages.getString("ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrorsWithLineBreak")); //$NON-NLS-1$ - - txtClusterRecyclingErrorsCountThreshold = new Text(groupWorkProcessesParams, SWT.BORDER); - GridData gdtxtClusterRecyclingErrorsCountThreshold = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); - gdtxtClusterRecyclingErrorsCountThreshold.widthHint = 200; - txtClusterRecyclingErrorsCountThreshold.setLayoutData(gdtxtClusterRecyclingErrorsCountThreshold); - txtClusterRecyclingErrorsCountThreshold.setToolTipText(Messages.getString("ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors")); //$NON-NLS-1$ - - btnClusterRecyclingKillProblemProcesses = new Button(groupWorkProcessesParams, SWT.CHECK); - btnClusterRecyclingKillProblemProcesses.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1)); - btnClusterRecyclingKillProblemProcesses.setText(Messages.getString("ClusterDialog.ForceShutdownOfProblematicProcesses")); //$NON-NLS-1$ - - btnClusterRecyclingKillByMemoryWithDump = new Button(groupWorkProcessesParams, SWT.CHECK); - btnClusterRecyclingKillByMemoryWithDump.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1)); - btnClusterRecyclingKillByMemoryWithDump.setText(Messages.getString("ClusterDialog.ClusterRecyclingKillByMemoryWithDump")); //$NON-NLS-1$ - - Label lblExpirationTimeout = new Label(container, SWT.NONE); - lblExpirationTimeout.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblExpirationTimeout.setText(Messages.getString("ClusterDialog.ShutDownProcessesStopAfterSecond")); //$NON-NLS-1$ - - txtExpirationTimeout = new Text(container, SWT.BORDER); - txtExpirationTimeout.setToolTipText(Messages.getString("ClusterDialog.ShutDownProcessesStopAfter")); - GridData gdtxtExpirationTimeout = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtExpirationTimeout.widthHint = 200; - txtExpirationTimeout.setLayoutData(gdtxtExpirationTimeout); - - Label lblSessionFaultToleranceLevel = new Label(container, SWT.NONE); - lblSessionFaultToleranceLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSessionFaultToleranceLevel.setText(Messages.getString("ClusterDialog.FaultToleranceLevel")); //$NON-NLS-1$ - - txtSessionFaultToleranceLevel = new Text(container, SWT.BORDER); - txtSessionFaultToleranceLevel.setToolTipText(Messages.getString("ClusterDialog.FaultToleranceLevel")); - GridData gdtxtSessionFaultToleranceLevel = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtSessionFaultToleranceLevel.widthHint = 200; - txtSessionFaultToleranceLevel.setLayoutData(gdtxtSessionFaultToleranceLevel); - - Label lblLoadBalancingMode = new Label(container, SWT.NONE); - lblLoadBalancingMode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLoadBalancingMode.setText(Messages.getString("ClusterDialog.LoadBalancingMode")); //$NON-NLS-1$ - - comboLoadBalancingMode = new Combo(container, SWT.READ_ONLY); - comboLoadBalancingMode.setVisibleItemCount(2); - comboLoadBalancingMode.setToolTipText(Messages.getString("ClusterDialog.LoadBalancingMode")); - GridData gdcomboLoadBalancingMode = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdcomboLoadBalancingMode.widthHint = 200; - comboLoadBalancingMode.setLayoutData(gdcomboLoadBalancingMode); - - comboLoadBalancingMode.add(Messages.getString("Dialogs.PerformancePriority")); //$NON-NLS-1$ - comboLoadBalancingMode.setData(Messages.getString("Dialogs.PerformancePriority"), 0); //$NON-NLS-1$ - comboLoadBalancingMode.add(Messages.getString("Dialogs.MemoryPriority")); //$NON-NLS-1$ - comboLoadBalancingMode.setData(Messages.getString("Dialogs.MemoryPriority"), 1); //$NON-NLS-1$ - comboLoadBalancingMode.select(0); - - initServerProperties(); - - return container; - } - - private void initServerProperties() { - IClusterInfo clusterInfo; - - if (clusterId != null) { - clusterInfo = server.getClusterInfo(clusterId); - - txtClusterName.setText(clusterInfo.getName()); - txtComputerName.setText(clusterInfo.getHostName()); - } else { - clusterInfo = new ClusterInfo(); - - txtClusterName.setText(""); //$NON-NLS-1$ - txtComputerName.setText(""); //$NON-NLS-1$ - } - - - txtIPPort.setText(Integer.toString(clusterInfo.getMainPort())); - comboSecurityLevel.select(clusterInfo.getSecurityLevel()); - - txtLifeTimeLimit.setText(Integer.toString(clusterInfo.getLifeTimeLimit())); - txtMaxMemorySize.setText(Integer.toString(clusterInfo.getMaxMemorySize())); // 8.3.15- - txtMaxMemoryTimeLimit.setText(Integer.toString(clusterInfo.getMaxMemoryTimeLimit())); // 8.3.15- - txtClusterRecyclingErrorsCountThreshold.setText(Integer.toString(clusterInfo.getClusterRecyclingErrorsCountThreshold())); // 8.3.15- - btnClusterRecyclingKillProblemProcesses.setSelection(clusterInfo.isClusterRecyclingKillProblemProcesses()); - btnClusterRecyclingKillByMemoryWithDump.setSelection(clusterInfo.isClusterRecyclingKillByMemoryWithDump()); // 8.3.15+ - - txtExpirationTimeout.setText(Integer.toString(clusterInfo.getExpirationTimeout())); - txtSessionFaultToleranceLevel.setText(Integer.toString(clusterInfo.getSessionFaultToleranceLevel())); - comboLoadBalancingMode.select(clusterInfo.getLoadBalancingMode()); - - if (server.isFifteenOrOlderAgentVersion()) { // 8.3.15+ - txtMaxMemorySize.setEditable(false); - txtMaxMemoryTimeLimit.setEditable(false); - txtClusterRecyclingErrorsCountThreshold.setEditable(false); - - txtMaxMemorySize.setToolTipText(Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - txtMaxMemoryTimeLimit.setToolTipText(Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - txtClusterRecyclingErrorsCountThreshold.setToolTipText(Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - } else { - btnClusterRecyclingKillByMemoryWithDump.setEnabled(false); - - btnClusterRecyclingKillByMemoryWithDump.setToolTipText(Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ - } - - // У уже созданного кластера запрещено менять хост и порт - if (clusterId != null) { - txtComputerName.setEditable(false); - txtIPPort.setEditable(false); - } - - } - - private void resetToProf() { - comboLoadBalancingMode.select(0); - } - - private boolean checkVariablesFromControls() { - - var existsError = false; - - List checksTextControls = new ArrayList<>(); - checksTextControls.add(txtClusterName); - checksTextControls.add(txtComputerName); - checksTextControls.add(txtIPPort); - - for (Text control : checksTextControls) { - if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); - existsError = true; - } else { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); - } - } - - List checksIntControls = new ArrayList<>(); - checksIntControls.add(txtIPPort); - checksIntControls.add(txtLifeTimeLimit); - checksIntControls.add(txtMaxMemorySize); - checksIntControls.add(txtMaxMemoryTimeLimit); - checksIntControls.add(txtClusterRecyclingErrorsCountThreshold); - checksIntControls.add(txtExpirationTimeout); - checksIntControls.add(txtSessionFaultToleranceLevel); - - for (Text control : checksIntControls) { - try { - Integer.parseInt(control.getText()); - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); - } catch (Exception e) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); - existsError = true; - } - } - - return existsError; - } - - private boolean saveNewClusterProperties() { - if (checkVariablesFromControls()) - return false; - - IClusterInfo clusterInfo; - - if (clusterId == null) { - clusterInfo = new ClusterInfo(); - - clusterInfo.setHostName(txtComputerName.getText()); - clusterInfo.setMainPort(Integer.parseInt(txtIPPort.getText())); - } else { - clusterInfo = server.getClusterInfo(clusterId); - } - - clusterInfo.setName(txtClusterName.getText()); - - clusterInfo.setSecurityLevel((int) comboSecurityLevel.getData(comboSecurityLevel.getText())); - - clusterInfo.setLifeTimeLimit(Integer.parseInt(txtLifeTimeLimit.getText())); - clusterInfo.setClusterRecyclingKillProblemProcesses(btnClusterRecyclingKillProblemProcesses.getSelection()); - - if (server.isFifteenOrOlderAgentVersion()) // 8.3.15+ - clusterInfo.setClusterRecyclingKillByMemoryWithDump(btnClusterRecyclingKillByMemoryWithDump.getSelection()); - else { - clusterInfo.setMaxMemorySize(Integer.parseInt(txtMaxMemorySize.getText())); - clusterInfo.setMaxMemoryTimeLimit(Integer.parseInt(txtMaxMemoryTimeLimit.getText())); - clusterInfo.setClusterRecyclingErrorsCountThreshold(Integer.parseInt(txtClusterRecyclingErrorsCountThreshold.getText())); - } - - clusterInfo.setExpirationTimeout(Integer.parseInt(txtExpirationTimeout.getText())); - clusterInfo.setSessionFaultToleranceLevel(Integer.parseInt(txtSessionFaultToleranceLevel.getText())); - clusterInfo.setLoadBalancingMode((int) comboLoadBalancingMode.getData(comboLoadBalancingMode.getText())); - - - try { - if (server.regCluster(clusterInfo)) - return true; - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - } - return false; - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button buttonOK = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - buttonOK.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (saveNewClusterProperties()) - close(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - - Button buttonApply = createButton(parent, IDialogConstants.PROCEED_ID, Messages.getString("Dialogs.Apply"), false); //$NON-NLS-1$ - buttonApply.setEnabled(clusterId != null); - buttonApply.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - saveNewClusterProperties(); - } - }); - Button buttonReset = createButton(parent, IDialogConstants.RETRY_ID, Messages.getString("Dialogs.Reset"), false); //$NON-NLS-1$ - buttonReset.setText(Messages.getString("Dialogs.Reset")); //$NON-NLS-1$ - buttonReset.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - initServerProperties(); - } - }); - Button buttonResetToProf = createButton(parent, IDialogConstants.RETRY_ID, Messages.getString("Dialogs.ResetToPROF"), false); //$NON-NLS-1$ - buttonResetToProf.addMouseTrackListener(new MouseTrackAdapter() { - @Override - public void mouseEnter(MouseEvent e) { - comboLoadBalancingMode.setBackground(SWTResourceManager.getLightGreenColor()); - } - @Override - public void mouseExit(MouseEvent e) { - comboLoadBalancingMode.setBackground(SWTResourceManager.getWhiteColor()); - } - }); - buttonResetToProf.setText(Messages.getString("Dialogs.ResetToPROF")); //$NON-NLS-1$ - buttonResetToProf.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - resetToProf(); - } - }); - - } + + private UUID clusterId; + private Server server; + + private Button btnClusterRecyclingKillProblemProcesses; + private Text txtClusterName; + private Text txtComputerName; + private Text txtIpPort; + private Combo comboSecurityLevel; + private Text txtLifeTimeLimit; + private Text txtMaxMemorySize; + private Text txtMaxMemoryTimeLimit; + private Text txtClusterRecyclingErrorsCountThreshold; + private Text txtExpirationTimeout; + private Text txtSessionFaultToleranceLevel; + private Combo comboLoadBalancingMode; + private Button btnClusterRecyclingKillByMemoryWithDump; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server + * @param clusterId - cluster ID + */ + public CreateEditClusterDialog(Shell parentShell, Server server, UUID clusterId) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.server = server; + this.clusterId = clusterId; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.makeColumnsEqualWidth = true; + gridLayout.marginWidth = 10; + gridLayout.marginHeight = 12; + gridLayout.numColumns = 2; + + Label lblClusterName = new Label(container, SWT.NONE); + lblClusterName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblClusterName.setText(Messages.getString("ClusterDialog.ClusterName")); //$NON-NLS-1$ + + txtClusterName = new Text(container, SWT.BORDER); + txtClusterName.setToolTipText(Messages.getString("ClusterDialog.ClusterName")); + GridData gdtxtClusterName = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtClusterName.widthHint = 200; + txtClusterName.setLayoutData(gdtxtClusterName); + + Label lblComputerName = new Label(container, SWT.NONE); + lblComputerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblComputerName.setText(Messages.getString("ClusterDialog.ComputerName")); //$NON-NLS-1$ + + txtComputerName = new Text(container, SWT.BORDER); + txtComputerName.setToolTipText(Messages.getString("ClusterDialog.ComputerName")); + GridData gdtxtComputerName = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtComputerName.widthHint = 200; + txtComputerName.setLayoutData(gdtxtComputerName); + + Label lblIpPort = new Label(container, SWT.NONE); + lblIpPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblIpPort.setText(Messages.getString("ClusterDialog.IPPort")); //$NON-NLS-1$ + + txtIpPort = new Text(container, SWT.BORDER); + txtIpPort.setToolTipText(Messages.getString("ClusterDialog.IPPort")); + GridData gdtxtIpPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtIpPort.widthHint = 200; + txtIpPort.setLayoutData(gdtxtIpPort); + + Label lblSecurityLevel = new Label(container, SWT.NONE); + lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + + comboSecurityLevel = new Combo(container, SWT.READ_ONLY); + comboSecurityLevel.setVisibleItemCount(3); + comboSecurityLevel.setTouchEnabled(true); + comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); + GridData gdcomboSecurityLevel = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdcomboSecurityLevel.widthHint = 200; + comboSecurityLevel.setLayoutData(gdcomboSecurityLevel); + + comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ + comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ + comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ + comboSecurityLevel.select(0); + + Group groupWorkProcessesParams = new Group(container, SWT.NONE); + groupWorkProcessesParams.setText( + Messages.getString("ClusterDialog.RestartWorkProcesses")); //$NON-NLS-1$ + GridLayout glgroupWorkProcessesParams = new GridLayout(2, true); + glgroupWorkProcessesParams.verticalSpacing = 8; + groupWorkProcessesParams.setLayout(glgroupWorkProcessesParams); + groupWorkProcessesParams.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); + + Label lblLifeTimeLimit = new Label(groupWorkProcessesParams, SWT.NONE); + lblLifeTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblLifeTimeLimit.setText(Messages.getString("ClusterDialog.RestartInterval")); //$NON-NLS-1$ + + txtLifeTimeLimit = new Text(groupWorkProcessesParams, SWT.BORDER); + GridData gdtxtLifeTimeLimit = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdtxtLifeTimeLimit.widthHint = 200; + txtLifeTimeLimit.setLayoutData(gdtxtLifeTimeLimit); + txtLifeTimeLimit.setToolTipText( + Messages.getString("ClusterDialog.RestartInterval")); //$NON-NLS-1$ + + Label lblMaxMemorySize = new Label(groupWorkProcessesParams, SWT.NONE); + lblMaxMemorySize.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblMaxMemorySize.setText( + Messages.getString("ClusterDialog.AllowedAmountOfMemoryWithLineBreak")); //$NON-NLS-1$ + + txtMaxMemorySize = new Text(groupWorkProcessesParams, SWT.BORDER); + GridData gdtxtMaxMemorySize = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdtxtMaxMemorySize.widthHint = 200; + txtMaxMemorySize.setLayoutData(gdtxtMaxMemorySize); + txtMaxMemorySize.setToolTipText( + Messages.getString("ClusterDialog.AllowedAmountOfMemory")); //$NON-NLS-1$ + + Label lblMaxMemoryTimeLimit = new Label(groupWorkProcessesParams, SWT.WRAP); + lblMaxMemoryTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, true, 1, 1)); + lblMaxMemoryTimeLimit.setText( + Messages.getString( + "ClusterDialog.IntervalExceedingAllowedAmountOfMemoryWithLineBreak")); //$NON-NLS-1$ + + txtMaxMemoryTimeLimit = new Text(groupWorkProcessesParams, SWT.BORDER); + GridData gdtxtMaxMemoryTimeLimit = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdtxtMaxMemoryTimeLimit.widthHint = 200; + txtMaxMemoryTimeLimit.setLayoutData(gdtxtMaxMemoryTimeLimit); + txtMaxMemoryTimeLimit.setToolTipText( + Messages.getString("ClusterDialog.IntervalExceedingAllowedAmountOfMemory")); //$NON-NLS-1$ + + Label lblAcceptableDeviationOfNumberOfServerErrors = + new Label(groupWorkProcessesParams, SWT.WRAP); + lblAcceptableDeviationOfNumberOfServerErrors.setLayoutData( + new GridData(SWT.RIGHT, SWT.FILL, false, true, 1, 1)); + lblAcceptableDeviationOfNumberOfServerErrors.setText( + Messages.getString( + "ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrorsWithLineBreak")); //$NON-NLS-1$ + + txtClusterRecyclingErrorsCountThreshold = new Text(groupWorkProcessesParams, SWT.BORDER); + GridData gdtxtClusterRecyclingErrorsCountThreshold = + new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdtxtClusterRecyclingErrorsCountThreshold.widthHint = 200; + txtClusterRecyclingErrorsCountThreshold.setLayoutData( + gdtxtClusterRecyclingErrorsCountThreshold); + txtClusterRecyclingErrorsCountThreshold.setToolTipText( + Messages.getString( + "ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors")); //$NON-NLS-1$ + + btnClusterRecyclingKillProblemProcesses = new Button(groupWorkProcessesParams, SWT.CHECK); + btnClusterRecyclingKillProblemProcesses.setLayoutData( + new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1)); + btnClusterRecyclingKillProblemProcesses.setText( + Messages.getString("ClusterDialog.ForceShutdownOfProblematicProcesses")); //$NON-NLS-1$ + + btnClusterRecyclingKillByMemoryWithDump = new Button(groupWorkProcessesParams, SWT.CHECK); + btnClusterRecyclingKillByMemoryWithDump.setLayoutData( + new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1)); + btnClusterRecyclingKillByMemoryWithDump.setText( + Messages.getString("ClusterDialog.ClusterRecyclingKillByMemoryWithDump")); //$NON-NLS-1$ + + Label lblExpirationTimeout = new Label(container, SWT.NONE); + lblExpirationTimeout.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblExpirationTimeout.setText( + Messages.getString("ClusterDialog.ShutDownProcessesStopAfterSecond")); //$NON-NLS-1$ + + txtExpirationTimeout = new Text(container, SWT.BORDER); + txtExpirationTimeout.setToolTipText( + Messages.getString("ClusterDialog.ShutDownProcessesStopAfter")); + GridData gdtxtExpirationTimeout = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtExpirationTimeout.widthHint = 200; + txtExpirationTimeout.setLayoutData(gdtxtExpirationTimeout); + + Label lblSessionFaultToleranceLevel = new Label(container, SWT.NONE); + lblSessionFaultToleranceLevel.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSessionFaultToleranceLevel.setText( + Messages.getString("ClusterDialog.FaultToleranceLevel")); //$NON-NLS-1$ + + txtSessionFaultToleranceLevel = new Text(container, SWT.BORDER); + txtSessionFaultToleranceLevel.setToolTipText( + Messages.getString("ClusterDialog.FaultToleranceLevel")); + GridData gdtxtSessionFaultToleranceLevel = + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtSessionFaultToleranceLevel.widthHint = 200; + txtSessionFaultToleranceLevel.setLayoutData(gdtxtSessionFaultToleranceLevel); + + Label lblLoadBalancingMode = new Label(container, SWT.NONE); + lblLoadBalancingMode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblLoadBalancingMode.setText( + Messages.getString("ClusterDialog.LoadBalancingMode")); //$NON-NLS-1$ + + comboLoadBalancingMode = new Combo(container, SWT.READ_ONLY); + comboLoadBalancingMode.setVisibleItemCount(2); + comboLoadBalancingMode.setToolTipText(Messages.getString("ClusterDialog.LoadBalancingMode")); + GridData gdcomboLoadBalancingMode = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdcomboLoadBalancingMode.widthHint = 200; + comboLoadBalancingMode.setLayoutData(gdcomboLoadBalancingMode); + + comboLoadBalancingMode.add(Messages.getString("Dialogs.PerformancePriority")); //$NON-NLS-1$ + comboLoadBalancingMode.setData( + Messages.getString("Dialogs.PerformancePriority"), 0); //$NON-NLS-1$ + comboLoadBalancingMode.add(Messages.getString("Dialogs.MemoryPriority")); //$NON-NLS-1$ + comboLoadBalancingMode.setData(Messages.getString("Dialogs.MemoryPriority"), 1); //$NON-NLS-1$ + comboLoadBalancingMode.select(0); + + initServerProperties(); + + return container; + } + + private void initServerProperties() { + IClusterInfo clusterInfo; + + if (clusterId != null) { + clusterInfo = server.getClusterInfo(clusterId); + + txtClusterName.setText(clusterInfo.getName()); + txtComputerName.setText(clusterInfo.getHostName()); + } else { + clusterInfo = new ClusterInfo(); + + txtClusterName.setText(""); //$NON-NLS-1$ + txtComputerName.setText(""); //$NON-NLS-1$ + } + + txtIpPort.setText(Integer.toString(clusterInfo.getMainPort())); + comboSecurityLevel.select(clusterInfo.getSecurityLevel()); + + txtLifeTimeLimit.setText(Integer.toString(clusterInfo.getLifeTimeLimit())); + txtMaxMemorySize.setText(Integer.toString(clusterInfo.getMaxMemorySize())); // 8.3.15- + txtMaxMemoryTimeLimit.setText(Integer.toString(clusterInfo.getMaxMemoryTimeLimit())); // 8.3.15- + txtClusterRecyclingErrorsCountThreshold.setText( + Integer.toString(clusterInfo.getClusterRecyclingErrorsCountThreshold())); // 8.3.15- + btnClusterRecyclingKillProblemProcesses.setSelection( + clusterInfo.isClusterRecyclingKillProblemProcesses()); + btnClusterRecyclingKillByMemoryWithDump.setSelection( + clusterInfo.isClusterRecyclingKillByMemoryWithDump()); // 8.3.15+ + + txtExpirationTimeout.setText(Integer.toString(clusterInfo.getExpirationTimeout())); + txtSessionFaultToleranceLevel.setText( + Integer.toString(clusterInfo.getSessionFaultToleranceLevel())); + comboLoadBalancingMode.select(clusterInfo.getLoadBalancingMode()); + + if (server.isFifteenOrMoreAgentVersion()) { // 8.3.15+ + txtMaxMemorySize.setEditable(false); + txtMaxMemoryTimeLimit.setEditable(false); + txtClusterRecyclingErrorsCountThreshold.setEditable(false); + + txtMaxMemorySize.setToolTipText( + Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + txtMaxMemoryTimeLimit.setToolTipText( + Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + txtClusterRecyclingErrorsCountThreshold.setToolTipText( + Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + } else { + btnClusterRecyclingKillByMemoryWithDump.setEnabled(false); + + btnClusterRecyclingKillByMemoryWithDump.setToolTipText( + Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ + } + + // У уже созданного кластера запрещено менять хост и порт + if (clusterId != null) { + txtComputerName.setEditable(false); + txtIpPort.setEditable(false); + } + } + + private void resetToProf() { + comboLoadBalancingMode.select(0); + } + + private boolean checkVariablesFromControls() { + + var existsError = false; + + List checksTextControls = new ArrayList<>(); + checksTextControls.add(txtClusterName); + checksTextControls.add(txtComputerName); + checksTextControls.add(txtIpPort); + + for (Text control : checksTextControls) { + if (control.getText().isBlank()) { + control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + existsError = true; + } else { + control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + } + } + + List checksIntControls = new ArrayList<>(); + checksIntControls.add(txtIpPort); + checksIntControls.add(txtLifeTimeLimit); + checksIntControls.add(txtMaxMemorySize); + checksIntControls.add(txtMaxMemoryTimeLimit); + checksIntControls.add(txtClusterRecyclingErrorsCountThreshold); + checksIntControls.add(txtExpirationTimeout); + checksIntControls.add(txtSessionFaultToleranceLevel); + + for (Text control : checksIntControls) { + try { + Integer.parseInt(control.getText()); + control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + } catch (Exception e) { + control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + existsError = true; + } + } + + return existsError; + } + + private boolean saveNewClusterProperties() { + if (checkVariablesFromControls()) { + return false; + } + + IClusterInfo clusterInfo; + + if (clusterId == null) { + clusterInfo = new ClusterInfo(); + + clusterInfo.setHostName(txtComputerName.getText()); + clusterInfo.setMainPort(Integer.parseInt(txtIpPort.getText())); + } else { + clusterInfo = server.getClusterInfo(clusterId); + } + + clusterInfo.setName(txtClusterName.getText()); + + clusterInfo.setSecurityLevel((int) comboSecurityLevel.getData(comboSecurityLevel.getText())); + + clusterInfo.setLifeTimeLimit(Integer.parseInt(txtLifeTimeLimit.getText())); + clusterInfo.setClusterRecyclingKillProblemProcesses( + btnClusterRecyclingKillProblemProcesses.getSelection()); + + if (server.isFifteenOrMoreAgentVersion()) { // 8.3.15+ + clusterInfo.setClusterRecyclingKillByMemoryWithDump( + btnClusterRecyclingKillByMemoryWithDump.getSelection()); + } else { + clusterInfo.setMaxMemorySize(Integer.parseInt(txtMaxMemorySize.getText())); + clusterInfo.setMaxMemoryTimeLimit(Integer.parseInt(txtMaxMemoryTimeLimit.getText())); + clusterInfo.setClusterRecyclingErrorsCountThreshold( + Integer.parseInt(txtClusterRecyclingErrorsCountThreshold.getText())); + } + + clusterInfo.setExpirationTimeout(Integer.parseInt(txtExpirationTimeout.getText())); + clusterInfo.setSessionFaultToleranceLevel( + Integer.parseInt(txtSessionFaultToleranceLevel.getText())); + clusterInfo.setLoadBalancingMode( + (int) comboLoadBalancingMode.getData(comboLoadBalancingMode.getText())); + + try { + if (server.regCluster(clusterInfo)) { + return true; + } + } catch (Exception excp) { + var messageBox = new MessageBox(getParentShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + } + return false; + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button buttonOk = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + buttonOk.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (saveNewClusterProperties()) { + close(); + } + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + + Button buttonApply = + createButton( + parent, + IDialogConstants.PROCEED_ID, + Messages.getString("Dialogs.Apply"), //$NON-NLS-1$ + false); + buttonApply.setEnabled(clusterId != null); + buttonApply.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + saveNewClusterProperties(); + } + }); + Button buttonReset = + createButton( + parent, + IDialogConstants.RETRY_ID, + Messages.getString("Dialogs.Reset"), //$NON-NLS-1$ + false); + buttonReset.setText(Messages.getString("Dialogs.Reset")); //$NON-NLS-1$ + buttonReset.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + initServerProperties(); + } + }); + Button buttonResetToProf = + createButton( + parent, + IDialogConstants.RETRY_ID, + Messages.getString("Dialogs.ResetToPROF"), //$NON-NLS-1$ + false); + buttonResetToProf.addMouseTrackListener( + new MouseTrackAdapter() { + @Override + public void mouseEnter(MouseEvent e) { + comboLoadBalancingMode.setBackground(SWTResourceManager.getLightGreenColor()); + } + + @Override + public void mouseExit(MouseEvent e) { + comboLoadBalancingMode.setBackground(SWTResourceManager.getWhiteColor()); + } + }); + buttonResetToProf.setText(Messages.getString("Dialogs.ResetToPROF")); //$NON-NLS-1$ + buttonResetToProf.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + resetToProf(); + } + }); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java index 88318b5..8e4e830 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -29,378 +28,400 @@ import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; - import ru.yanygin.clusterAdminLibrary.ClusterProvider; import ru.yanygin.clusterAdminLibrary.Server; +/** Dialog for create and edit Server parameters. */ public class CreateEditServerDialog extends Dialog { - - private Server serverParams; - private boolean rasOnSameHost; - - private Text txtRASHost; - private Text txtRasPort; - - private Text txtAgentHost; - private Text txtAgentPort; - private Text txtLocalRasPort; - private Combo comboV8Version; - - private Button btnAutoconnect; - private Text txtAgentUser; - private Text txtAgentPasswors; - private Table tableCredentials; - private Button radioUseRemoteRAS; - private Button radioUseLocalRAS; - private Button btnSaveCredentials; - private Text txtDescription; - - /** - * Create the dialog. - * - * @param parentShell - * @param serverParams - */ - public CreateEditServerDialog(Shell parentShell, Server serverParams) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM); - - // найти способ установить заголовок окна -// parentShell.setText("Parameters of the central server 1C:Enterprise"); - - this.serverParams = serverParams; - } - - /** - * Create contents of the dialog. - * - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.marginHeight = 0; - gridLayout.marginWidth = 0; - - TabFolder tabFolder = new TabFolder(container, SWT.NONE); - - TabItem tabConnect = new TabItem(tabFolder, SWT.NONE); - tabConnect.setText(Messages.getString("ServerDialog.ConnectParameters")); //$NON-NLS-1$ - - Composite connectContainer = new Composite(tabFolder, SWT.NONE); - tabConnect.setControl(connectContainer); - GridLayout glconnectContainer = new GridLayout(2, false); - connectContainer.setLayout(glconnectContainer); - - Composite composite = new Composite(connectContainer, SWT.NONE); - composite.setLayout(new GridLayout(2, false)); - composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); - - Label lblDescription = new Label(composite, SWT.NONE); - lblDescription.setText(Messages.getString("ServerDialog.Description")); //$NON-NLS-1$ - - txtDescription = new Text(composite, SWT.BORDER); - txtDescription.setToolTipText(Messages.getString("ServerDialog.Description")); //$NON-NLS-1$ - txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - btnAutoconnect = new Button(connectContainer, SWT.CHECK); - GridData gdbtnAutoconnect = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdbtnAutoconnect.horizontalIndent = 5; - btnAutoconnect.setLayoutData(gdbtnAutoconnect); - btnAutoconnect.setText(Messages.getString("ServerDialog.AutoconnectAtStartup")); //$NON-NLS-1$ - new Label(connectContainer, SWT.NONE); - - radioUseRemoteRAS = new Button(connectContainer, SWT.RADIO); - GridData gdradioUseRemoteRAS = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdradioUseRemoteRAS.horizontalIndent = 5; - radioUseRemoteRAS.setLayoutData(gdradioUseRemoteRAS); - radioUseRemoteRAS.setSelection(true); - radioUseRemoteRAS.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - setEnabledRasGroupParameters(); - } - }); - radioUseRemoteRAS.setBounds(0, 0, 90, 16); - radioUseRemoteRAS.setText(Messages.getString("ServerDialog.UseRemoteRAS")); //$NON-NLS-1$ - - radioUseLocalRAS = new Button(connectContainer, SWT.RADIO); - GridData gdradioUseLocalRAS = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdradioUseLocalRAS.horizontalIndent = 5; - radioUseLocalRAS.setLayoutData(gdradioUseLocalRAS); - radioUseLocalRAS.setBounds(0, 0, 90, 16); - radioUseLocalRAS.setText(Messages.getString("ServerDialog.UseLocalRAS")); //$NON-NLS-1$ - - Group grpRemoteRasParameters = new Group(connectContainer, SWT.NONE); - grpRemoteRasParameters.setText(Messages.getString("ServerDialog.RemoteRASParameters")); //$NON-NLS-1$ - grpRemoteRasParameters.setLayout(new GridLayout(2, false)); - - Label lblRASHost = new Label(grpRemoteRasParameters, SWT.NONE); - lblRASHost.setText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - Label lblRasPort = new Label(grpRemoteRasParameters, SWT.NONE); - lblRasPort.setSize(46, 15); - lblRasPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - txtRASHost = new Text(grpRemoteRasParameters, SWT.BORDER); - txtRASHost.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - if (rasOnSameHost) - txtAgentHost.setText(((Text)e.widget).getText()); - - checkRasOnSameHost(); - } - }); - GridData gdtxtRASHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdtxtRASHost.widthHint = 200; - txtRASHost.setLayoutData(gdtxtRASHost); - txtRASHost.setToolTipText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - txtRasPort = new Text(grpRemoteRasParameters, SWT.BORDER); - GridData gdtxtRasPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtRasPort.widthHint = 50; - txtRasPort.setLayoutData(gdtxtRasPort); - txtRasPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - Group grpLocalRasParameters = new Group(connectContainer, SWT.NONE); - grpLocalRasParameters.setSize(417, 90); - grpLocalRasParameters.setText(Messages.getString("ServerDialog.LocalRASParameters")); //$NON-NLS-1$ - grpLocalRasParameters.setLayout(new GridLayout(2, false)); - - Label lblV8Version = new Label(grpLocalRasParameters, SWT.NONE); - lblV8Version.setSize(124, 15); - lblV8Version.setText(Messages.getString("ServerDialog.V8Version")); //$NON-NLS-1$ - - Label lblLocalRasPort = new Label(grpLocalRasParameters, SWT.NONE); - lblLocalRasPort.setSize(77, 15); - lblLocalRasPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - comboV8Version = new Combo(grpLocalRasParameters, SWT.READ_ONLY); - GridData gdcomboV8Version = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdcomboV8Version.widthHint = 140; - comboV8Version.setLayoutData(gdcomboV8Version); - comboV8Version.setSize(389, 21); - comboV8Version.setToolTipText(Messages.getString("ServerDialog.V8Version")); //$NON-NLS-1$ - - txtLocalRasPort = new Text(grpLocalRasParameters, SWT.BORDER); - GridData gdtxtLocalRasPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); - gdtxtLocalRasPort.widthHint = 50; - txtLocalRasPort.setLayoutData(gdtxtLocalRasPort); - txtLocalRasPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - Group grpRagentParameters = new Group(connectContainer, SWT.NONE); - grpRagentParameters.setText(Messages.getString("ServerDialog.AgentParameters")); //$NON-NLS-1$ - grpRagentParameters.setLayout(new GridLayout(2, false)); - - Label lblAgentHost = new Label(grpRagentParameters, SWT.NONE); - lblAgentHost.setText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - Label lblAgentPort = new Label(grpRagentParameters, SWT.NONE); - lblAgentPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - txtAgentHost = new Text(grpRagentParameters, SWT.BORDER); - txtAgentHost.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - checkRasOnSameHost(); - } - }); - GridData gdtxtAgentHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdtxtAgentHost.widthHint = 200; - txtAgentHost.setLayoutData(gdtxtAgentHost); - txtAgentHost.setToolTipText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - txtAgentPort = new Text(grpRagentParameters, SWT.BORDER); - GridData gdtxtAgentPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtAgentPort.widthHint = 50; - txtAgentPort.setLayoutData(gdtxtAgentPort); - txtAgentPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - new Label(connectContainer, SWT.NONE); - - TabItem tabCredentials = new TabItem(tabFolder, SWT.NONE); - tabCredentials.setText(Messages.getString("ServerDialog.Credentials")); //$NON-NLS-1$ - - Composite credentialsContainer = new Composite(tabFolder, SWT.NONE); - tabCredentials.setControl(credentialsContainer); - credentialsContainer.setLayout(new GridLayout(1, false)); - - btnSaveCredentials = new Button(credentialsContainer, SWT.CHECK); - btnSaveCredentials.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - btnSaveCredentials.setSize(155, 16); - btnSaveCredentials.setText(Messages.getString("ServerDialog.SaveCredentials")); //$NON-NLS-1$ - - Group grpCentralServerCredential = new Group(credentialsContainer, SWT.NONE); - grpCentralServerCredential.setText(Messages.getString("ServerDialog.CentralServerAdminstrator")); //$NON-NLS-1$ - grpCentralServerCredential.setLayout(new GridLayout(4, false)); - GridData gdgrpCentralServerCredential = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); - gdgrpCentralServerCredential.verticalIndent = 5; - grpCentralServerCredential.setLayoutData(gdgrpCentralServerCredential); - - Label lblAgentUser = new Label(grpCentralServerCredential, SWT.NONE); - lblAgentUser.setSize(23, 15); - lblAgentUser.setText(Messages.getString("ServerDialog.User")); //$NON-NLS-1$ - - txtAgentUser = new Text(grpCentralServerCredential, SWT.BORDER); - GridData gdtxtAgentUser = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtAgentUser.widthHint = 200; - txtAgentUser.setLayoutData(gdtxtAgentUser); - txtAgentUser.setSize(76, 21); - txtAgentUser.setToolTipText(Messages.getString("ServerDialog.User")); //$NON-NLS-1$ - - Label lblAgentPwd = new Label(grpCentralServerCredential, SWT.NONE); - lblAgentPwd.setSize(50, 15); - lblAgentPwd.setText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ - - txtAgentPasswors = new Text(grpCentralServerCredential, SWT.BORDER | SWT.PASSWORD); - GridData gdtxtAgentPasswors = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtAgentPasswors.widthHint = 100; - txtAgentPasswors.setLayoutData(gdtxtAgentPasswors); - txtAgentPasswors.setSize(76, 21); - txtAgentPasswors.setToolTipText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ - - tableCredentials = new Table(credentialsContainer, SWT.BORDER | SWT.FULL_SELECTION); - GridData gdtableCredentials = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); - gdtableCredentials.heightHint = 183; - gdtableCredentials.verticalIndent = 5; - tableCredentials.setLayoutData(gdtableCredentials); - tableCredentials.setHeaderVisible(true); - tableCredentials.setLinesVisible(true); - - TableColumn tblclmnType = new TableColumn(tableCredentials, SWT.NONE); - tblclmnType.setWidth(60); - tblclmnType.setText(Messages.getString("ServerDialog.Type")); //$NON-NLS-1$ - - TableColumn tblclmnName = new TableColumn(tableCredentials, SWT.NONE); - tblclmnName.setWidth(160); - tblclmnName.setText(Messages.getString("ServerDialog.Name")); //$NON-NLS-1$ - - TableColumn tblclmnID = new TableColumn(tableCredentials, SWT.NONE); - tblclmnID.setWidth(100); - tblclmnID.setText(Messages.getString("ServerDialog.ID")); //$NON-NLS-1$ - - TableColumn tblclmnUsername = new TableColumn(tableCredentials, SWT.NONE); - tblclmnUsername.setWidth(100); - tblclmnUsername.setText(Messages.getString("ServerDialog.Username")); //$NON-NLS-1$ - - TableColumn tblclmnPassword = new TableColumn(tableCredentials, SWT.NONE); - tblclmnPassword.setWidth(100); - tblclmnPassword.setText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ - new Label(container, SWT.NONE); - - initServerProperties(); - checkRasOnSameHost(); - setEnabledRasGroupParameters(); - - return container; - } - - private void initServerProperties() { - if (serverParams != null) { - this.txtDescription.setText(serverParams.description); - - this.txtRASHost.setText(serverParams.rasHost); - this.txtRasPort.setText(serverParams.getRasPortAsString()); - - this.txtAgentHost.setText(serverParams.agentHost); - this.txtAgentPort.setText(serverParams.getAgentPortAsString()); - - this.radioUseRemoteRAS.setSelection(!serverParams.useLocalRas); - this.radioUseLocalRAS.setSelection(serverParams.useLocalRas); - List installedV8Versions = new ArrayList<>(); - ClusterProvider.getInstalledV8Versions().forEach( (desc, path) -> { - installedV8Versions.add(desc); - }); - installedV8Versions.sort(String.CASE_INSENSITIVE_ORDER); - comboV8Version.setItems(installedV8Versions.toArray(new String[0])); - - this.comboV8Version.setText(serverParams.localRasV8version); - - this.txtLocalRasPort.setText(serverParams.getLocalRasPortAsString()); - - this.btnAutoconnect.setSelection(serverParams.autoconnect); - this.btnSaveCredentials.setSelection(serverParams.saveCredentials); - this.txtAgentUser.setText(serverParams.agentUserName); - this.txtAgentPasswors.setText(serverParams.agentPassword); - - serverParams.credentialsClustersCashe.forEach((uuid, userPass) -> { - - TableItem credentialItem = new TableItem(this.tableCredentials, SWT.NONE); - - String[] itemText = { "cluster", userPass[2], // clusterName //$NON-NLS-1$ - uuid.toString(), userPass[0], // username - userPass[1] }; // pass - - credentialItem.setText(itemText); - credentialItem.setData("UUID", uuid); //$NON-NLS-1$ - credentialItem.setChecked(false); - - }); - } - } - - private boolean saveNewServerProperties() { - try { - serverParams.description = txtDescription.getText(); - - Map credentialsClustersCashe = new HashMap<>(); - if (btnSaveCredentials.getSelection()) { - TableItem[] credentials = tableCredentials.getItems(); - for (TableItem credential : credentials) { - UUID uuid = (UUID) credential.getData("UUID"); //$NON-NLS-1$ - credentialsClustersCashe.put(uuid, new String[] { credential.getText(3), credential.getText(4), credential.getText(1) }); - } - } - - serverParams.setServerNewProperties( - txtAgentHost.getText(), - Integer.parseInt(txtAgentPort.getText()), - txtRASHost.getText(), - Integer.parseInt(txtRasPort.getText()), - !radioUseRemoteRAS.getSelection(), - Integer.parseInt(txtLocalRasPort.getText()), - comboV8Version.getText(), - btnAutoconnect.getSelection(), - btnSaveCredentials.getSelection(), - txtAgentUser.getText(), - txtAgentPasswors.getText(), - credentialsClustersCashe); - return true; - - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - } - - /** - * Create contents of the button bar. - * - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (saveNewServerProperties()) - close(); - } - }); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } - - private void checkRasOnSameHost() { - rasOnSameHost = txtAgentHost.getText().equals(txtRASHost.getText()); - } - - private void setEnabledRasGroupParameters() { - txtRASHost.setEnabled(radioUseRemoteRAS.getSelection()); - txtRasPort.setEnabled(radioUseRemoteRAS.getSelection()); - comboV8Version.setEnabled(!radioUseRemoteRAS.getSelection()); - txtLocalRasPort.setEnabled(!radioUseRemoteRAS.getSelection()); - } + + private Server serverParams; + private boolean rasOnSameHost; + + private Text txtRasHost; + private Text txtRasPort; + + private Text txtAgentHost; + private Text txtAgentPort; + private Text txtLocalRasPort; + private Combo comboV8Version; + + private Button btnAutoconnect; + private Text txtAgentUser; + private Text txtAgentPasswors; + private Table tableCredentials; + private Button radioUseRemoteRas; + private Button radioUseLocalRas; + private Button btnSaveCredentials; + private Text txtDescription; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param serverParams - server params + */ + public CreateEditServerDialog(Shell parentShell, Server serverParams) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM); + + // найти способ установить заголовок окна + // parentShell.setText("Parameters of the central server 1C:Enterprise"); + + this.serverParams = serverParams; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.marginHeight = 0; + gridLayout.marginWidth = 0; + + TabFolder tabFolder = new TabFolder(container, SWT.NONE); + + TabItem tabConnect = new TabItem(tabFolder, SWT.NONE); + tabConnect.setText(Messages.getString("ServerDialog.ConnectParameters")); //$NON-NLS-1$ + + Composite connectContainer = new Composite(tabFolder, SWT.NONE); + tabConnect.setControl(connectContainer); + GridLayout glconnectContainer = new GridLayout(2, false); + connectContainer.setLayout(glconnectContainer); + + Composite composite = new Composite(connectContainer, SWT.NONE); + composite.setLayout(new GridLayout(2, false)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); + + Label lblDescription = new Label(composite, SWT.NONE); + lblDescription.setText(Messages.getString("ServerDialog.Description")); //$NON-NLS-1$ + + txtDescription = new Text(composite, SWT.BORDER); + txtDescription.setToolTipText(Messages.getString("ServerDialog.Description")); //$NON-NLS-1$ + txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + btnAutoconnect = new Button(connectContainer, SWT.CHECK); + GridData gdbtnAutoconnect = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdbtnAutoconnect.horizontalIndent = 5; + btnAutoconnect.setLayoutData(gdbtnAutoconnect); + btnAutoconnect.setText(Messages.getString("ServerDialog.AutoconnectAtStartup")); //$NON-NLS-1$ + new Label(connectContainer, SWT.NONE); + + radioUseRemoteRas = new Button(connectContainer, SWT.RADIO); + GridData gdradioUseRemoteRas = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdradioUseRemoteRas.horizontalIndent = 5; + radioUseRemoteRas.setLayoutData(gdradioUseRemoteRas); + radioUseRemoteRas.setSelection(true); + radioUseRemoteRas.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + setEnabledRasGroupParameters(); + } + }); + radioUseRemoteRas.setBounds(0, 0, 90, 16); + radioUseRemoteRas.setText(Messages.getString("ServerDialog.UseRemoteRAS")); //$NON-NLS-1$ + + radioUseLocalRas = new Button(connectContainer, SWT.RADIO); + GridData gdradioUseLocalRas = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdradioUseLocalRas.horizontalIndent = 5; + radioUseLocalRas.setLayoutData(gdradioUseLocalRas); + radioUseLocalRas.setBounds(0, 0, 90, 16); + radioUseLocalRas.setText(Messages.getString("ServerDialog.UseLocalRAS")); //$NON-NLS-1$ + + Group grpRemoteRasParameters = new Group(connectContainer, SWT.NONE); + grpRemoteRasParameters.setText( + Messages.getString("ServerDialog.RemoteRASParameters")); //$NON-NLS-1$ + grpRemoteRasParameters.setLayout(new GridLayout(2, false)); + + Label lblRasHost = new Label(grpRemoteRasParameters, SWT.NONE); + lblRasHost.setText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ + + Label lblRasPort = new Label(grpRemoteRasParameters, SWT.NONE); + lblRasPort.setSize(46, 15); + lblRasPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ + + txtRasHost = new Text(grpRemoteRasParameters, SWT.BORDER); + txtRasHost.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (rasOnSameHost) { + txtAgentHost.setText(((Text) e.widget).getText()); + } + checkRasOnSameHost(); + } + }); + GridData gdtxtRasHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdtxtRasHost.widthHint = 200; + txtRasHost.setLayoutData(gdtxtRasHost); + txtRasHost.setToolTipText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ + + txtRasPort = new Text(grpRemoteRasParameters, SWT.BORDER); + GridData gdtxtRasPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtRasPort.widthHint = 50; + txtRasPort.setLayoutData(gdtxtRasPort); + txtRasPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ + + Group grpLocalRasParameters = new Group(connectContainer, SWT.NONE); + grpLocalRasParameters.setSize(417, 90); + grpLocalRasParameters.setText( + Messages.getString("ServerDialog.LocalRASParameters")); //$NON-NLS-1$ + grpLocalRasParameters.setLayout(new GridLayout(2, false)); + + Label lblV8Version = new Label(grpLocalRasParameters, SWT.NONE); + lblV8Version.setSize(124, 15); + lblV8Version.setText(Messages.getString("ServerDialog.V8Version")); //$NON-NLS-1$ + + Label lblLocalRasPort = new Label(grpLocalRasParameters, SWT.NONE); + lblLocalRasPort.setSize(77, 15); + lblLocalRasPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ + + comboV8Version = new Combo(grpLocalRasParameters, SWT.READ_ONLY); + GridData gdcomboV8Version = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdcomboV8Version.widthHint = 140; + comboV8Version.setLayoutData(gdcomboV8Version); + comboV8Version.setSize(389, 21); + comboV8Version.setToolTipText(Messages.getString("ServerDialog.V8Version")); //$NON-NLS-1$ + + txtLocalRasPort = new Text(grpLocalRasParameters, SWT.BORDER); + GridData gdtxtLocalRasPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); + gdtxtLocalRasPort.widthHint = 50; + txtLocalRasPort.setLayoutData(gdtxtLocalRasPort); + txtLocalRasPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ + + Group grpRagentParameters = new Group(connectContainer, SWT.NONE); + grpRagentParameters.setText(Messages.getString("ServerDialog.AgentParameters")); //$NON-NLS-1$ + grpRagentParameters.setLayout(new GridLayout(2, false)); + + Label lblAgentHost = new Label(grpRagentParameters, SWT.NONE); + lblAgentHost.setText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ + + Label lblAgentPort = new Label(grpRagentParameters, SWT.NONE); + lblAgentPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ + + txtAgentHost = new Text(grpRagentParameters, SWT.BORDER); + txtAgentHost.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + checkRasOnSameHost(); + } + }); + GridData gdtxtAgentHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdtxtAgentHost.widthHint = 200; + txtAgentHost.setLayoutData(gdtxtAgentHost); + txtAgentHost.setToolTipText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ + + txtAgentPort = new Text(grpRagentParameters, SWT.BORDER); + GridData gdtxtAgentPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtAgentPort.widthHint = 50; + txtAgentPort.setLayoutData(gdtxtAgentPort); + txtAgentPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ + new Label(connectContainer, SWT.NONE); + + TabItem tabCredentials = new TabItem(tabFolder, SWT.NONE); + tabCredentials.setText(Messages.getString("ServerDialog.Credentials")); //$NON-NLS-1$ + + Composite credentialsContainer = new Composite(tabFolder, SWT.NONE); + tabCredentials.setControl(credentialsContainer); + credentialsContainer.setLayout(new GridLayout(1, false)); + + btnSaveCredentials = new Button(credentialsContainer, SWT.CHECK); + btnSaveCredentials.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + btnSaveCredentials.setSize(155, 16); + btnSaveCredentials.setText(Messages.getString("ServerDialog.SaveCredentials")); //$NON-NLS-1$ + + Group grpCentralServerCredential = new Group(credentialsContainer, SWT.NONE); + grpCentralServerCredential.setText( + Messages.getString("ServerDialog.CentralServerAdminstrator")); //$NON-NLS-1$ + grpCentralServerCredential.setLayout(new GridLayout(4, false)); + GridData gdgrpCentralServerCredential = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); + gdgrpCentralServerCredential.verticalIndent = 5; + grpCentralServerCredential.setLayoutData(gdgrpCentralServerCredential); + + Label lblAgentUser = new Label(grpCentralServerCredential, SWT.NONE); + lblAgentUser.setSize(23, 15); + lblAgentUser.setText(Messages.getString("ServerDialog.User")); //$NON-NLS-1$ + + txtAgentUser = new Text(grpCentralServerCredential, SWT.BORDER); + GridData gdtxtAgentUser = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtAgentUser.widthHint = 200; + txtAgentUser.setLayoutData(gdtxtAgentUser); + txtAgentUser.setSize(76, 21); + txtAgentUser.setToolTipText(Messages.getString("ServerDialog.User")); //$NON-NLS-1$ + + Label lblAgentPwd = new Label(grpCentralServerCredential, SWT.NONE); + lblAgentPwd.setSize(50, 15); + lblAgentPwd.setText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ + + txtAgentPasswors = new Text(grpCentralServerCredential, SWT.BORDER | SWT.PASSWORD); + GridData gdtxtAgentPasswors = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtAgentPasswors.widthHint = 100; + txtAgentPasswors.setLayoutData(gdtxtAgentPasswors); + txtAgentPasswors.setSize(76, 21); + txtAgentPasswors.setToolTipText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ + + tableCredentials = new Table(credentialsContainer, SWT.BORDER | SWT.FULL_SELECTION); + GridData gdtableCredentials = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); + gdtableCredentials.heightHint = 183; + gdtableCredentials.verticalIndent = 5; + tableCredentials.setLayoutData(gdtableCredentials); + tableCredentials.setHeaderVisible(true); + tableCredentials.setLinesVisible(true); + + TableColumn tblclmnType = new TableColumn(tableCredentials, SWT.NONE); + tblclmnType.setWidth(60); + tblclmnType.setText(Messages.getString("ServerDialog.Type")); //$NON-NLS-1$ + + TableColumn tblclmnName = new TableColumn(tableCredentials, SWT.NONE); + tblclmnName.setWidth(160); + tblclmnName.setText(Messages.getString("ServerDialog.Name")); //$NON-NLS-1$ + + TableColumn tblclmnId = new TableColumn(tableCredentials, SWT.NONE); + tblclmnId.setWidth(100); + tblclmnId.setText(Messages.getString("ServerDialog.ID")); //$NON-NLS-1$ + + TableColumn tblclmnUsername = new TableColumn(tableCredentials, SWT.NONE); + tblclmnUsername.setWidth(100); + tblclmnUsername.setText(Messages.getString("ServerDialog.Username")); //$NON-NLS-1$ + + TableColumn tblclmnPassword = new TableColumn(tableCredentials, SWT.NONE); + tblclmnPassword.setWidth(100); + tblclmnPassword.setText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ + new Label(container, SWT.NONE); + + initServerProperties(); + checkRasOnSameHost(); + setEnabledRasGroupParameters(); + + return container; + } + + private void initServerProperties() { + if (serverParams != null) { + this.txtDescription.setText(serverParams.getDescription()); + + this.txtRasHost.setText(serverParams.getRasHost()); + this.txtRasPort.setText(serverParams.getRasPortAsString()); + + this.txtAgentHost.setText(serverParams.getAgentHost()); + this.txtAgentPort.setText(serverParams.getAgentPortAsString()); + + this.radioUseRemoteRas.setSelection(!serverParams.getUseLocalRas()); + this.radioUseLocalRas.setSelection(serverParams.getUseLocalRas()); + List installedV8Versions = new ArrayList<>(); + ClusterProvider.getInstalledV8Versions() + .forEach( + (desc, path) -> { + installedV8Versions.add(desc); + }); + installedV8Versions.sort(String.CASE_INSENSITIVE_ORDER); + comboV8Version.setItems(installedV8Versions.toArray(new String[0])); + + this.comboV8Version.setText(serverParams.getLocalRasV8version()); + + this.txtLocalRasPort.setText(serverParams.getLocalRasPortAsString()); + + this.btnAutoconnect.setSelection(serverParams.getAutoconnect()); + this.btnSaveCredentials.setSelection(serverParams.getSaveCredentials()); + this.txtAgentUser.setText(serverParams.getAgentUserName()); + this.txtAgentPasswors.setText(serverParams.getAgentPassword()); + + serverParams.getCredentials().forEach( + (uuid, userPass) -> { + TableItem credentialItem = new TableItem(this.tableCredentials, SWT.NONE); + + String[] itemText = { + "cluster", //$NON-NLS-1$ + userPass[2], // clusterName + uuid.toString(), + userPass[0], // username + userPass[1] // pass + }; + + credentialItem.setText(itemText); + credentialItem.setData("UUID", uuid); //$NON-NLS-1$ + credentialItem.setChecked(false); + }); + } + } + + private boolean saveNewServerProperties() { + try { + serverParams.setDescription(txtDescription.getText()); + + Map credentialsClustersCashe = new HashMap<>(); + if (btnSaveCredentials.getSelection()) { + TableItem[] credentials = tableCredentials.getItems(); + for (TableItem credential : credentials) { + UUID uuid = (UUID) credential.getData("UUID"); //$NON-NLS-1$ + credentialsClustersCashe.put( + uuid, + new String[] {credential.getText(3), credential.getText(4), credential.getText(1)}); + } + } + + serverParams.setAgentHost(txtAgentHost.getText()); + serverParams.setAgentPort(Integer.parseInt(txtAgentPort.getText())); + serverParams.setRasHost(txtRasHost.getText()); + serverParams.setRasPort(Integer.parseInt(txtRasPort.getText())); + serverParams.setUseLocalRas(!radioUseRemoteRas.getSelection()); + serverParams.setLocalRasPort(Integer.parseInt(txtLocalRasPort.getText())); + + serverParams.setLocalRasV8version(comboV8Version.getText()); + serverParams.setAutoconnect(btnAutoconnect.getSelection()); + serverParams.setSaveCredentials(btnSaveCredentials.getSelection()); + serverParams.setAgentUserName(txtAgentUser.getText()); + serverParams.setAgentPassword(txtAgentPasswors.getText()); + serverParams.setCredentials(credentialsClustersCashe); + + // LOGGER.info("Set new properties for server <{}>", serverParams.getServerKey()); // + //$NON-NLS-1$ + + return true; + + } catch (Exception excp) { + var messageBox = new MessageBox(getParentShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (saveNewServerProperties()) { + close(); + } + } + }); + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } + + private void checkRasOnSameHost() { + rasOnSameHost = txtAgentHost.getText().equals(txtRasHost.getText()); + } + + private void setEnabledRasGroupParameters() { + txtRasHost.setEnabled(radioUseRemoteRas.getSelection()); + txtRasPort.setEnabled(radioUseRemoteRas.getSelection()); + comboV8Version.setEnabled(!radioUseRemoteRas.getSelection()); + txtLocalRasPort.setEnabled(!radioUseRemoteRas.getSelection()); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java index 5ce2319..ff0d72b 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java @@ -1,9 +1,12 @@ package ru.yanygin.clusterAdminLibraryUI; +import com._1c.v8.ibis.admin.IPortRangeInfo; +import com._1c.v8.ibis.admin.IWorkingServerInfo; +import com._1c.v8.ibis.admin.PortRangeInfo; +import com._1c.v8.ibis.admin.WorkingServerInfo; import java.util.ArrayList; import java.util.List; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -13,7 +16,6 @@ import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -25,540 +27,648 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.SWTResourceManager; - -import com._1c.v8.ibis.admin.IPortRangeInfo; -import com._1c.v8.ibis.admin.IWorkingServerInfo; -import com._1c.v8.ibis.admin.PortRangeInfo; -import com._1c.v8.ibis.admin.WorkingServerInfo; - import ru.yanygin.clusterAdminLibrary.Server; +/** Dialog for create and edit Working Server parameters. */ public class CreateEditWorkingServerDialog extends Dialog { - - private UUID clusterId; - private UUID workingServerId; - private Server server; - - private Button btnIsDedicatedManagers; - private Text txtServerName; - private Text txtComputerName; - private Text txtIPPort; - private Text txtPortRange; - - private Text txtInfoBasesPerWorkingProcessLimit; - private Text txtConnectionsPerWorkingProcessLimit; - private Text txtIPPortMainManager; - private Button btnIsMainServer; - private Text txtWorkingProcessMemoryLimit; - private Text txtSafeCallMemoryLimit; - private Text txtCriticalProcessesTotalMemory; - private Text txtTemporaryAllowedProcessesTotalMemory; - private Text txtTemporaryAllowedProcessesTotalMemoryTimeLimit; - private Text txtSafeWorkingProcessesMemoryLimit; - private Label lblSafeWorkingProcessesMemoryLimitMb; - private Label lblSafeCallMemoryLimitMb; - private Label lblWorkingProcessMemoryLimitMb; - private Label lblCriticalProcessesTotalMemoryMb; - private Label lblTemporaryAllowedProcessesTotalMemoryMb; - private Label lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin; - - public UUID getNewWorkingServerId() { - return workingServerId; - } - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public CreateEditWorkingServerDialog(Shell parentShell, Server server, UUID clusterId, UUID workingServerId) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.server = server; - this.clusterId = clusterId; - this.workingServerId = workingServerId; - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.marginWidth = 10; - gridLayout.marginHeight = 12; - gridLayout.numColumns = 3; - - Label lblServerName = new Label(container, SWT.NONE); - lblServerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerName.setText(Messages.getString("WorkingServerDialog.ServerName")); //$NON-NLS-1$ - - txtServerName = new Text(container, SWT.BORDER); - txtServerName.setToolTipText(Messages.getString("WorkingServerDialog.ServerName")); //$NON-NLS-1$ - txtServerName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - new Label(container, SWT.NONE); - - Label lblComputerName = new Label(container, SWT.NONE); - lblComputerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblComputerName.setText(Messages.getString("WorkingServerDialog.ComputerName")); //$NON-NLS-1$ - - txtComputerName = new Text(container, SWT.BORDER); - txtComputerName.setToolTipText(Messages.getString("WorkingServerDialog.ComputerName")); //$NON-NLS-1$ - txtComputerName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - new Label(container, SWT.NONE); - - Label lblIPPort = new Label(container, SWT.NONE); - lblIPPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblIPPort.setText(Messages.getString("WorkingServerDialog.IPPort")); //$NON-NLS-1$ - - txtIPPort = new Text(container, SWT.BORDER); - txtIPPort.setToolTipText(Messages.getString("WorkingServerDialog.IPPort")); //$NON-NLS-1$ - txtIPPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - new Label(container, SWT.NONE); - - Label lblPortRange = new Label(container, SWT.NONE); - lblPortRange.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPortRange.setText(Messages.getString("WorkingServerDialog.PortRange")); //$NON-NLS-1$ - - txtPortRange = new Text(container, SWT.BORDER); - txtPortRange.setToolTipText(Messages.getString("WorkingServerDialog.PortRange")); //$NON-NLS-1$ - txtPortRange.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - new Label(container, SWT.NONE); - - Label lblSafeWorkingProcessesMemoryLimit = new Label(container, SWT.NONE); - lblSafeWorkingProcessesMemoryLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSafeWorkingProcessesMemoryLimit.setText(Messages.getString("WorkingServerDialog.SafeWorkingProcessesMemoryLimit")); //$NON-NLS-1$ - - txtSafeWorkingProcessesMemoryLimit = new Text(container, SWT.BORDER); - txtSafeWorkingProcessesMemoryLimit.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - lblSafeWorkingProcessesMemoryLimitMb.setText(convertToMegabytes((Text)e.widget)); - } - }); - - txtSafeWorkingProcessesMemoryLimit.setToolTipText(Messages.getString("WorkingServerDialog.SafeWorkingProcessesMemoryLimit")); //$NON-NLS-1$ - txtSafeWorkingProcessesMemoryLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - - lblSafeWorkingProcessesMemoryLimitMb = new Label(container, SWT.NONE); - GridData gdlblSafeWorkingProcessesMemoryLimitMb = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdlblSafeWorkingProcessesMemoryLimitMb.minimumHeight = 8; - lblSafeWorkingProcessesMemoryLimitMb.setLayoutData(gdlblSafeWorkingProcessesMemoryLimitMb); - - Label lblSafeCallMemoryLimit = new Label(container, SWT.NONE); - lblSafeCallMemoryLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSafeCallMemoryLimit.setText(Messages.getString("WorkingServerDialog.SafeCallMemoryLimit")); //$NON-NLS-1$ - - txtSafeCallMemoryLimit = new Text(container, SWT.BORDER); - txtSafeCallMemoryLimit.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - lblSafeCallMemoryLimitMb.setText(convertToMegabytes((Text)e.widget)); - } - }); - txtSafeCallMemoryLimit.setToolTipText(Messages.getString("WorkingServerDialog.SafeCallMemoryLimit")); //$NON-NLS-1$ - txtSafeCallMemoryLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - - lblSafeCallMemoryLimitMb = new Label(container, SWT.NONE); - GridData gdlblSafeCallMemoryLimitMb = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdlblSafeCallMemoryLimitMb.minimumHeight = 8; - lblSafeCallMemoryLimitMb.setLayoutData(gdlblSafeCallMemoryLimitMb); - - Label lblWorkingProcessMemoryLimit = new Label(container, SWT.NONE); - lblWorkingProcessMemoryLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1)); - lblWorkingProcessMemoryLimit.setText(Messages.getString("WorkingServerDialog.WorkingProcessMemoryLimit")); //$NON-NLS-1$ - - txtWorkingProcessMemoryLimit = new Text(container, SWT.BORDER); - txtWorkingProcessMemoryLimit.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - lblWorkingProcessMemoryLimitMb.setText(convertToMegabytes((Text)e.widget)); - } - }); - txtWorkingProcessMemoryLimit.setToolTipText(Messages.getString("WorkingServerDialog.WorkingProcessMemoryLimit")); //$NON-NLS-1$ - txtWorkingProcessMemoryLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - lblWorkingProcessMemoryLimitMb = new Label(container, SWT.NONE); - GridData gdlblWorkingProcessMemoryLimitMb = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); - gdlblWorkingProcessMemoryLimitMb.minimumHeight = 8; - lblWorkingProcessMemoryLimitMb.setLayoutData(gdlblWorkingProcessMemoryLimitMb); - - Label lblCriticalProcessesTotalMemory = new Label(container, SWT.NONE); - lblCriticalProcessesTotalMemory.setText(Messages.getString("WorkingServerDialog.CriticalProcessesTotalMemory")); //$NON-NLS-1$ - lblCriticalProcessesTotalMemory.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - - txtCriticalProcessesTotalMemory = new Text(container, SWT.BORDER); - txtCriticalProcessesTotalMemory.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - lblCriticalProcessesTotalMemoryMb.setText(convertToMegabytes((Text)e.widget)); - } - }); - txtCriticalProcessesTotalMemory.setToolTipText(Messages.getString("WorkingServerDialog.CriticalProcessesTotalMemory")); //$NON-NLS-1$ - txtCriticalProcessesTotalMemory.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - - lblCriticalProcessesTotalMemoryMb = new Label(container, SWT.NONE); - GridData gdlblCriticalProcessesTotalMemoryMb = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdlblCriticalProcessesTotalMemoryMb.minimumHeight = 8; - lblCriticalProcessesTotalMemoryMb.setLayoutData(gdlblCriticalProcessesTotalMemoryMb); - - Label lblTemporaryAllowedProcessesTotalMemory = new Label(container, SWT.NONE); - lblTemporaryAllowedProcessesTotalMemory.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false, 1, 1)); - lblTemporaryAllowedProcessesTotalMemory.setText(Messages.getString("WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryLabel")); //$NON-NLS-1$ - - txtTemporaryAllowedProcessesTotalMemory = new Text(container, SWT.BORDER); - txtTemporaryAllowedProcessesTotalMemory.addModifyListener(new ModifyListener() { //NOSONAR - public void modifyText(ModifyEvent e) { - lblTemporaryAllowedProcessesTotalMemoryMb.setText(convertToMegabytes((Text)e.widget)); - } - }); - txtTemporaryAllowedProcessesTotalMemory.setToolTipText(Messages.getString("WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryToolTip")); //$NON-NLS-1$ - txtTemporaryAllowedProcessesTotalMemory.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - - lblTemporaryAllowedProcessesTotalMemoryMb = new Label(container, SWT.NONE); - GridData gdlblTemporaryAllowedProcessesTotalMemoryMb = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdlblTemporaryAllowedProcessesTotalMemoryMb.minimumHeight = 8; - lblTemporaryAllowedProcessesTotalMemoryMb.setLayoutData(gdlblTemporaryAllowedProcessesTotalMemoryMb); - - Label lblTemporaryAllowedProcessesTotalMemoryTimeLimit = new Label(container, SWT.NONE); - lblTemporaryAllowedProcessesTotalMemoryTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblTemporaryAllowedProcessesTotalMemoryTimeLimit.setText(Messages.getString("WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitLabel")); //$NON-NLS-1$ - - txtTemporaryAllowedProcessesTotalMemoryTimeLimit = new Text(container, SWT.BORDER); - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin.setText(convertToMinutes((Text)e.widget)); - } - }); - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText(Messages.getString("WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitToolTip")); //$NON-NLS-1$ - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - - lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin = new Label(container, SWT.NONE); - GridData gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin.minimumHeight = 8; - lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin.setLayoutData(gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin); - - Group groupWorkProcessesParams = new Group(container, SWT.NONE); - groupWorkProcessesParams.setText(Messages.getString("WorkingServerDialog.WorkingProcessesParameters")); //$NON-NLS-1$ - GridLayout glgroupWorkProcessesParams = new GridLayout(2, true); - glgroupWorkProcessesParams.verticalSpacing = 8; - groupWorkProcessesParams.setLayout(glgroupWorkProcessesParams); - GridData gdgroupWorkProcessesParams = new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1); - gdgroupWorkProcessesParams.widthHint = 424; - groupWorkProcessesParams.setLayoutData(gdgroupWorkProcessesParams); - - Label lblInfoBasesPerWorkingProcessLimit = new Label(groupWorkProcessesParams, SWT.NONE); - lblInfoBasesPerWorkingProcessLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfoBasesPerWorkingProcessLimit.setText(Messages.getString("WorkingServerDialog.InfobasesPerWorkingProcessLimit")); //$NON-NLS-1$ - lblInfoBasesPerWorkingProcessLimit.setBounds(0, 0, 35, 15); - - txtInfoBasesPerWorkingProcessLimit = new Text(groupWorkProcessesParams, SWT.BORDER); - txtInfoBasesPerWorkingProcessLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - txtInfoBasesPerWorkingProcessLimit.setToolTipText(Messages.getString("WorkingServerDialog.InfobasesPerWorkingProcessLimit")); //$NON-NLS-1$ - txtInfoBasesPerWorkingProcessLimit.setBounds(0, 0, 76, 21); - - Label lblConnectionsPerWorkingProcessLimit = new Label(groupWorkProcessesParams, SWT.WRAP); - lblConnectionsPerWorkingProcessLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1)); - lblConnectionsPerWorkingProcessLimit.setText(Messages.getString("WorkingServerDialog.ConnectionsPerWorkingProcessLimit")); //$NON-NLS-1$ - lblConnectionsPerWorkingProcessLimit.setBounds(0, 0, 35, 15); - - txtConnectionsPerWorkingProcessLimit = new Text(groupWorkProcessesParams, SWT.BORDER); - txtConnectionsPerWorkingProcessLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - txtConnectionsPerWorkingProcessLimit.setToolTipText(Messages.getString("WorkingServerDialog.ConnectionsPerWorkingProcessLimit")); //$NON-NLS-1$ - txtConnectionsPerWorkingProcessLimit.setBounds(0, 0, 76, 21); - new Label(container, SWT.NONE); - - Label lblIPPortMainManager = new Label(container, SWT.NONE); - lblIPPortMainManager.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblIPPortMainManager.setText(Messages.getString("WorkingServerDialog.IPPortMainClusterManager")); //$NON-NLS-1$ - - txtIPPortMainManager = new Text(container, SWT.BORDER); - txtIPPortMainManager.setToolTipText(Messages.getString("WorkingServerDialog.IPPortMainClusterManager")); //$NON-NLS-1$ - txtIPPortMainManager.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - new Label(container, SWT.NONE); - new Label(container, SWT.NONE); - - btnIsDedicatedManagers = new Button(container, SWT.CHECK); - btnIsDedicatedManagers.setText(Messages.getString("WorkingServerDialog.IsDedicatedManagers")); //$NON-NLS-1$ - new Label(container, SWT.NONE); - new Label(container, SWT.NONE); - - btnIsMainServer = new Button(container, SWT.CHECK); - btnIsMainServer.setText(Messages.getString("WorkingServerDialog.IsMainServer")); //$NON-NLS-1$ - new Label(container, SWT.NONE); - new Label(container, SWT.NONE); - new Label(container, SWT.NONE); - - initServerProperties(); - - return container; - } - - private void initServerProperties() { - IWorkingServerInfo serverInfo; - - if (workingServerId != null) { // Редактируем существующий рабочий сервер - serverInfo = server.getWorkingServerInfo(clusterId, workingServerId); - - txtServerName.setText(serverInfo.getName()); - txtComputerName.setText(serverInfo.getHostName()); - - IPortRangeInfo portRangesInfo = serverInfo.getPortRanges().get(0); - String portRanges = Integer.toString(portRangesInfo.getLowBound()).concat(":").concat(Integer.toString(portRangesInfo.getHighBound())); //$NON-NLS-1$ - txtPortRange.setText(portRanges); - - txtInfoBasesPerWorkingProcessLimit.setText(Integer.toString(serverInfo.getInfoBasesPerWorkingProcessLimit())); - txtConnectionsPerWorkingProcessLimit.setText(Integer.toString(serverInfo.getConnectionsPerWorkingProcessLimit())); - - } else { // Создаем новый рабочий сервер - serverInfo = new WorkingServerInfo(); - - txtServerName.setText(""); //$NON-NLS-1$ - txtPortRange.setText(""); //$NON-NLS-1$ - txtComputerName.setText(""); //$NON-NLS-1$ - - txtInfoBasesPerWorkingProcessLimit.setText("8"); //$NON-NLS-1$ - txtConnectionsPerWorkingProcessLimit.setText("128"); //$NON-NLS-1$ - } - - txtIPPort.setText(Integer.toString(serverInfo.getMainPort())); - - txtSafeWorkingProcessesMemoryLimit.setText(String.valueOf(serverInfo.getSafeWorkingProcessesMemoryLimit())); - txtSafeCallMemoryLimit.setText(String.valueOf(serverInfo.getSafeCallMemoryLimit())); - txtCriticalProcessesTotalMemory.setText(String.valueOf(serverInfo.getCriticalProcessesTotalMemory())); - txtTemporaryAllowedProcessesTotalMemory.setText(String.valueOf(serverInfo.getTemporaryAllowedProcessesTotalMemory())); - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setText(String.valueOf(serverInfo.getTemporaryAllowedProcessesTotalMemoryTimeLimit())); - txtWorkingProcessMemoryLimit.setText(String.valueOf(serverInfo.getWorkingProcessMemoryLimit())); - - txtIPPortMainManager.setText(Integer.toString(serverInfo.getClusterMainPort())); - btnIsDedicatedManagers.setSelection(serverInfo.isDedicatedManagers()); - btnIsMainServer.setSelection(serverInfo.isMainServer()); - - if (server.isFifteenOrOlderAgentVersion()) { // 8.3.15+ - txtSafeWorkingProcessesMemoryLimit.setEditable(false); - txtWorkingProcessMemoryLimit.setEditable(false); - - txtSafeWorkingProcessesMemoryLimit.setToolTipText(Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - txtWorkingProcessMemoryLimit.setToolTipText(Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - } else { // 8.3.15- - txtCriticalProcessesTotalMemory.setEditable(false); - txtTemporaryAllowedProcessesTotalMemory.setEditable(false); - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setEditable(false); - - txtCriticalProcessesTotalMemory.setToolTipText(Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ - txtTemporaryAllowedProcessesTotalMemory.setToolTipText(Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText(Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ - } - - if (workingServerId != null) { // У уже созданного кластера запрещено менять хост и порт - txtServerName.setEditable(false); - txtComputerName.setEditable(false); - txtIPPort.setEditable(false); - } else { - btnIsMainServer.setEnabled(false); // Почему новому серверу запрещено сразу ставить галочку Центральный сервер? - txtIPPortMainManager.setText(""); //$NON-NLS-1$ - } - txtIPPortMainManager.setEditable(false); - - } - - private void resetToProf() { - if (!server.isFifteenOrOlderAgentVersion()) { // 8.3.15- - txtSafeWorkingProcessesMemoryLimit.setText("0"); //$NON-NLS-1$ - txtWorkingProcessMemoryLimit.setText("0"); //$NON-NLS-1$ - } - txtSafeCallMemoryLimit.setText("0"); //$NON-NLS-1$ - txtInfoBasesPerWorkingProcessLimit.setText("8"); //$NON-NLS-1$ - } - - private boolean checkVariablesFromControls() { - - var existsError = false; - - List checksTextControls = new ArrayList<>(); - checksTextControls.add(txtServerName); - checksTextControls.add(txtComputerName); - checksTextControls.add(txtIPPort); - checksTextControls.add(txtPortRange); - - for (Text control : checksTextControls) { - if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getPinkColor()); - existsError = true; - } else { - control.setBackground(SWTResourceManager.getWhiteColor()); - } - } - - List checksIntControls = new ArrayList<>(); - checksIntControls.add(txtIPPort); - checksIntControls.add(txtInfoBasesPerWorkingProcessLimit); - checksIntControls.add(txtConnectionsPerWorkingProcessLimit); - - for (Text control : checksIntControls) { - try { - Integer.parseInt(control.getText()); - control.setBackground(SWTResourceManager.getWhiteColor()); - } catch (Exception e) { - control.setBackground(SWTResourceManager.getPinkColor()); - existsError = true; - } - } - - List checksLongControls = new ArrayList<>(); - checksLongControls.add(txtSafeCallMemoryLimit); - checksLongControls.add(txtCriticalProcessesTotalMemory); - checksLongControls.add(txtTemporaryAllowedProcessesTotalMemory); - checksLongControls.add(txtTemporaryAllowedProcessesTotalMemoryTimeLimit); - checksLongControls.add(txtSafeWorkingProcessesMemoryLimit); - checksLongControls.add(txtWorkingProcessMemoryLimit); - - for (Text control : checksLongControls) { - try { - Long.parseLong(control.getText()); - control.setBackground(SWTResourceManager.getWhiteColor()); - } catch (Exception e) { - control.setBackground(SWTResourceManager.getPinkColor()); - existsError = true; - } - } - - try { - String[] portRange = txtPortRange.getText().split(":"); //$NON-NLS-1$ - new PortRangeInfo(Integer.parseInt(portRange[1]), Integer.parseInt(portRange[0])); - txtPortRange.setBackground(SWTResourceManager.getWhiteColor()); - } catch (Exception e) { - txtPortRange.setBackground(SWTResourceManager.getPinkColor()); - existsError = true; - } - - return existsError; - } - - private boolean saveNewClusterProperties() { - if (checkVariablesFromControls()) - return false; - - IWorkingServerInfo workingServerInfo; - - if (workingServerId == null) { - workingServerInfo = new WorkingServerInfo(); - - workingServerInfo.setHostName(txtComputerName.getText()); - workingServerInfo.setMainPort(Integer.parseInt(txtIPPort.getText())); - } else { - workingServerInfo = server.getWorkingServerInfo(clusterId, workingServerId); - } - - String[] portRange = txtPortRange.getText().split(":"); //$NON-NLS-1$ - IPortRangeInfo portRangesInfo = new PortRangeInfo(Integer.parseInt(portRange[1]), Integer.parseInt(portRange[0])); - List portRangeList = new ArrayList<>(); - portRangeList.add(portRangesInfo); - workingServerInfo.setPortRanges(portRangeList); - - workingServerInfo.setInfoBasesPerWorkingProcessLimit(Integer.parseInt(txtInfoBasesPerWorkingProcessLimit.getText())); - workingServerInfo.setConnectionsPerWorkingProcessLimit(Integer.parseInt(txtConnectionsPerWorkingProcessLimit.getText())); - - workingServerInfo.setSafeCallMemoryLimit(Long.parseLong(txtSafeCallMemoryLimit.getText())); - - workingServerInfo.setDedicatedManagers(btnIsDedicatedManagers.getSelection()); - workingServerInfo.setMainServer(btnIsMainServer.getSelection()); - - if (server.isFifteenOrOlderAgentVersion()) { - workingServerInfo.setCriticalProcessesTotalMemory(Long.parseLong(txtCriticalProcessesTotalMemory.getText())); - workingServerInfo.setTemporaryAllowedProcessesTotalMemory(Long.parseLong(txtTemporaryAllowedProcessesTotalMemory.getText())); - workingServerInfo.setTemporaryAllowedProcessesTotalMemoryTimeLimit(Long.parseLong(txtTemporaryAllowedProcessesTotalMemoryTimeLimit.getText())); - } else { - workingServerInfo.setSafeWorkingProcessesMemoryLimit(Long.parseLong(txtSafeWorkingProcessesMemoryLimit.getText())); - workingServerInfo.setWorkingProcessMemoryLimit(Long.parseLong(txtWorkingProcessMemoryLimit.getText())); - } - - try { - if (server.regWorkingServer(clusterId, workingServerInfo, workingServerId == null)) { - workingServerId = workingServerInfo.getWorkingServerId(); - return true; - } - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - } - return false; - - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button buttonOK = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - buttonOK.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (saveNewClusterProperties()) - close(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - - Button buttonApply = createButton(parent, IDialogConstants.PROCEED_ID, Messages.getString("Dialogs.Apply"), false); //$NON-NLS-1$ - buttonApply.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - saveNewClusterProperties(); - } - }); - Button buttonReset = createButton(parent, IDialogConstants.RETRY_ID, Messages.getString("Dialogs.Reset"), false); //$NON-NLS-1$ - buttonReset.setText(Messages.getString("Dialogs.Reset")); //$NON-NLS-1$ - buttonReset.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - initServerProperties(); - } - }); - Button buttonResetToProf = createButton(parent, IDialogConstants.RETRY_ID, Messages.getString("Dialogs.ResetToPROF"), false); //$NON-NLS-1$ - buttonResetToProf.addMouseTrackListener(new MouseTrackAdapter() { - @Override - public void mouseEnter(MouseEvent e) { - txtSafeCallMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); - txtSafeWorkingProcessesMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); - txtWorkingProcessMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); - txtInfoBasesPerWorkingProcessLimit.setBackground(SWTResourceManager.getLightGreenColor()); - } - @Override - public void mouseExit(MouseEvent e) { - txtSafeCallMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); - txtSafeWorkingProcessesMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); - txtWorkingProcessMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); - txtInfoBasesPerWorkingProcessLimit.setBackground(SWTResourceManager.getWhiteColor()); - } - }); - buttonResetToProf.setText(Messages.getString("Dialogs.ResetToPROF")); //$NON-NLS-1$ - buttonResetToProf.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - resetToProf(); - } - }); - - } - - private String convertToMegabytes(Text textControl) { - long inMb = Long.parseLong(textControl.getText()) / (1024*1024); - return Long.toString(inMb).concat(Messages.getString("WorkingServerDialog.Megabytes")); //$NON-NLS-1$ - - } - - private String convertToMinutes(Text textControl) { - long inMb = Long.parseLong(textControl.getText()) / (60); - return Long.toString(inMb).concat(Messages.getString("WorkingServerDialog.Minutes")); //$NON-NLS-1$ - - } + private UUID clusterId; + private UUID workingServerId; + private Server server; + + private Button btnIsDedicatedManagers; + private Text txtServerName; + private Text txtComputerName; + private Text txtIpPort; + private Text txtPortRange; + + private Text txtInfoBasesPerWorkingProcessLimit; + private Text txtConnectionsPerWorkingProcessLimit; + private Text txtIpPortMainManager; + private Button btnIsMainServer; + private Text txtWorkingProcessMemoryLimit; + private Text txtSafeCallMemoryLimit; + private Text txtCriticalProcessesTotalMemory; + private Text txtTemporaryAllowedProcessesTotalMemory; + private Text txtTemporaryAllowedProcessesTotalMemoryTimeLimit; + private Text txtSafeWorkingProcessesMemoryLimit; + private Label lblSafeWorkingProcessesMemoryLimitMb; + private Label lblSafeCallMemoryLimitMb; + private Label lblWorkingProcessMemoryLimitMb; + private Label lblCriticalProcessesTotalMemoryMb; + private Label lblTemporaryAllowedProcessesTotalMemoryMb; + private Label lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin; + + public UUID getNewWorkingServerId() { + return workingServerId; + } + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server + * @param clusterId - cluster ID + * @param workingServerId - working server ID + */ + public CreateEditWorkingServerDialog( + Shell parentShell, Server server, UUID clusterId, UUID workingServerId) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.server = server; + this.clusterId = clusterId; + this.workingServerId = workingServerId; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.marginWidth = 10; + gridLayout.marginHeight = 12; + gridLayout.numColumns = 3; + + Label lblServerName = new Label(container, SWT.NONE); + lblServerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblServerName.setText(Messages.getString("WorkingServerDialog.ServerName")); //$NON-NLS-1$ + + txtServerName = new Text(container, SWT.BORDER); + txtServerName.setToolTipText( + Messages.getString("WorkingServerDialog.ServerName")); //$NON-NLS-1$ + txtServerName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + new Label(container, SWT.NONE); + + Label lblComputerName = new Label(container, SWT.NONE); + lblComputerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblComputerName.setText(Messages.getString("WorkingServerDialog.ComputerName")); //$NON-NLS-1$ + + txtComputerName = new Text(container, SWT.BORDER); + txtComputerName.setToolTipText( + Messages.getString("WorkingServerDialog.ComputerName")); //$NON-NLS-1$ + txtComputerName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + new Label(container, SWT.NONE); + + Label lblIpPort = new Label(container, SWT.NONE); + lblIpPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblIpPort.setText(Messages.getString("WorkingServerDialog.IPPort")); //$NON-NLS-1$ + + txtIpPort = new Text(container, SWT.BORDER); + txtIpPort.setToolTipText(Messages.getString("WorkingServerDialog.IPPort")); //$NON-NLS-1$ + txtIpPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + new Label(container, SWT.NONE); + + Label lblPortRange = new Label(container, SWT.NONE); + lblPortRange.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblPortRange.setText(Messages.getString("WorkingServerDialog.PortRange")); //$NON-NLS-1$ + + txtPortRange = new Text(container, SWT.BORDER); + txtPortRange.setToolTipText(Messages.getString("WorkingServerDialog.PortRange")); //$NON-NLS-1$ + txtPortRange.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + new Label(container, SWT.NONE); + + Label lblSafeWorkingProcessesMemoryLimit = new Label(container, SWT.NONE); + lblSafeWorkingProcessesMemoryLimit.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSafeWorkingProcessesMemoryLimit.setText( + Messages.getString("WorkingServerDialog.SafeWorkingProcessesMemoryLimit")); //$NON-NLS-1$ + + txtSafeWorkingProcessesMemoryLimit = new Text(container, SWT.BORDER); + txtSafeWorkingProcessesMemoryLimit.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + lblSafeWorkingProcessesMemoryLimitMb.setText(convertToMegabytes((Text) e.widget)); + } + }); + + txtSafeWorkingProcessesMemoryLimit.setToolTipText( + Messages.getString("WorkingServerDialog.SafeWorkingProcessesMemoryLimit")); //$NON-NLS-1$ + txtSafeWorkingProcessesMemoryLimit.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + + lblSafeWorkingProcessesMemoryLimitMb = new Label(container, SWT.NONE); + GridData gdlblSafeWorkingProcessesMemoryLimitMb = + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdlblSafeWorkingProcessesMemoryLimitMb.minimumHeight = 8; + lblSafeWorkingProcessesMemoryLimitMb.setLayoutData(gdlblSafeWorkingProcessesMemoryLimitMb); + + Label lblSafeCallMemoryLimit = new Label(container, SWT.NONE); + lblSafeCallMemoryLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSafeCallMemoryLimit.setText( + Messages.getString("WorkingServerDialog.SafeCallMemoryLimit")); //$NON-NLS-1$ + + txtSafeCallMemoryLimit = new Text(container, SWT.BORDER); + txtSafeCallMemoryLimit.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + lblSafeCallMemoryLimitMb.setText(convertToMegabytes((Text) e.widget)); + } + }); + txtSafeCallMemoryLimit.setToolTipText( + Messages.getString("WorkingServerDialog.SafeCallMemoryLimit")); //$NON-NLS-1$ + txtSafeCallMemoryLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + + lblSafeCallMemoryLimitMb = new Label(container, SWT.NONE); + GridData gdlblSafeCallMemoryLimitMb = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdlblSafeCallMemoryLimitMb.minimumHeight = 8; + lblSafeCallMemoryLimitMb.setLayoutData(gdlblSafeCallMemoryLimitMb); + + Label lblWorkingProcessMemoryLimit = new Label(container, SWT.NONE); + lblWorkingProcessMemoryLimit.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1)); + lblWorkingProcessMemoryLimit.setText( + Messages.getString("WorkingServerDialog.WorkingProcessMemoryLimit")); //$NON-NLS-1$ + + txtWorkingProcessMemoryLimit = new Text(container, SWT.BORDER); + txtWorkingProcessMemoryLimit.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + lblWorkingProcessMemoryLimitMb.setText(convertToMegabytes((Text) e.widget)); + } + }); + txtWorkingProcessMemoryLimit.setToolTipText( + Messages.getString("WorkingServerDialog.WorkingProcessMemoryLimit")); //$NON-NLS-1$ + txtWorkingProcessMemoryLimit.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + lblWorkingProcessMemoryLimitMb = new Label(container, SWT.NONE); + GridData gdlblWorkingProcessMemoryLimitMb = + new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdlblWorkingProcessMemoryLimitMb.minimumHeight = 8; + lblWorkingProcessMemoryLimitMb.setLayoutData(gdlblWorkingProcessMemoryLimitMb); + + Label lblCriticalProcessesTotalMemory = new Label(container, SWT.NONE); + lblCriticalProcessesTotalMemory.setText( + Messages.getString("WorkingServerDialog.CriticalProcessesTotalMemory")); //$NON-NLS-1$ + lblCriticalProcessesTotalMemory.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + + txtCriticalProcessesTotalMemory = new Text(container, SWT.BORDER); + txtCriticalProcessesTotalMemory.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + lblCriticalProcessesTotalMemoryMb.setText(convertToMegabytes((Text) e.widget)); + } + }); + txtCriticalProcessesTotalMemory.setToolTipText( + Messages.getString("WorkingServerDialog.CriticalProcessesTotalMemory")); //$NON-NLS-1$ + txtCriticalProcessesTotalMemory.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + + lblCriticalProcessesTotalMemoryMb = new Label(container, SWT.NONE); + GridData gdlblCriticalProcessesTotalMemoryMb = + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdlblCriticalProcessesTotalMemoryMb.minimumHeight = 8; + lblCriticalProcessesTotalMemoryMb.setLayoutData(gdlblCriticalProcessesTotalMemoryMb); + + Label lblTemporaryAllowedProcessesTotalMemory = new Label(container, SWT.NONE); + lblTemporaryAllowedProcessesTotalMemory.setLayoutData( + new GridData(SWT.RIGHT, SWT.FILL, false, false, 1, 1)); + lblTemporaryAllowedProcessesTotalMemory.setText( + Messages.getString( + "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryLabel")); //$NON-NLS-1$ + + txtTemporaryAllowedProcessesTotalMemory = new Text(container, SWT.BORDER); + txtTemporaryAllowedProcessesTotalMemory.addModifyListener( + new ModifyListener() { // NOSONAR + @Override + public void modifyText(ModifyEvent e) { + lblTemporaryAllowedProcessesTotalMemoryMb.setText(convertToMegabytes((Text) e.widget)); + } + }); + txtTemporaryAllowedProcessesTotalMemory.setToolTipText( + Messages.getString( + "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryToolTip")); //$NON-NLS-1$ + txtTemporaryAllowedProcessesTotalMemory.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + + lblTemporaryAllowedProcessesTotalMemoryMb = new Label(container, SWT.NONE); + GridData gdlblTemporaryAllowedProcessesTotalMemoryMb = + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdlblTemporaryAllowedProcessesTotalMemoryMb.minimumHeight = 8; + lblTemporaryAllowedProcessesTotalMemoryMb.setLayoutData( + gdlblTemporaryAllowedProcessesTotalMemoryMb); + + Label lblTemporaryAllowedProcessesTotalMemoryTimeLimit = new Label(container, SWT.NONE); + lblTemporaryAllowedProcessesTotalMemoryTimeLimit.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblTemporaryAllowedProcessesTotalMemoryTimeLimit.setText( + Messages.getString( + "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitLabel")); //$NON-NLS-1$ + + txtTemporaryAllowedProcessesTotalMemoryTimeLimit = new Text(container, SWT.BORDER); + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin.setText( + convertToMinutes((Text) e.widget)); + } + }); + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText( + Messages.getString( + "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitToolTip")); //$NON-NLS-1$ + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + + lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin = new Label(container, SWT.NONE); + GridData gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin = + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin.minimumHeight = 8; + lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin.setLayoutData( + gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin); + + Group groupWorkProcessesParams = new Group(container, SWT.NONE); + groupWorkProcessesParams.setText( + Messages.getString("WorkingServerDialog.WorkingProcessesParameters")); //$NON-NLS-1$ + GridLayout glgroupWorkProcessesParams = new GridLayout(2, true); + glgroupWorkProcessesParams.verticalSpacing = 8; + groupWorkProcessesParams.setLayout(glgroupWorkProcessesParams); + GridData gdgroupWorkProcessesParams = new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1); + gdgroupWorkProcessesParams.widthHint = 424; + groupWorkProcessesParams.setLayoutData(gdgroupWorkProcessesParams); + + Label lblInfoBasesPerWorkingProcessLimit = new Label(groupWorkProcessesParams, SWT.NONE); + lblInfoBasesPerWorkingProcessLimit.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblInfoBasesPerWorkingProcessLimit.setText( + Messages.getString("WorkingServerDialog.InfobasesPerWorkingProcessLimit")); //$NON-NLS-1$ + lblInfoBasesPerWorkingProcessLimit.setBounds(0, 0, 35, 15); + + txtInfoBasesPerWorkingProcessLimit = new Text(groupWorkProcessesParams, SWT.BORDER); + txtInfoBasesPerWorkingProcessLimit.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + txtInfoBasesPerWorkingProcessLimit.setToolTipText( + Messages.getString("WorkingServerDialog.InfobasesPerWorkingProcessLimit")); //$NON-NLS-1$ + txtInfoBasesPerWorkingProcessLimit.setBounds(0, 0, 76, 21); + + Label lblConnectionsPerWorkingProcessLimit = new Label(groupWorkProcessesParams, SWT.WRAP); + lblConnectionsPerWorkingProcessLimit.setLayoutData( + new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1)); + lblConnectionsPerWorkingProcessLimit.setText( + Messages.getString("WorkingServerDialog.ConnectionsPerWorkingProcessLimit")); //$NON-NLS-1$ + lblConnectionsPerWorkingProcessLimit.setBounds(0, 0, 35, 15); + + txtConnectionsPerWorkingProcessLimit = new Text(groupWorkProcessesParams, SWT.BORDER); + txtConnectionsPerWorkingProcessLimit.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + txtConnectionsPerWorkingProcessLimit.setToolTipText( + Messages.getString("WorkingServerDialog.ConnectionsPerWorkingProcessLimit")); //$NON-NLS-1$ + txtConnectionsPerWorkingProcessLimit.setBounds(0, 0, 76, 21); + new Label(container, SWT.NONE); + + Label lblIpPortMainManager = new Label(container, SWT.NONE); + lblIpPortMainManager.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblIpPortMainManager.setText( + Messages.getString("WorkingServerDialog.IPPortMainClusterManager")); //$NON-NLS-1$ + + txtIpPortMainManager = new Text(container, SWT.BORDER); + txtIpPortMainManager.setToolTipText( + Messages.getString("WorkingServerDialog.IPPortMainClusterManager")); //$NON-NLS-1$ + txtIpPortMainManager.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + new Label(container, SWT.NONE); + new Label(container, SWT.NONE); + + btnIsDedicatedManagers = new Button(container, SWT.CHECK); + btnIsDedicatedManagers.setText( + Messages.getString("WorkingServerDialog.IsDedicatedManagers")); //$NON-NLS-1$ + new Label(container, SWT.NONE); + new Label(container, SWT.NONE); + + btnIsMainServer = new Button(container, SWT.CHECK); + btnIsMainServer.setText(Messages.getString("WorkingServerDialog.IsMainServer")); //$NON-NLS-1$ + new Label(container, SWT.NONE); + new Label(container, SWT.NONE); + new Label(container, SWT.NONE); + + initServerProperties(); + + return container; + } + + private void initServerProperties() { + IWorkingServerInfo serverInfo; + + if (workingServerId != null) { // Редактируем существующий рабочий сервер + serverInfo = server.getWorkingServerInfo(clusterId, workingServerId); + + txtServerName.setText(serverInfo.getName()); + txtComputerName.setText(serverInfo.getHostName()); + + IPortRangeInfo portRangesInfo = serverInfo.getPortRanges().get(0); + String portRanges = + Integer.toString(portRangesInfo.getLowBound()) + .concat(":") //$NON-NLS-1$ + .concat(Integer.toString(portRangesInfo.getHighBound())); + txtPortRange.setText(portRanges); + + txtInfoBasesPerWorkingProcessLimit.setText( + Integer.toString(serverInfo.getInfoBasesPerWorkingProcessLimit())); + txtConnectionsPerWorkingProcessLimit.setText( + Integer.toString(serverInfo.getConnectionsPerWorkingProcessLimit())); + + } else { // Создаем новый рабочий сервер + serverInfo = new WorkingServerInfo(); + + txtServerName.setText(""); //$NON-NLS-1$ + txtPortRange.setText(""); //$NON-NLS-1$ + txtComputerName.setText(""); //$NON-NLS-1$ + + txtInfoBasesPerWorkingProcessLimit.setText("8"); //$NON-NLS-1$ + txtConnectionsPerWorkingProcessLimit.setText("128"); //$NON-NLS-1$ + } + + txtIpPort.setText(Integer.toString(serverInfo.getMainPort())); + + txtSafeWorkingProcessesMemoryLimit.setText( + String.valueOf(serverInfo.getSafeWorkingProcessesMemoryLimit())); + txtSafeCallMemoryLimit.setText(String.valueOf(serverInfo.getSafeCallMemoryLimit())); + txtCriticalProcessesTotalMemory.setText( + String.valueOf(serverInfo.getCriticalProcessesTotalMemory())); + txtTemporaryAllowedProcessesTotalMemory.setText( + String.valueOf(serverInfo.getTemporaryAllowedProcessesTotalMemory())); + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setText( + String.valueOf(serverInfo.getTemporaryAllowedProcessesTotalMemoryTimeLimit())); + txtWorkingProcessMemoryLimit.setText(String.valueOf(serverInfo.getWorkingProcessMemoryLimit())); + + txtIpPortMainManager.setText(Integer.toString(serverInfo.getClusterMainPort())); + btnIsDedicatedManagers.setSelection(serverInfo.isDedicatedManagers()); + btnIsMainServer.setSelection(serverInfo.isMainServer()); + + if (server.isFifteenOrMoreAgentVersion()) { // 8.3.15+ + txtSafeWorkingProcessesMemoryLimit.setEditable(false); + txtWorkingProcessMemoryLimit.setEditable(false); + + txtSafeWorkingProcessesMemoryLimit.setToolTipText( + Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + txtWorkingProcessMemoryLimit.setToolTipText( + Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + } else { // 8.3.15- + txtCriticalProcessesTotalMemory.setEditable(false); + txtTemporaryAllowedProcessesTotalMemory.setEditable(false); + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setEditable(false); + + txtCriticalProcessesTotalMemory.setToolTipText( + Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ + txtTemporaryAllowedProcessesTotalMemory.setToolTipText( + Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText( + Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ + } + + if (workingServerId != null) { // У уже созданного кластера запрещено менять хост и порт + txtServerName.setEditable(false); + txtComputerName.setEditable(false); + txtIpPort.setEditable(false); + } else { + // Почему новому серверу запрещено сразу ставить галочку Центральный сервер? + btnIsMainServer.setEnabled(false); + txtIpPortMainManager.setText(""); //$NON-NLS-1$ + } + txtIpPortMainManager.setEditable(false); + } + + private void resetToProf() { + if (!server.isFifteenOrMoreAgentVersion()) { // 8.3.15- + txtSafeWorkingProcessesMemoryLimit.setText("0"); //$NON-NLS-1$ + txtWorkingProcessMemoryLimit.setText("0"); //$NON-NLS-1$ + } + txtSafeCallMemoryLimit.setText("0"); //$NON-NLS-1$ + txtInfoBasesPerWorkingProcessLimit.setText("8"); //$NON-NLS-1$ + } + + private boolean checkVariablesFromControls() { + + var existsError = false; + + List checksTextControls = new ArrayList<>(); + checksTextControls.add(txtServerName); + checksTextControls.add(txtComputerName); + checksTextControls.add(txtIpPort); + checksTextControls.add(txtPortRange); + + for (Text control : checksTextControls) { + if (control.getText().isBlank()) { + control.setBackground(SWTResourceManager.getPinkColor()); + existsError = true; + } else { + control.setBackground(SWTResourceManager.getWhiteColor()); + } + } + + List checksIntControls = new ArrayList<>(); + checksIntControls.add(txtIpPort); + checksIntControls.add(txtInfoBasesPerWorkingProcessLimit); + checksIntControls.add(txtConnectionsPerWorkingProcessLimit); + + for (Text control : checksIntControls) { + try { + Integer.parseInt(control.getText()); + control.setBackground(SWTResourceManager.getWhiteColor()); + } catch (Exception e) { + control.setBackground(SWTResourceManager.getPinkColor()); + existsError = true; + } + } + + List checksLongControls = new ArrayList<>(); + checksLongControls.add(txtSafeCallMemoryLimit); + checksLongControls.add(txtCriticalProcessesTotalMemory); + checksLongControls.add(txtTemporaryAllowedProcessesTotalMemory); + checksLongControls.add(txtTemporaryAllowedProcessesTotalMemoryTimeLimit); + checksLongControls.add(txtSafeWorkingProcessesMemoryLimit); + checksLongControls.add(txtWorkingProcessMemoryLimit); + + for (Text control : checksLongControls) { + try { + Long.parseLong(control.getText()); + control.setBackground(SWTResourceManager.getWhiteColor()); + } catch (Exception e) { + control.setBackground(SWTResourceManager.getPinkColor()); + existsError = true; + } + } + + try { + String[] portRange = txtPortRange.getText().split(":"); //$NON-NLS-1$ + new PortRangeInfo(Integer.parseInt(portRange[1]), Integer.parseInt(portRange[0])); + txtPortRange.setBackground(SWTResourceManager.getWhiteColor()); + } catch (Exception e) { + txtPortRange.setBackground(SWTResourceManager.getPinkColor()); + existsError = true; + } + + return existsError; + } + + private boolean saveNewClusterProperties() { + if (checkVariablesFromControls()) { + return false; + } + + IWorkingServerInfo workingServerInfo; + + if (workingServerId == null) { + workingServerInfo = new WorkingServerInfo(); + + workingServerInfo.setHostName(txtComputerName.getText()); + workingServerInfo.setMainPort(Integer.parseInt(txtIpPort.getText())); + } else { + workingServerInfo = server.getWorkingServerInfo(clusterId, workingServerId); + } + + String[] portRange = txtPortRange.getText().split(":"); //$NON-NLS-1$ + IPortRangeInfo portRangesInfo = + new PortRangeInfo(Integer.parseInt(portRange[1]), Integer.parseInt(portRange[0])); + List portRangeList = new ArrayList<>(); + portRangeList.add(portRangesInfo); + workingServerInfo.setPortRanges(portRangeList); + + workingServerInfo.setInfoBasesPerWorkingProcessLimit( + Integer.parseInt(txtInfoBasesPerWorkingProcessLimit.getText())); + workingServerInfo.setConnectionsPerWorkingProcessLimit( + Integer.parseInt(txtConnectionsPerWorkingProcessLimit.getText())); + + workingServerInfo.setSafeCallMemoryLimit(Long.parseLong(txtSafeCallMemoryLimit.getText())); + + workingServerInfo.setDedicatedManagers(btnIsDedicatedManagers.getSelection()); + workingServerInfo.setMainServer(btnIsMainServer.getSelection()); + + if (server.isFifteenOrMoreAgentVersion()) { + workingServerInfo.setCriticalProcessesTotalMemory( + Long.parseLong(txtCriticalProcessesTotalMemory.getText())); + workingServerInfo.setTemporaryAllowedProcessesTotalMemory( + Long.parseLong(txtTemporaryAllowedProcessesTotalMemory.getText())); + workingServerInfo.setTemporaryAllowedProcessesTotalMemoryTimeLimit( + Long.parseLong(txtTemporaryAllowedProcessesTotalMemoryTimeLimit.getText())); + } else { + workingServerInfo.setSafeWorkingProcessesMemoryLimit( + Long.parseLong(txtSafeWorkingProcessesMemoryLimit.getText())); + workingServerInfo.setWorkingProcessMemoryLimit( + Long.parseLong(txtWorkingProcessMemoryLimit.getText())); + } + + try { + if (server.regWorkingServer(clusterId, workingServerInfo, workingServerId == null)) { + workingServerId = workingServerInfo.getWorkingServerId(); + return true; + } + } catch (Exception excp) { + var messageBox = new MessageBox(getParentShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + } + return false; + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button buttonOk = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + buttonOk.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (saveNewClusterProperties()) { + close(); + } + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + + Button buttonApply = + createButton( + parent, + IDialogConstants.PROCEED_ID, + Messages.getString("Dialogs.Apply"), //$NON-NLS-1$ + false); + buttonApply.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + saveNewClusterProperties(); + } + }); + + Button buttonReset = + createButton( + parent, + IDialogConstants.RETRY_ID, + Messages.getString("Dialogs.Reset"), //$NON-NLS-1$ + false); + buttonReset.setText(Messages.getString("Dialogs.Reset")); //$NON-NLS-1$ + buttonReset.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + initServerProperties(); + } + }); + + Button buttonResetToProf = + createButton( + parent, + IDialogConstants.RETRY_ID, + Messages.getString("Dialogs.ResetToPROF"), //$NON-NLS-1$ + false); + buttonResetToProf.addMouseTrackListener( + new MouseTrackAdapter() { + @Override + public void mouseEnter(MouseEvent e) { + txtSafeCallMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); + txtSafeWorkingProcessesMemoryLimit.setBackground( + SWTResourceManager.getLightGreenColor()); + txtWorkingProcessMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); + txtInfoBasesPerWorkingProcessLimit.setBackground( + SWTResourceManager.getLightGreenColor()); + } + + @Override + public void mouseExit(MouseEvent e) { + txtSafeCallMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); + txtSafeWorkingProcessesMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); + txtWorkingProcessMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); + txtInfoBasesPerWorkingProcessLimit.setBackground(SWTResourceManager.getWhiteColor()); + } + }); + buttonResetToProf.setText(Messages.getString("Dialogs.ResetToPROF")); //$NON-NLS-1$ + buttonResetToProf.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + resetToProf(); + } + }); + } + + private String convertToMegabytes(Text textControl) { + long inMb = Long.parseLong(textControl.getText()) / (1024 * 1024); + return Long.toString(inMb) + .concat(Messages.getString("WorkingServerDialog.Megabytes")); //$NON-NLS-1$ + } + + private String convertToMinutes(Text textControl) { + long inMb = Long.parseLong(textControl.getText()) / (60); + return Long.toString(inMb) + .concat(Messages.getString("WorkingServerDialog.Minutes")); //$NON-NLS-1$ + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java index b693faa..fe8b3e3 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java @@ -1,9 +1,10 @@ package ru.yanygin.clusterAdminLibraryUI; +import com._1c.v8.ibis.admin.IInfoBaseInfo; +import com._1c.v8.ibis.admin.InfoBaseInfo; import java.util.ArrayList; import java.util.List; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -12,7 +13,6 @@ import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -24,319 +24,355 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.SWTResourceManager; - -import com._1c.v8.ibis.admin.IInfoBaseInfo; -import com._1c.v8.ibis.admin.InfoBaseInfo; - import ru.yanygin.clusterAdminLibrary.Server; +/** Dialog for create infobase. */ public class CreateInfobaseDialog extends Dialog { - - private UUID clusterId; - - private Server server; - private Button btnSheduledJobsDenied; - private Button btnAllowDistributeLicense; - private Button btnInfobaseCreationMode; - private Text txtInfobaseName; - private Text txtServerDBName; - private Text txtDatabaseDbName; - private Text txtDatabaseDbUser; - private Text txtDatabaseDbPassword; - private Text txtInfobaseDescription; - private Combo comboSecurityLevel; // Disable, Connection only, Constantly (Выключено, Только соединение, Постоянно) - private Combo comboServerDBType; // MSSQLServer, PostgreSQL, IBMDB2, OracleDatabase - private Combo comboLocale; // Откуда то загрузить все возможные локали - private Combo comboDateOffset; - - private UUID newInfobaseUUID; - - private UUID sampleInfobaseId; - - - public UUID getNewInfobaseUUID() { - return newInfobaseUUID; - } - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public CreateInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID sampleInfobaseId) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.server = server; - this.clusterId = clusterId; - this.sampleInfobaseId = sampleInfobaseId; - - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.numColumns = 2; - - Label lblInfobaseName = new Label(container, SWT.NONE); - lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseName.setText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ - - txtInfobaseName = new Text(container, SWT.BORDER); - txtInfobaseName.addModifyListener(new ModifyListener() { - public void modifyText(ModifyEvent e) { - txtDatabaseDbName.setText(((Text)e.widget).getText()); - } - }); - txtInfobaseName.setToolTipText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ - txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblInfobaseDescription = new Label(container, SWT.NONE); - lblInfobaseDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseDescription.setText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ - - txtInfobaseDescription = new Text(container, SWT.BORDER); - txtInfobaseDescription.setToolTipText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ - txtInfobaseDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblSecurityLevel = new Label(container, SWT.NONE); - lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ - - comboSecurityLevel = new Combo(container, SWT.READ_ONLY); - comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ - comboSecurityLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); -// comboSecurityLevel.setText(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - - comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ - comboSecurityLevel.select(0); - - - Label lblServerDBName = new Label(container, SWT.NONE); - lblServerDBName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDBName.setText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ - - txtServerDBName = new Text(container, SWT.BORDER); - txtServerDBName.setToolTipText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ - txtServerDBName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblServerDBType = new Label(container, SWT.NONE); - lblServerDBType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDBType.setText(Messages.getString("InfobaseDialog.DBMSType")); //$NON-NLS-1$ - - comboServerDBType = new Combo(container, SWT.READ_ONLY); - comboServerDBType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - comboServerDBType.add(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ - comboServerDBType.add(Messages.getString("InfobaseDialog.PostgreSQL")); //$NON-NLS-1$ - comboServerDBType.add(Messages.getString("InfobaseDialog.IBMDB2")); //$NON-NLS-1$ - comboServerDBType.add(Messages.getString("InfobaseDialog.OracleDatabase")); //$NON-NLS-1$ - comboServerDBType.select(0); - - comboServerDBType.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - boolean dateOffsetEnabled = comboServerDBType.getText().equals(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ - comboDateOffset.setEnabled(dateOffsetEnabled); - comboDateOffset.setText("0"); //$NON-NLS-1$ - } - }); - - Label lblDatabaseDbName = new Label(container, SWT.NONE); - lblDatabaseDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbName.setText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ - - txtDatabaseDbName = new Text(container, SWT.BORDER); - txtDatabaseDbName.setToolTipText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ - txtDatabaseDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblDatabaseDbUser = new Label(container, SWT.NONE); - lblDatabaseDbUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbUser.setText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ - - txtDatabaseDbUser = new Text(container, SWT.BORDER); - txtDatabaseDbUser.setToolTipText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ - txtDatabaseDbUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblDatabaseDbPassword = new Label(container, SWT.NONE); - lblDatabaseDbPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbPassword.setAlignment(SWT.RIGHT); - lblDatabaseDbPassword.setText(Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ - - txtDatabaseDbPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); - txtDatabaseDbPassword.setToolTipText(Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ - txtDatabaseDbPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - btnAllowDistributeLicense = new Button(container, SWT.CHECK); - btnAllowDistributeLicense.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnAllowDistributeLicense.setText(Messages.getString("InfobaseDialog.AllowDistributeLicense")); //$NON-NLS-1$ - - Label lblLocale = new Label(container, SWT.NONE); - lblLocale.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLocale.setText(Messages.getString("InfobaseDialog.Locale")); //$NON-NLS-1$ - - comboLocale = new Combo(container, SWT.READ_ONLY); - comboLocale.setItems(new String[] {Messages.getString("InfobaseDialog.ru_RU"), Messages.getString("InfobaseDialog.en_US"), "xx_XX", "yy_YY"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - comboLocale.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboLocale.select(0); - - Label lblDateOffset = new Label(container, SWT.NONE); - lblDateOffset.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDateOffset.setText(Messages.getString("InfobaseDialog.DateOffset")); //$NON-NLS-1$ - - comboDateOffset = new Combo(container, SWT.READ_ONLY); - comboDateOffset.setItems(new String[] {"0", "2000"}); //$NON-NLS-1$ //$NON-NLS-2$ - comboDateOffset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboDateOffset.setText("2000"); //$NON-NLS-1$ - - btnInfobaseCreationMode = new Button(container, SWT.CHECK); - btnInfobaseCreationMode.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnInfobaseCreationMode.setText(Messages.getString("InfobaseDialog.CreateDatabaseIfNotAvailable")); //$NON-NLS-1$ - - btnSheduledJobsDenied = new Button(container, SWT.CHECK); - btnSheduledJobsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnSheduledJobsDenied.setText(Messages.getString("InfobaseDialog.SheduledJobsDenied")); //$NON-NLS-1$ - new Label(container, SWT.NONE); - - initInfobaseProperties(); - - return container; - } - - private void initInfobaseProperties() { - if (sampleInfobaseId == null) { - - txtInfobaseName.setText(""); //$NON-NLS-1$ - txtInfobaseDescription.setText(""); //$NON-NLS-1$ - comboSecurityLevel.select(0); - btnAllowDistributeLicense.setSelection(false); - btnSheduledJobsDenied.setSelection(false); - - // DB properties - txtServerDBName.setText(""); //$NON-NLS-1$ - comboServerDBType.select(0); - txtDatabaseDbName.setText(""); //$NON-NLS-1$ - txtDatabaseDbUser.setText(""); //$NON-NLS-1$ - txtDatabaseDbPassword.setText(""); //$NON-NLS-1$ - txtDatabaseDbPassword.setToolTipText(Messages.getString("InfobaseDialog.YouNeedToEnter")); //$NON-NLS-1$ - - } else { - - IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, sampleInfobaseId); - if (infoBaseInfo == null) { - close(); - return; - } - - // Common properties - txtInfobaseName.setText(infoBaseInfo.getName()); - txtInfobaseDescription.setText(infoBaseInfo.getDescr()); - comboSecurityLevel.setText(Integer.toString(infoBaseInfo.getSecurityLevel())); - btnAllowDistributeLicense.setSelection(infoBaseInfo.getLicenseDistributionAllowed() == 1); - btnSheduledJobsDenied.setSelection(infoBaseInfo.isScheduledJobsDenied()); - - // DB properties - txtServerDBName.setText(infoBaseInfo.getDbServerName()); - comboServerDBType.setText(infoBaseInfo.getDbms()); - txtDatabaseDbName.setText(infoBaseInfo.getDbName()); - txtDatabaseDbUser.setText(infoBaseInfo.getDbUser()); - txtDatabaseDbPassword.setText(""); //$NON-NLS-1$ - txtDatabaseDbPassword.setToolTipText(Messages.getString("InfobaseDialog.YouNeedToEnter")); //$NON-NLS-1$ - - txtInfobaseName.setForeground(new Color(255, 0, 0)); - txtDatabaseDbName.setForeground(new Color(255, 0, 0)); - btnInfobaseCreationMode.setForeground(new Color(255, 0, 0)); - txtDatabaseDbPassword.setForeground(new Color(255, 0, 0)); - } - } - - private boolean checkVariablesFromControls() { - - var existsError = false; - - List checksTextControls = new ArrayList<>(); - checksTextControls.add(txtInfobaseName); - checksTextControls.add(txtServerDBName); - checksTextControls.add(txtDatabaseDbName); - checksTextControls.add(txtDatabaseDbUser); - - for (Text control : checksTextControls) { - if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); - existsError = true; - } else { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); - } - } - - return existsError; - } - - private boolean saveInfobaseProperties() { - - if (checkVariablesFromControls()) - return false; - - IInfoBaseInfo infoBaseInfo = new InfoBaseInfo((int) comboSecurityLevel.getData(comboSecurityLevel.getText())); - - // Common properties - infoBaseInfo.setName(txtInfobaseName.getText()); - infoBaseInfo.setDescr(txtInfobaseDescription.getText()); - infoBaseInfo.setLicenseDistributionAllowed(btnAllowDistributeLicense.getSelection() ? 1 : 0); - infoBaseInfo.setScheduledJobsDenied(btnSheduledJobsDenied.getSelection()); - - // DB properties - infoBaseInfo.setDbServerName(txtServerDBName.getText()); - infoBaseInfo.setDbms(comboServerDBType.getText()); - infoBaseInfo.setDbName(txtDatabaseDbName.getText()); - infoBaseInfo.setDbUser(txtDatabaseDbUser.getText()); - infoBaseInfo.setDbPassword(txtDatabaseDbPassword.getText()); - infoBaseInfo.setLocale(comboLocale.getText()); - if (comboServerDBType.getText().equals(Messages.getString("InfobaseDialog.MSSQLServer"))) //$NON-NLS-1$ - infoBaseInfo.setDateOffset(Integer.parseInt(comboDateOffset.getText())); - - try { - newInfobaseUUID = server.createInfoBase(clusterId, infoBaseInfo, - (btnInfobaseCreationMode.getSelection() ? 1 : 0)); - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - return true; - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (saveInfobaseProperties()) - close(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } + private UUID clusterId; + + private Server server; + private Button btnSheduledJobsDenied; + private Button btnAllowDistributeLicense; + private Button btnInfobaseCreationMode; + private Text txtInfobaseName; + private Text txtServerDbName; + private Text txtDatabaseDbName; + private Text txtDatabaseDbUser; + private Text txtDatabaseDbPassword; + private Text txtInfobaseDescription; + private Combo comboSecurityLevel; + private Combo comboServerDbType; + private Combo comboLocale; // Откуда то загрузить все возможные локали + private Combo comboDateOffset; + + private UUID newInfobaseUuid; + + /** + * Return infobase ID for create new infobase from sample. + * + * @return infobase ID + */ + public UUID getNewInfobaseUuid() { + return newInfobaseUuid; + } + + private UUID sampleInfobaseId; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server parameters + * @param clusterId - cluster ID + * @param sampleInfobaseId - infobase ID for create from sample, else null + */ + public CreateInfobaseDialog( + Shell parentShell, Server server, UUID clusterId, UUID sampleInfobaseId) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.server = server; + this.clusterId = clusterId; + this.sampleInfobaseId = sampleInfobaseId; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.numColumns = 2; + + Label lblInfobaseName = new Label(container, SWT.NONE); + lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblInfobaseName.setText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ + + txtInfobaseName = new Text(container, SWT.BORDER); + txtInfobaseName.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + txtDatabaseDbName.setText(((Text) e.widget).getText()); + } + }); + txtInfobaseName.setToolTipText( + Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ + txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblInfobaseDescription = new Label(container, SWT.NONE); + lblInfobaseDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblInfobaseDescription.setText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ + + txtInfobaseDescription = new Text(container, SWT.BORDER); + txtInfobaseDescription.setToolTipText( + Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ + txtInfobaseDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblSecurityLevel = new Label(container, SWT.NONE); + lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + + comboSecurityLevel = new Combo(container, SWT.READ_ONLY); + comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + comboSecurityLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ + comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ + comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ + comboSecurityLevel.select(0); + + Label lblServerDbName = new Label(container, SWT.NONE); + lblServerDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblServerDbName.setText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ + + txtServerDbName = new Text(container, SWT.BORDER); + txtServerDbName.setToolTipText( + Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ + txtServerDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblServerDbType = new Label(container, SWT.NONE); + lblServerDbType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblServerDbType.setText(Messages.getString("InfobaseDialog.DBMSType")); //$NON-NLS-1$ + + comboServerDbType = new Combo(container, SWT.READ_ONLY); + comboServerDbType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + comboServerDbType.add(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ + comboServerDbType.add(Messages.getString("InfobaseDialog.PostgreSQL")); //$NON-NLS-1$ + comboServerDbType.add(Messages.getString("InfobaseDialog.IBMDB2")); //$NON-NLS-1$ + comboServerDbType.add(Messages.getString("InfobaseDialog.OracleDatabase")); //$NON-NLS-1$ + comboServerDbType.select(0); + + comboServerDbType.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + boolean dateOffsetEnabled = + comboServerDbType + .getText() + .equals(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ + comboDateOffset.setEnabled(dateOffsetEnabled); + comboDateOffset.setText(dateOffsetEnabled ? "2000" : "0"); //$NON-NLS-1$ //$NON-NLS-2$ + } + }); + + Label lblDatabaseDbName = new Label(container, SWT.NONE); + lblDatabaseDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDatabaseDbName.setText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ + + txtDatabaseDbName = new Text(container, SWT.BORDER); + txtDatabaseDbName.setToolTipText( + Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ + txtDatabaseDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblDatabaseDbUser = new Label(container, SWT.NONE); + lblDatabaseDbUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDatabaseDbUser.setText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ + + txtDatabaseDbUser = new Text(container, SWT.BORDER); + txtDatabaseDbUser.setToolTipText( + Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ + txtDatabaseDbUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblDatabaseDbPassword = new Label(container, SWT.NONE); + lblDatabaseDbPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDatabaseDbPassword.setAlignment(SWT.RIGHT); + lblDatabaseDbPassword.setText( + Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ + + txtDatabaseDbPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); + txtDatabaseDbPassword.setToolTipText( + Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ + txtDatabaseDbPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + btnAllowDistributeLicense = new Button(container, SWT.CHECK); + btnAllowDistributeLicense.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnAllowDistributeLicense.setText( + Messages.getString("InfobaseDialog.AllowDistributeLicense")); //$NON-NLS-1$ + + Label lblLocale = new Label(container, SWT.NONE); + lblLocale.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblLocale.setText(Messages.getString("InfobaseDialog.Locale")); //$NON-NLS-1$ + + comboLocale = new Combo(container, SWT.READ_ONLY); + comboLocale.setItems( + new String[] { + Messages.getString("InfobaseDialog.ru_RU"), + Messages.getString("InfobaseDialog.en_US"), + "xx_XX", + "yy_YY" + }); + comboLocale.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + comboLocale.select(0); + + Label lblDateOffset = new Label(container, SWT.NONE); + lblDateOffset.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDateOffset.setText(Messages.getString("InfobaseDialog.DateOffset")); //$NON-NLS-1$ + + comboDateOffset = new Combo(container, SWT.READ_ONLY); + comboDateOffset.setItems("0", "2000"); //$NON-NLS-1$ //$NON-NLS-2$ + comboDateOffset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + comboDateOffset.setText("2000"); //$NON-NLS-1$ + + btnInfobaseCreationMode = new Button(container, SWT.CHECK); + btnInfobaseCreationMode.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnInfobaseCreationMode.setText( + Messages.getString("InfobaseDialog.CreateDatabaseIfNotAvailable")); //$NON-NLS-1$ + + btnSheduledJobsDenied = new Button(container, SWT.CHECK); + btnSheduledJobsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnSheduledJobsDenied.setText( + Messages.getString("InfobaseDialog.SheduledJobsDenied")); //$NON-NLS-1$ + new Label(container, SWT.NONE); + + initInfobaseProperties(); + + return container; + } + + private void initInfobaseProperties() { + if (sampleInfobaseId == null) { + + txtInfobaseName.setText(""); //$NON-NLS-1$ + txtInfobaseDescription.setText(""); //$NON-NLS-1$ + comboSecurityLevel.select(0); + btnAllowDistributeLicense.setSelection(false); + btnSheduledJobsDenied.setSelection(false); + + // DB properties + txtServerDbName.setText(""); //$NON-NLS-1$ + comboServerDbType.select(0); + txtDatabaseDbName.setText(""); //$NON-NLS-1$ + txtDatabaseDbUser.setText(""); //$NON-NLS-1$ + txtDatabaseDbPassword.setText(""); //$NON-NLS-1$ + txtDatabaseDbPassword.setToolTipText( + Messages.getString("InfobaseDialog.YouNeedToEnter")); //$NON-NLS-1$ + + } else { + + IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, sampleInfobaseId); + if (infoBaseInfo == null) { + close(); + return; + } + + // Common properties + txtInfobaseName.setText(infoBaseInfo.getName()); + txtInfobaseDescription.setText(infoBaseInfo.getDescr()); + comboSecurityLevel.setText(Integer.toString(infoBaseInfo.getSecurityLevel())); + btnAllowDistributeLicense.setSelection(infoBaseInfo.getLicenseDistributionAllowed() == 1); + btnSheduledJobsDenied.setSelection(infoBaseInfo.isScheduledJobsDenied()); + + // DB properties + txtServerDbName.setText(infoBaseInfo.getDbServerName()); + comboServerDbType.setText(infoBaseInfo.getDbms()); + txtDatabaseDbName.setText(infoBaseInfo.getDbName()); + txtDatabaseDbUser.setText(infoBaseInfo.getDbUser()); + txtDatabaseDbPassword.setText(""); //$NON-NLS-1$ + txtDatabaseDbPassword.setToolTipText( + Messages.getString("InfobaseDialog.YouNeedToEnter")); //$NON-NLS-1$ + + txtInfobaseName.setForeground(new Color(255, 0, 0)); + txtDatabaseDbName.setForeground(new Color(255, 0, 0)); + btnInfobaseCreationMode.setForeground(new Color(255, 0, 0)); + txtDatabaseDbPassword.setForeground(new Color(255, 0, 0)); + } + } + + private boolean checkVariablesFromControls() { + + var existsError = false; + + List checksTextControls = new ArrayList<>(); + checksTextControls.add(txtInfobaseName); + checksTextControls.add(txtServerDbName); + checksTextControls.add(txtDatabaseDbName); + checksTextControls.add(txtDatabaseDbUser); + + for (Text control : checksTextControls) { + if (control.getText().isBlank()) { + control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + existsError = true; + } else { + control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + } + } + + return existsError; + } + + private boolean saveInfobaseProperties() { + + if (checkVariablesFromControls()) { + return false; + } + + IInfoBaseInfo infoBaseInfo = + new InfoBaseInfo((int) comboSecurityLevel.getData(comboSecurityLevel.getText())); + + // Common properties + infoBaseInfo.setName(txtInfobaseName.getText()); + infoBaseInfo.setDescr(txtInfobaseDescription.getText()); + infoBaseInfo.setLicenseDistributionAllowed(btnAllowDistributeLicense.getSelection() ? 1 : 0); + infoBaseInfo.setScheduledJobsDenied(btnSheduledJobsDenied.getSelection()); + + // DB properties + infoBaseInfo.setDbServerName(txtServerDbName.getText()); + infoBaseInfo.setDbms(comboServerDbType.getText()); + infoBaseInfo.setDbName(txtDatabaseDbName.getText()); + infoBaseInfo.setDbUser(txtDatabaseDbUser.getText()); + infoBaseInfo.setDbPassword(txtDatabaseDbPassword.getText()); + infoBaseInfo.setLocale(comboLocale.getText()); + if (comboServerDbType + .getText() + .equals(Messages.getString("InfobaseDialog.MSSQLServer"))) { //$NON-NLS-1$ + infoBaseInfo.setDateOffset(Integer.parseInt(comboDateOffset.getText())); + } + + try { + newInfobaseUuid = + server.createInfoBase( + clusterId, infoBaseInfo, (btnInfobaseCreationMode.getSelection() ? 1 : 0)); + } catch (Exception excp) { + var messageBox = new MessageBox(getParentShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + return true; + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (saveInfobaseProperties()) { + close(); + } + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java index 60bbc54..abf74c8 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java @@ -1,13 +1,11 @@ package ru.yanygin.clusterAdminLibraryUI; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -15,107 +13,116 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; - import ru.yanygin.clusterAdminLibrary.Server; +/** Dialog for drop infobase. */ public class DropInfobaseDialog extends Dialog { - - private UUID clusterId; - private Server server; - - private int databaseDropMode; - private UUID infobaseId; - - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public DropInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID infobaseId) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.infobaseId = infobaseId; - this.clusterId = clusterId; - this.server = server; - - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.numColumns = 2; - - Label lblInfo = new Label(container, SWT.WRAP); - GridData gdlblInfo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1); - gdlblInfo.heightHint = 34; - lblInfo.setLayoutData(gdlblInfo); - lblInfo.setText(Messages.getString("Dialogs.DropInfobaseDescription")); //$NON-NLS-1$ - new Label(container, SWT.NONE); - - Button btnNotDelete = new Button(container, SWT.RADIO); - btnNotDelete.setText(Messages.getString("Dialogs.LeaveDatabaseUnchanged")); //$NON-NLS-1$ - btnNotDelete.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - databaseDropMode = 0; - } - }); - new Label(container, SWT.NONE); - - Button btnDeleteTheDatabase = new Button(container, SWT.RADIO); - btnDeleteTheDatabase.setText(Messages.getString("Dialogs.DeleteTheEntireDatabase")); //$NON-NLS-1$ - btnDeleteTheDatabase.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - databaseDropMode = 1; - } - }); - new Label(container, SWT.NONE); - - Button btnClearTheDatabase = new Button(container, SWT.RADIO); - btnClearTheDatabase.setText(Messages.getString("Dialogs.ClearTheDatabase")); //$NON-NLS-1$ - btnClearTheDatabase.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - databaseDropMode = 2; - } - }); - - return container; - } - - private void runRemoveInfobase() { - - if (server.dropInfoBase(clusterId, infobaseId, databaseDropMode)) - close(); - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - runRemoveInfobase(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } + private UUID clusterId; + private Server server; + + private int databaseDropMode; + private UUID infobaseId; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server parameters + * @param clusterId - cluster ID + * @param infobaseId - infobase ID + */ + public DropInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID infobaseId) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.infobaseId = infobaseId; + this.clusterId = clusterId; + this.server = server; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.numColumns = 2; + + Label lblInfo = new Label(container, SWT.WRAP); + GridData gdlblInfo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1); + gdlblInfo.heightHint = 34; + lblInfo.setLayoutData(gdlblInfo); + lblInfo.setText(Messages.getString("Dialogs.DropInfobaseDescription")); //$NON-NLS-1$ + new Label(container, SWT.NONE); + + Button btnNotDelete = new Button(container, SWT.RADIO); + btnNotDelete.setText(Messages.getString("Dialogs.LeaveDatabaseUnchanged")); //$NON-NLS-1$ + btnNotDelete.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + databaseDropMode = 0; + } + }); + new Label(container, SWT.NONE); + + Button btnDeleteTheDatabase = new Button(container, SWT.RADIO); + btnDeleteTheDatabase.setText( + Messages.getString("Dialogs.DeleteTheEntireDatabase")); //$NON-NLS-1$ + btnDeleteTheDatabase.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + databaseDropMode = 1; + } + }); + new Label(container, SWT.NONE); + + Button btnClearTheDatabase = new Button(container, SWT.RADIO); + btnClearTheDatabase.setText(Messages.getString("Dialogs.ClearTheDatabase")); //$NON-NLS-1$ + btnClearTheDatabase.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + databaseDropMode = 2; + } + }); + + return container; + } + + private void runRemoveInfobase() { + + if (server.dropInfoBase(clusterId, infobaseId, databaseDropMode)) { + close(); + } + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + runRemoveInfobase(); + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java index b11a9a1..1302138 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java @@ -1,5 +1,6 @@ package ru.yanygin.clusterAdminLibraryUI; +import com._1c.v8.ibis.admin.IInfoBaseInfo; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -7,13 +8,11 @@ import java.util.Date; import java.util.List; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; @@ -25,409 +24,448 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.wb.swt.SWTResourceManager; - -import com._1c.v8.ibis.admin.IInfoBaseInfo; - import ru.yanygin.clusterAdminLibrary.Server; +/** Dialog for edit infobase parameters. */ public class EditInfobaseDialog extends Dialog { - - private UUID infoBaseId; - private UUID clusterId; - private Server server; - - // Controls - private Button btnSessionsDenied; - private Button btnSheduledJobsDenied; - private Button btnAllowDistributeLicense; - private Button btnExternalSessionManagerRequired; - private Text txtInfobaseName; - private Text txtServerDBName; - private Text txtDatabaseDbName; - private Text txtDatabaseDbUser; - private Text txtDatabaseDbPassword; - private Text txtInfobaseDescription; - private Combo comboSecurityLevel; - private Text txtPermissionCode; - private Text txtDeniedParameter; - private Text txtExternalSessionManagerConnectionString; - private Text txtSecurityProfile; - private Text txtSafeModeSecurityProfile; - private Text txtDeniedMessage; - private Combo comboServerDBType; - private Text deniedFromDate; - private Text deniedToDate; - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public EditInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID infoBaseId) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.server = server; - this.clusterId = clusterId; - this.infoBaseId = infoBaseId; - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.numColumns = 2; - - Label lblInfobaseName = new Label(container, SWT.NONE); - lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseName.setText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ - - txtInfobaseName = new Text(container, SWT.BORDER); - txtInfobaseName.setToolTipText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ - txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblInfobaseDescription = new Label(container, SWT.NONE); - lblInfobaseDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseDescription.setText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ - - txtInfobaseDescription = new Text(container, SWT.BORDER); - txtInfobaseDescription.setToolTipText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ - txtInfobaseDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblSecurityLevel = new Label(container, SWT.NONE); - lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ - - comboSecurityLevel = new Combo(container, SWT.READ_ONLY); - comboSecurityLevel.setEnabled(false); - comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ - comboSecurityLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ - comboSecurityLevel.select(0); - - Label lblServerDBName = new Label(container, SWT.NONE); - lblServerDBName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDBName.setText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ - - txtServerDBName = new Text(container, SWT.BORDER); - txtServerDBName.setToolTipText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ - txtServerDBName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblServerDBType = new Label(container, SWT.NONE); - lblServerDBType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDBType.setText(Messages.getString("InfobaseDialog.DBMSType")); //$NON-NLS-1$ - - comboServerDBType = new Combo(container, SWT.READ_ONLY); - comboServerDBType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - comboServerDBType.add(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ - comboServerDBType.add(Messages.getString("InfobaseDialog.PostgreSQL")); //$NON-NLS-1$ - comboServerDBType.add(Messages.getString("InfobaseDialog.IBMDB2")); //$NON-NLS-1$ - comboServerDBType.add(Messages.getString("InfobaseDialog.OracleDatabase")); //$NON-NLS-1$ - comboServerDBType.select(0); - - Label lblDatabaseDbName = new Label(container, SWT.NONE); - lblDatabaseDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbName.setText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ - - txtDatabaseDbName = new Text(container, SWT.BORDER); - txtDatabaseDbName.setToolTipText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ - txtDatabaseDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblDatabaseDbUser = new Label(container, SWT.NONE); - lblDatabaseDbUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbUser.setText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ - - txtDatabaseDbUser = new Text(container, SWT.BORDER); - txtDatabaseDbUser.setToolTipText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ - txtDatabaseDbUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblDatabaseDbPassword = new Label(container, SWT.NONE); - lblDatabaseDbPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbPassword.setAlignment(SWT.RIGHT); - lblDatabaseDbPassword.setText(Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ - - txtDatabaseDbPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); - txtDatabaseDbPassword.setToolTipText(Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ - txtDatabaseDbPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - btnAllowDistributeLicense = new Button(container, SWT.CHECK); - btnAllowDistributeLicense.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnAllowDistributeLicense.setText(Messages.getString("InfobaseDialog.AllowDistributeLicense")); //$NON-NLS-1$ - - btnSessionsDenied = new Button(container, SWT.CHECK); - btnSessionsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnSessionsDenied.setText(Messages.getString("InfobaseDialog.SessionsDenied")); //$NON-NLS-1$ - - Label lblDeniedFrom = new Label(container, SWT.NONE); - lblDeniedFrom.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDeniedFrom.setText(Messages.getString("InfobaseDialog.DeniedFrom")); //$NON-NLS-1$ - - Composite compositeDeniedFrom = new Composite(container, SWT.NONE); - compositeDeniedFrom.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - compositeDeniedFrom.setLayout(new FillLayout(SWT.HORIZONTAL)); - - deniedFromDate = new Text(compositeDeniedFrom, SWT.BORDER | SWT.DATE | SWT.DROP_DOWN); - - Label lblDeniedTo = new Label(container, SWT.NONE); - lblDeniedTo.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDeniedTo.setText(Messages.getString("InfobaseDialog.DeniedTo")); //$NON-NLS-1$ - - Composite compositeDeniedTo = new Composite(container, SWT.NONE); - compositeDeniedTo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - compositeDeniedTo.setLayout(new FillLayout(SWT.HORIZONTAL)); - - deniedToDate = new Text(compositeDeniedTo, SWT.BORDER); - - Label lblDeniedMessage = new Label(container, SWT.NONE); - lblDeniedMessage.setText(Messages.getString("InfobaseDialog.DeniedMessage")); //$NON-NLS-1$ - - txtDeniedMessage = new Text(container, SWT.BORDER); - txtDeniedMessage.setToolTipText(Messages.getString("InfobaseDialog.DeniedMessage")); //$NON-NLS-1$ - GridData gdtxtDeniedMessage = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); - gdtxtDeniedMessage.heightHint = 63; - txtDeniedMessage.setLayoutData(gdtxtDeniedMessage); - - Label lblPermissionCode = new Label(container, SWT.NONE); - lblPermissionCode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPermissionCode.setText(Messages.getString("InfobaseDialog.PermissionCode")); //$NON-NLS-1$ - - txtPermissionCode = new Text(container, SWT.BORDER); - txtPermissionCode.setToolTipText(Messages.getString("InfobaseDialog.PermissionCode")); //$NON-NLS-1$ - txtPermissionCode.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblDeniedParameter = new Label(container, SWT.NONE); - lblDeniedParameter.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDeniedParameter.setText(Messages.getString("InfobaseDialog.DeniedParameter")); //$NON-NLS-1$ - - txtDeniedParameter = new Text(container, SWT.BORDER); - txtDeniedParameter.setToolTipText(Messages.getString("InfobaseDialog.DeniedParameter")); //$NON-NLS-1$ - txtDeniedParameter.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - btnSheduledJobsDenied = new Button(container, SWT.CHECK); - btnSheduledJobsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnSheduledJobsDenied.setText(Messages.getString("InfobaseDialog.SheduledJobsDenied")); //$NON-NLS-1$ - - Label lblExternalSessionManagerConnectionString = new Label(container, SWT.NONE); - lblExternalSessionManagerConnectionString.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblExternalSessionManagerConnectionString.setText(Messages.getString("InfobaseDialog.ExternalSessionManagement")); //$NON-NLS-1$ - - txtExternalSessionManagerConnectionString = new Text(container, SWT.BORDER); - txtExternalSessionManagerConnectionString.setToolTipText(Messages.getString("InfobaseDialog.ExternalSessionManagement")); //$NON-NLS-1$ - txtExternalSessionManagerConnectionString.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - btnExternalSessionManagerRequired = new Button(container, SWT.CHECK); - btnExternalSessionManagerRequired.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnExternalSessionManagerRequired.setText(Messages.getString("InfobaseDialog.RequiredUseOfExternalManagement")); //$NON-NLS-1$ - - Label lblSecurityProfile = new Label(container, SWT.NONE); - lblSecurityProfile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityProfile.setText(Messages.getString("InfobaseDialog.SecurityProfile")); //$NON-NLS-1$ - - txtSecurityProfile = new Text(container, SWT.BORDER); - txtSecurityProfile.setToolTipText(Messages.getString("InfobaseDialog.SecurityProfile")); //$NON-NLS-1$ - txtSecurityProfile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblSafeModeSecurityProfile = new Label(container, SWT.NONE); - lblSafeModeSecurityProfile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSafeModeSecurityProfile.setText(Messages.getString("InfobaseDialog.SafeModeSecurityProfile")); //$NON-NLS-1$ - - txtSafeModeSecurityProfile = new Text(container, SWT.BORDER); - txtSafeModeSecurityProfile.setToolTipText(Messages.getString("InfobaseDialog.SafeModeSecurityProfile")); //$NON-NLS-1$ - txtSafeModeSecurityProfile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - initInfobaseProperties(); - - return container; - } - - private void initInfobaseProperties() { - if (infoBaseId != null) { - - IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infoBaseId); - if (infoBaseInfo == null) { - close(); - return; - } - - // Common properties - txtInfobaseName.setText(infoBaseInfo.getName()); - txtInfobaseDescription.setText(infoBaseInfo.getDescr()); - comboSecurityLevel.setText(Integer.toString(infoBaseInfo.getSecurityLevel())); - btnAllowDistributeLicense.setSelection(infoBaseInfo.getLicenseDistributionAllowed() == 1); - btnSheduledJobsDenied.setSelection(infoBaseInfo.isScheduledJobsDenied()); - - // DB properties - txtServerDBName.setText(infoBaseInfo.getDbServerName()); - comboServerDBType.setText(infoBaseInfo.getDbms()); - txtDatabaseDbName.setText(infoBaseInfo.getDbName()); - txtDatabaseDbUser.setText(infoBaseInfo.getDbUser()); - txtDatabaseDbPassword.setText(infoBaseInfo.getDbPassword()); - - // Lock properties - btnSessionsDenied.setSelection(infoBaseInfo.isSessionsDenied()); - deniedFromDate.setText(convertDateToString(infoBaseInfo.getDeniedFrom())); - deniedToDate.setText(convertDateToString(infoBaseInfo.getDeniedTo())); - - txtDeniedMessage.setText(infoBaseInfo.getDeniedMessage()); - txtPermissionCode.setText(infoBaseInfo.getPermissionCode()); - txtDeniedParameter.setText(infoBaseInfo.getDeniedParameter()); - - // ExternalSessionManager properties - txtExternalSessionManagerConnectionString.setText(infoBaseInfo.getExternalSessionManagerConnectionString()); - btnExternalSessionManagerRequired.setSelection(infoBaseInfo.getExternalSessionManagerRequired()); - - // SecurityProfile properties - txtSecurityProfile.setText(infoBaseInfo.getSecurityProfileName()); - txtSafeModeSecurityProfile.setText(infoBaseInfo.getSafeModeSecurityProfileName()); - - } - } - - private boolean checkVariablesFromControls() { - - var existsError = false; - - List checksTextControls = new ArrayList<>(); - checksTextControls.add(txtInfobaseName); - checksTextControls.add(txtServerDBName); - checksTextControls.add(txtDatabaseDbName); - checksTextControls.add(txtDatabaseDbUser); - - for (Text control : checksTextControls) { - if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); - existsError = true; - } else { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); - } - } - - List checksDateControls = new ArrayList<>(); - checksDateControls.add(deniedFromDate); - checksDateControls.add(deniedToDate); - - for (Text control : checksDateControls) { - if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); - } else { - if (convertStringToDate(control.getText()).equals(new Date(0))) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); - existsError = true; - } - } - } - - return existsError; - } - - private boolean saveInfobaseProperties() { - - if (checkVariablesFromControls()) - return false; - - IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infoBaseId); - if (infoBaseInfo == null) - return false; - - // Common properties - infoBaseInfo.setName(txtInfobaseName.getText()); - infoBaseInfo.setDescr(txtInfobaseDescription.getText()); - infoBaseInfo.setLicenseDistributionAllowed(btnAllowDistributeLicense.getSelection() ? 1 : 0); - infoBaseInfo.setScheduledJobsDenied(btnSheduledJobsDenied.getSelection()); - - // DB properties - infoBaseInfo.setDbServerName(txtServerDBName.getText()); - infoBaseInfo.setDbms(comboServerDBType.getText()); - infoBaseInfo.setDbName(txtDatabaseDbName.getText()); - infoBaseInfo.setDbUser(txtDatabaseDbUser.getText()); - infoBaseInfo.setDbPassword(txtDatabaseDbPassword.getText()); - - // Lock properties - infoBaseInfo.setSessionsDenied(btnSessionsDenied.getSelection()); - infoBaseInfo.setDeniedFrom(convertStringToDate(deniedFromDate.getText())); - infoBaseInfo.setDeniedTo(convertStringToDate(deniedToDate.getText())); - - infoBaseInfo.setDeniedMessage(txtDeniedMessage.getText()); - infoBaseInfo.setPermissionCode(txtPermissionCode.getText()); - infoBaseInfo.setDeniedParameter(txtDeniedParameter.getText()); - - // ExternalSessionManager properties - infoBaseInfo.setExternalSessionManagerConnectionString(txtExternalSessionManagerConnectionString.getText()); - infoBaseInfo.setExternalSessionManagerRequired(btnExternalSessionManagerRequired.getSelection()); - - // SecurityProfile properties - infoBaseInfo.setSecurityProfileName(txtSecurityProfile.getText()); - infoBaseInfo.setSafeModeSecurityProfileName(txtSafeModeSecurityProfile.getText()); - - return server.updateInfoBase(clusterId, infoBaseInfo); - } - - private Date convertStringToDate(String date) { - - Date emptyDate = new Date(0); - - if (date.isBlank()) - return emptyDate; - - Date convertDate; - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - try { - convertDate = dateFormat.parse(date); - } catch (ParseException excp) { - excp.printStackTrace(); - convertDate = emptyDate; - } - - return convertDate; - } - - private String convertDateToString(Date date) { - - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date emptyDate = new Date(0); - - return date.equals(emptyDate) ? "" : dateFormat.format(date); - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button buttonOK = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - buttonOK.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (saveInfobaseProperties()) - close(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - - Button buttonApply = createButton(parent, IDialogConstants.PROCEED_ID, Messages.getString("Dialogs.Apply"), false); //$NON-NLS-1$ - buttonApply.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - saveInfobaseProperties(); - } - }); - } + private UUID infoBaseId; + private UUID clusterId; + private Server server; + + // Controls + private Button btnSessionsDenied; + private Button btnSheduledJobsDenied; + private Button btnAllowDistributeLicense; + private Button btnExternalSessionManagerRequired; + private Text txtInfobaseName; + private Text txtServerDbName; + private Text txtDatabaseDbName; + private Text txtDatabaseDbUser; + private Text txtDatabaseDbPassword; + private Text txtInfobaseDescription; + private Combo comboSecurityLevel; + private Text txtPermissionCode; + private Text txtDeniedParameter; + private Text txtExternalSessionManagerConnectionString; + private Text txtSecurityProfile; + private Text txtSafeModeSecurityProfile; + private Text txtDeniedMessage; + private Combo comboServerDbType; + private Text deniedFromDate; + private Text deniedToDate; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server parameters + * @param clusterId - cluster ID + * @param infoBaseId - infobase ID + */ + public EditInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID infoBaseId) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.server = server; + this.clusterId = clusterId; + this.infoBaseId = infoBaseId; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.numColumns = 2; + + Label lblInfobaseName = new Label(container, SWT.NONE); + lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblInfobaseName.setText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ + + txtInfobaseName = new Text(container, SWT.BORDER); + txtInfobaseName.setToolTipText( + Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ + txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblInfobaseDescription = new Label(container, SWT.NONE); + lblInfobaseDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblInfobaseDescription.setText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ + + txtInfobaseDescription = new Text(container, SWT.BORDER); + txtInfobaseDescription.setToolTipText( + Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ + txtInfobaseDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblSecurityLevel = new Label(container, SWT.NONE); + lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + + comboSecurityLevel = new Combo(container, SWT.READ_ONLY); + comboSecurityLevel.setEnabled(false); + comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + comboSecurityLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ + comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ + comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ + comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ + comboSecurityLevel.select(0); + + Label lblServerDbName = new Label(container, SWT.NONE); + lblServerDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblServerDbName.setText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ + + txtServerDbName = new Text(container, SWT.BORDER); + txtServerDbName.setToolTipText( + Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ + txtServerDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblServerDbType = new Label(container, SWT.NONE); + lblServerDbType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblServerDbType.setText(Messages.getString("InfobaseDialog.DBMSType")); //$NON-NLS-1$ + + comboServerDbType = new Combo(container, SWT.READ_ONLY); + comboServerDbType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + comboServerDbType.add(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ + comboServerDbType.add(Messages.getString("InfobaseDialog.PostgreSQL")); //$NON-NLS-1$ + comboServerDbType.add(Messages.getString("InfobaseDialog.IBMDB2")); //$NON-NLS-1$ + comboServerDbType.add(Messages.getString("InfobaseDialog.OracleDatabase")); //$NON-NLS-1$ + comboServerDbType.select(0); + + Label lblDatabaseDbName = new Label(container, SWT.NONE); + lblDatabaseDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDatabaseDbName.setText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ + + txtDatabaseDbName = new Text(container, SWT.BORDER); + txtDatabaseDbName.setToolTipText( + Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ + txtDatabaseDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblDatabaseDbUser = new Label(container, SWT.NONE); + lblDatabaseDbUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDatabaseDbUser.setText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ + + txtDatabaseDbUser = new Text(container, SWT.BORDER); + txtDatabaseDbUser.setToolTipText( + Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ + txtDatabaseDbUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblDatabaseDbPassword = new Label(container, SWT.NONE); + lblDatabaseDbPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDatabaseDbPassword.setAlignment(SWT.RIGHT); + lblDatabaseDbPassword.setText( + Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ + + txtDatabaseDbPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); + txtDatabaseDbPassword.setToolTipText( + Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ + txtDatabaseDbPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + btnAllowDistributeLicense = new Button(container, SWT.CHECK); + btnAllowDistributeLicense.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnAllowDistributeLicense.setText( + Messages.getString("InfobaseDialog.AllowDistributeLicense")); //$NON-NLS-1$ + + btnSessionsDenied = new Button(container, SWT.CHECK); + btnSessionsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnSessionsDenied.setText(Messages.getString("InfobaseDialog.SessionsDenied")); //$NON-NLS-1$ + + Label lblDeniedFrom = new Label(container, SWT.NONE); + lblDeniedFrom.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDeniedFrom.setText(Messages.getString("InfobaseDialog.DeniedFrom")); //$NON-NLS-1$ + + Composite compositeDeniedFrom = new Composite(container, SWT.NONE); + compositeDeniedFrom.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + compositeDeniedFrom.setLayout(new FillLayout(SWT.HORIZONTAL)); + + deniedFromDate = new Text(compositeDeniedFrom, SWT.BORDER | SWT.DATE | SWT.DROP_DOWN); + + Label lblDeniedTo = new Label(container, SWT.NONE); + lblDeniedTo.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDeniedTo.setText(Messages.getString("InfobaseDialog.DeniedTo")); //$NON-NLS-1$ + + Composite compositeDeniedTo = new Composite(container, SWT.NONE); + compositeDeniedTo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + compositeDeniedTo.setLayout(new FillLayout(SWT.HORIZONTAL)); + + deniedToDate = new Text(compositeDeniedTo, SWT.BORDER); + + Label lblDeniedMessage = new Label(container, SWT.NONE); + lblDeniedMessage.setText(Messages.getString("InfobaseDialog.DeniedMessage")); //$NON-NLS-1$ + + txtDeniedMessage = new Text(container, SWT.BORDER); + txtDeniedMessage.setToolTipText( + Messages.getString("InfobaseDialog.DeniedMessage")); //$NON-NLS-1$ + GridData gdtxtDeniedMessage = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); + gdtxtDeniedMessage.heightHint = 63; + txtDeniedMessage.setLayoutData(gdtxtDeniedMessage); + + Label lblPermissionCode = new Label(container, SWT.NONE); + lblPermissionCode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblPermissionCode.setText(Messages.getString("InfobaseDialog.PermissionCode")); //$NON-NLS-1$ + + txtPermissionCode = new Text(container, SWT.BORDER); + txtPermissionCode.setToolTipText( + Messages.getString("InfobaseDialog.PermissionCode")); //$NON-NLS-1$ + txtPermissionCode.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblDeniedParameter = new Label(container, SWT.NONE); + lblDeniedParameter.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblDeniedParameter.setText(Messages.getString("InfobaseDialog.DeniedParameter")); //$NON-NLS-1$ + + txtDeniedParameter = new Text(container, SWT.BORDER); + txtDeniedParameter.setToolTipText( + Messages.getString("InfobaseDialog.DeniedParameter")); //$NON-NLS-1$ + txtDeniedParameter.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + btnSheduledJobsDenied = new Button(container, SWT.CHECK); + btnSheduledJobsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnSheduledJobsDenied.setText( + Messages.getString("InfobaseDialog.SheduledJobsDenied")); //$NON-NLS-1$ + + Label lblExternalSessionManagerConnectionString = new Label(container, SWT.NONE); + lblExternalSessionManagerConnectionString.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblExternalSessionManagerConnectionString.setText( + Messages.getString("InfobaseDialog.ExternalSessionManagement")); //$NON-NLS-1$ + + txtExternalSessionManagerConnectionString = new Text(container, SWT.BORDER); + txtExternalSessionManagerConnectionString.setToolTipText( + Messages.getString("InfobaseDialog.ExternalSessionManagement")); //$NON-NLS-1$ + txtExternalSessionManagerConnectionString.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + btnExternalSessionManagerRequired = new Button(container, SWT.CHECK); + btnExternalSessionManagerRequired.setLayoutData( + new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); + btnExternalSessionManagerRequired.setText( + Messages.getString("InfobaseDialog.RequiredUseOfExternalManagement")); //$NON-NLS-1$ + + Label lblSecurityProfile = new Label(container, SWT.NONE); + lblSecurityProfile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSecurityProfile.setText(Messages.getString("InfobaseDialog.SecurityProfile")); //$NON-NLS-1$ + + txtSecurityProfile = new Text(container, SWT.BORDER); + txtSecurityProfile.setToolTipText( + Messages.getString("InfobaseDialog.SecurityProfile")); //$NON-NLS-1$ + txtSecurityProfile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblSafeModeSecurityProfile = new Label(container, SWT.NONE); + lblSafeModeSecurityProfile.setLayoutData( + new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblSafeModeSecurityProfile.setText( + Messages.getString("InfobaseDialog.SafeModeSecurityProfile")); //$NON-NLS-1$ + + txtSafeModeSecurityProfile = new Text(container, SWT.BORDER); + txtSafeModeSecurityProfile.setToolTipText( + Messages.getString("InfobaseDialog.SafeModeSecurityProfile")); //$NON-NLS-1$ + txtSafeModeSecurityProfile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + initInfobaseProperties(); + + return container; + } + + private void initInfobaseProperties() { + if (infoBaseId != null) { + + IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infoBaseId); + if (infoBaseInfo == null) { + close(); + return; + } + + // Common properties + txtInfobaseName.setText(infoBaseInfo.getName()); + txtInfobaseDescription.setText(infoBaseInfo.getDescr()); + comboSecurityLevel.setText(Integer.toString(infoBaseInfo.getSecurityLevel())); + btnAllowDistributeLicense.setSelection(infoBaseInfo.getLicenseDistributionAllowed() == 1); + btnSheduledJobsDenied.setSelection(infoBaseInfo.isScheduledJobsDenied()); + + // DB properties + txtServerDbName.setText(infoBaseInfo.getDbServerName()); + comboServerDbType.setText(infoBaseInfo.getDbms()); + txtDatabaseDbName.setText(infoBaseInfo.getDbName()); + txtDatabaseDbUser.setText(infoBaseInfo.getDbUser()); + txtDatabaseDbPassword.setText(infoBaseInfo.getDbPassword()); + + // Lock properties + btnSessionsDenied.setSelection(infoBaseInfo.isSessionsDenied()); + deniedFromDate.setText(convertDateToString(infoBaseInfo.getDeniedFrom())); + deniedToDate.setText(convertDateToString(infoBaseInfo.getDeniedTo())); + + txtDeniedMessage.setText(infoBaseInfo.getDeniedMessage()); + txtPermissionCode.setText(infoBaseInfo.getPermissionCode()); + txtDeniedParameter.setText(infoBaseInfo.getDeniedParameter()); + + // ExternalSessionManager properties + txtExternalSessionManagerConnectionString.setText( + infoBaseInfo.getExternalSessionManagerConnectionString()); + btnExternalSessionManagerRequired.setSelection( + infoBaseInfo.getExternalSessionManagerRequired()); + + // SecurityProfile properties + txtSecurityProfile.setText(infoBaseInfo.getSecurityProfileName()); + txtSafeModeSecurityProfile.setText(infoBaseInfo.getSafeModeSecurityProfileName()); + } + } + + private boolean checkVariablesFromControls() { + + var existsError = false; + + List checksTextControls = new ArrayList<>(); + checksTextControls.add(txtInfobaseName); + checksTextControls.add(txtServerDbName); + checksTextControls.add(txtDatabaseDbName); + checksTextControls.add(txtDatabaseDbUser); + + for (Text control : checksTextControls) { + if (control.getText().isBlank()) { + control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + existsError = true; + } else { + control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + } + } + + List checksDateControls = new ArrayList<>(); + checksDateControls.add(deniedFromDate); + checksDateControls.add(deniedToDate); + + for (Text control : checksDateControls) { + if (control.getText().isBlank()) { + control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + } else { + if (convertStringToDate(control.getText()).equals(new Date(0))) { + control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + existsError = true; + } + } + } + + return existsError; + } + + private boolean saveInfobaseProperties() { + + if (checkVariablesFromControls()) { + return false; + } + + IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infoBaseId); + if (infoBaseInfo == null) { + return false; + } + + // Common properties + infoBaseInfo.setName(txtInfobaseName.getText()); + infoBaseInfo.setDescr(txtInfobaseDescription.getText()); + infoBaseInfo.setLicenseDistributionAllowed(btnAllowDistributeLicense.getSelection() ? 1 : 0); + infoBaseInfo.setScheduledJobsDenied(btnSheduledJobsDenied.getSelection()); + + // DB properties + infoBaseInfo.setDbServerName(txtServerDbName.getText()); + infoBaseInfo.setDbms(comboServerDbType.getText()); + infoBaseInfo.setDbName(txtDatabaseDbName.getText()); + infoBaseInfo.setDbUser(txtDatabaseDbUser.getText()); + infoBaseInfo.setDbPassword(txtDatabaseDbPassword.getText()); + + // Lock properties + infoBaseInfo.setSessionsDenied(btnSessionsDenied.getSelection()); + infoBaseInfo.setDeniedFrom(convertStringToDate(deniedFromDate.getText())); + infoBaseInfo.setDeniedTo(convertStringToDate(deniedToDate.getText())); + + infoBaseInfo.setDeniedMessage(txtDeniedMessage.getText()); + infoBaseInfo.setPermissionCode(txtPermissionCode.getText()); + infoBaseInfo.setDeniedParameter(txtDeniedParameter.getText()); + + // ExternalSessionManager properties + infoBaseInfo.setExternalSessionManagerConnectionString( + txtExternalSessionManagerConnectionString.getText()); + infoBaseInfo.setExternalSessionManagerRequired( + btnExternalSessionManagerRequired.getSelection()); + + // SecurityProfile properties + infoBaseInfo.setSecurityProfileName(txtSecurityProfile.getText()); + infoBaseInfo.setSafeModeSecurityProfileName(txtSafeModeSecurityProfile.getText()); + + return server.updateInfoBase(clusterId, infoBaseInfo); + } + + private Date convertStringToDate(String date) { + + Date emptyDate = new Date(0); + + if (date.isBlank()) { + return emptyDate; + } + + Date convertDate; + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { + convertDate = dateFormat.parse(date); + } catch (ParseException excp) { + excp.printStackTrace(); + convertDate = emptyDate; + } + + return convertDate; + } + + private String convertDateToString(Date date) { + + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + Date emptyDate = new Date(0); + + return date.equals(emptyDate) ? "" : dateFormat.format(date); + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button buttonOk = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + buttonOk.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (saveInfobaseProperties()) { + close(); + } + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + + Button buttonApply = + createButton( + parent, + IDialogConstants.PROCEED_ID, + Messages.getString("Dialogs.Apply"), //$NON-NLS-1$ + false); + buttonApply.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + saveInfobaseProperties(); + } + }); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/Messages.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/Messages.java index 3e1e341..5de57dd 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/Messages.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/Messages.java @@ -3,19 +3,26 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; +/** Messages. */ public class Messages { - private static final String BUNDLE_NAME = "ru.yanygin.clusterAdminLibraryUI.messages"; //$NON-NLS-1$ - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); - - private Messages() { - } - - public static String getString(String key) { - try { - return RESOURCE_BUNDLE.getString(key); - } catch (MissingResourceException e) { - return '!' + key + '!'; - } - } + private static final String BUNDLE_NAME = + "ru.yanygin.clusterAdminLibraryUI.messages"; //$NON-NLS-1$ + + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); + + private Messages() {} + + /** + * Get the localized string. + * + * @param key - key of string + * @return localized string + */ + public static String getString(String key) { + try { + return RESOURCE_BUNDLE.getString(key); + } catch (MissingResourceException e) { + return '!' + key + '!'; + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java index 409e49f..7b10ce5 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java @@ -1,10 +1,12 @@ package ru.yanygin.clusterAdminLibraryUI; +import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; +import com._1c.v8.ibis.admin.ISessionInfo; +import com._1c.v8.ibis.admin.IWorkingProcessInfo; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -18,243 +20,254 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; - -import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; -import com._1c.v8.ibis.admin.ISessionInfo; -import com._1c.v8.ibis.admin.IWorkingProcessInfo; - import ru.yanygin.clusterAdminLibrary.Messages; import ru.yanygin.clusterAdminLibrary.Server; +/** The dialog box shows the session information. */ public class SessionInfoDialog extends Dialog { - - private UUID clusterId; - private UUID sessionId; - private ISessionInfo sessionInfo; - - private Server server; - private Text txtInfobaseName; - private Text txtLastActiveAt; - private Text txtClientIPAddress; - private Text txtUsername; - private Text txtApplication; - private Text txtStartedAt; - private Text txtComputer; - - private Text txtServer; - private Text txtPort; - private Text txtPID; - private Text txtConnectionNumber; - private Text txtLicense; - private Text txtSessionNumber; - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public SessionInfoDialog(Shell parentShell, Server server, UUID clusterId, UUID sessionId, ISessionInfo sessionInfo) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.server = server; - this.clusterId = clusterId; - this.sessionId = sessionId; - this.sessionInfo = sessionInfo; - - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.makeColumnsEqualWidth = true; - gridLayout.numColumns = 2; - - Label lblInfobaseName = new Label(container, SWT.NONE); - lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseName.setText(Messages.getString("SessionInfo.Infobase")); //$NON-NLS-1$ - - txtInfobaseName = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lbSessionNumber = new Label(container, SWT.NONE); - lbSessionNumber.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lbSessionNumber.setText(Messages.getString("SessionInfo.SessionN")); //$NON-NLS-1$ - - txtSessionNumber = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtSessionNumber.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblStartedAt = new Label(container, SWT.NONE); - lblStartedAt.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblStartedAt.setText(Messages.getString("SessionInfo.StartedAt")); //$NON-NLS-1$ - - txtStartedAt = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtStartedAt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblLastActiveAt = new Label(container, SWT.NONE); - lblLastActiveAt.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLastActiveAt.setText(Messages.getString("SessionInfo.LastActiveAt")); //$NON-NLS-1$ - - txtLastActiveAt = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtLastActiveAt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblComputer = new Label(container, SWT.NONE); - lblComputer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblComputer.setText(Messages.getString("SessionInfo.Computer")); //$NON-NLS-1$ - - txtComputer = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtComputer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblClientIPAddress = new Label(container, SWT.NONE); - lblClientIPAddress.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblClientIPAddress.setText(Messages.getString("SessionInfo.ClientIPAddress")); //$NON-NLS-1$ - - txtClientIPAddress = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtClientIPAddress.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblUsername = new Label(container, SWT.NONE); - lblUsername.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblUsername.setText(Messages.getString("SessionInfo.Username")); //$NON-NLS-1$ - - txtUsername = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblApplication = new Label(container, SWT.NONE); - lblApplication.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblApplication.setAlignment(SWT.RIGHT); - lblApplication.setText(Messages.getString("SessionInfo.Application")); //$NON-NLS-1$ - - txtApplication = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtApplication.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblServer = new Label(container, SWT.NONE); - lblServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServer.setText(Messages.getString("SessionInfo.Server")); //$NON-NLS-1$ - lblServer.setAlignment(SWT.RIGHT); - - txtServer = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtServer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblPort = new Label(container, SWT.NONE); - lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPort.setText(Messages.getString("SessionInfo.Port")); //$NON-NLS-1$ - lblPort.setAlignment(SWT.RIGHT); - - txtPort = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblPID = new Label(container, SWT.NONE); - lblPID.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPID.setText(Messages.getString("SessionInfo.PID")); //$NON-NLS-1$ - lblPID.setAlignment(SWT.RIGHT); - - txtPID = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtPID.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblConnectionNumber = new Label(container, SWT.NONE); - lblConnectionNumber.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblConnectionNumber.setText(Messages.getString("SessionInfo.ConnectionN")); //$NON-NLS-1$ - lblConnectionNumber.setAlignment(SWT.RIGHT); - - txtConnectionNumber = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtConnectionNumber.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - Label lblLicense = new Label(container, SWT.NONE); - lblLicense.setText(Messages.getString("SessionInfo.License")); //$NON-NLS-1$ - lblLicense.setAlignment(SWT.RIGHT); - new Label(container, SWT.NONE); - - txtLicense = new Text(container, SWT.BORDER | SWT.READ_ONLY); - txtLicense.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 2)); - - initInfobaseProperties(); - - return container; - } - - private void initInfobaseProperties() { - if (sessionInfo == null) - sessionInfo = server.getSessionInfo(clusterId, sessionId); - - if (sessionInfo == null) - return; - - UUID infobaseId = sessionInfo.getInfoBaseId(); - String infobaseName = server.getInfoBaseName(clusterId, infobaseId); - - UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ - - // connection - var connectionNumber = ""; //$NON-NLS-1$ - if (!sessionInfo.getConnectionId().equals(emptyUuid)) { - IInfoBaseConnectionShort connectionInfoShort = server.getConnectionInfoShort(clusterId, sessionInfo.getConnectionId()); - connectionNumber = String.valueOf(connectionInfoShort.getConnId()); - } - - // Working Process - var wpHostName = ""; //$NON-NLS-1$ - var wpMainPort = ""; //$NON-NLS-1$ - var wpPid = ""; //$NON-NLS-1$ - if (!sessionInfo.getWorkingProcessId().equals(emptyUuid)) { - IWorkingProcessInfo wpInfo = server.getWorkingProcessInfo(clusterId, sessionInfo.getWorkingProcessId()); - wpHostName = wpInfo.getHostName(); - wpMainPort = Integer.toString(wpInfo.getMainPort()); - wpPid = wpInfo.getPid(); - } - - // license - var license = sessionInfo.getLicenses().isEmpty() ? "" : sessionInfo.getLicenses().get(0).getFullPresentation(); //$NON-NLS-1$ - - txtInfobaseName.setText(infobaseName); - txtSessionNumber.setText(Integer.toString(sessionInfo.getSessionId())); - txtStartedAt.setText(dateToString(sessionInfo.getStartedAt())); - txtLastActiveAt.setText(dateToString(sessionInfo.getLastActiveAt())); - - txtComputer.setText(sessionInfo.getHost()); - String clientIPAddress = sessionInfo.getClientIPAddress() == null ? "" : sessionInfo.getClientIPAddress(); //8.3.17+ - txtClientIPAddress.setText(clientIPAddress); - txtUsername.setText(sessionInfo.getUserName()); - txtApplication.setText(server.getApplicationName(sessionInfo.getAppId())); - - txtServer.setText(wpHostName); - txtPort.setText(wpMainPort); - txtPID.setText(wpPid); - txtConnectionNumber.setText(connectionNumber); - txtLicense.setText(license); - - - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - close(); - } - }); - } - - private String dateToString(Date date) { - - DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); //$NON-NLS-1$ - Date emptyDate = new Date(0); - - return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ - } + private UUID clusterId; + private UUID sessionId; + private ISessionInfo sessionInfo; + + private Server server; + private Text txtInfobaseName; + private Text txtLastActiveAt; + private Text txtClientIpAddress; + private Text txtUsername; + private Text txtApplication; + private Text txtStartedAt; + private Text txtComputer; + + private Text txtServer; + private Text txtPort; + private Text txtPid; + private Text txtConnectionNumber; + private Text txtLicense; + private Text txtSessionNumber; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server parameters + * @param clusterId - cluster ID + * @param sessionId - session ID + * @param sessionInfo - session info + */ + public SessionInfoDialog( + Shell parentShell, Server server, UUID clusterId, UUID sessionId, ISessionInfo sessionInfo) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.server = server; + this.clusterId = clusterId; + this.sessionId = sessionId; + this.sessionInfo = sessionInfo; + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.makeColumnsEqualWidth = true; + gridLayout.numColumns = 2; + + Label lblInfobaseName = new Label(container, SWT.NONE); + lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblInfobaseName.setText(Messages.getString("SessionInfo.Infobase")); //$NON-NLS-1$ + + txtInfobaseName = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lbSessionNumber = new Label(container, SWT.NONE); + lbSessionNumber.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lbSessionNumber.setText(Messages.getString("SessionInfo.SessionN")); //$NON-NLS-1$ + + txtSessionNumber = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtSessionNumber.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblStartedAt = new Label(container, SWT.NONE); + lblStartedAt.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblStartedAt.setText(Messages.getString("SessionInfo.StartedAt")); //$NON-NLS-1$ + + txtStartedAt = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtStartedAt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblLastActiveAt = new Label(container, SWT.NONE); + lblLastActiveAt.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblLastActiveAt.setText(Messages.getString("SessionInfo.LastActiveAt")); //$NON-NLS-1$ + + txtLastActiveAt = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtLastActiveAt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblComputer = new Label(container, SWT.NONE); + lblComputer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblComputer.setText(Messages.getString("SessionInfo.Computer")); //$NON-NLS-1$ + + txtComputer = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtComputer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblClientIpAddress = new Label(container, SWT.NONE); + lblClientIpAddress.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblClientIpAddress.setText(Messages.getString("SessionInfo.ClientIPAddress")); //$NON-NLS-1$ + + txtClientIpAddress = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtClientIpAddress.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblUsername = new Label(container, SWT.NONE); + lblUsername.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblUsername.setText(Messages.getString("SessionInfo.Username")); //$NON-NLS-1$ + + txtUsername = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblApplication = new Label(container, SWT.NONE); + lblApplication.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblApplication.setAlignment(SWT.RIGHT); + lblApplication.setText(Messages.getString("SessionInfo.Application")); //$NON-NLS-1$ + + txtApplication = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtApplication.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblServer = new Label(container, SWT.NONE); + lblServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblServer.setText(Messages.getString("SessionInfo.Server")); //$NON-NLS-1$ + lblServer.setAlignment(SWT.RIGHT); + + txtServer = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtServer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblPort = new Label(container, SWT.NONE); + lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblPort.setText(Messages.getString("SessionInfo.Port")); //$NON-NLS-1$ + lblPort.setAlignment(SWT.RIGHT); + + txtPort = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblPid = new Label(container, SWT.NONE); + lblPid.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblPid.setText(Messages.getString("SessionInfo.PID")); //$NON-NLS-1$ + lblPid.setAlignment(SWT.RIGHT); + + txtPid = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtPid.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblConnectionNumber = new Label(container, SWT.NONE); + lblConnectionNumber.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); + lblConnectionNumber.setText(Messages.getString("SessionInfo.ConnectionN")); //$NON-NLS-1$ + lblConnectionNumber.setAlignment(SWT.RIGHT); + + txtConnectionNumber = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtConnectionNumber.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + Label lblLicense = new Label(container, SWT.NONE); + lblLicense.setText(Messages.getString("SessionInfo.License")); //$NON-NLS-1$ + lblLicense.setAlignment(SWT.RIGHT); + new Label(container, SWT.NONE); + + txtLicense = new Text(container, SWT.BORDER | SWT.READ_ONLY); + txtLicense.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 2)); + + initInfobaseProperties(); + + return container; + } + + private void initInfobaseProperties() { + if (sessionInfo == null) { + sessionInfo = server.getSessionInfo(clusterId, sessionId); + } + + if (sessionInfo == null) { + return; + } + + UUID infobaseId = sessionInfo.getInfoBaseId(); + String infobaseName = server.getInfoBaseName(clusterId, infobaseId); + + UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ + + // connection + var connectionNumber = ""; //$NON-NLS-1$ + if (!sessionInfo.getConnectionId().equals(emptyUuid)) { + IInfoBaseConnectionShort connectionInfoShort = + server.getConnectionInfoShort(clusterId, sessionInfo.getConnectionId()); + connectionNumber = String.valueOf(connectionInfoShort.getConnId()); + } + + // Working Process + var wpHostName = ""; //$NON-NLS-1$ + var wpMainPort = ""; //$NON-NLS-1$ + var wpPid = ""; //$NON-NLS-1$ + if (!sessionInfo.getWorkingProcessId().equals(emptyUuid)) { + IWorkingProcessInfo wpInfo = + server.getWorkingProcessInfo(clusterId, sessionInfo.getWorkingProcessId()); + wpHostName = wpInfo.getHostName(); + wpMainPort = Integer.toString(wpInfo.getMainPort()); + wpPid = wpInfo.getPid(); + } + + txtInfobaseName.setText(infobaseName); + txtSessionNumber.setText(Integer.toString(sessionInfo.getSessionId())); + txtStartedAt.setText(dateToString(sessionInfo.getStartedAt())); + txtLastActiveAt.setText(dateToString(sessionInfo.getLastActiveAt())); + + txtComputer.setText(sessionInfo.getHost()); + + var clientIpAddress = + sessionInfo.getClientIPAddress() == null + ? "" //$NON-NLS-1$ + : sessionInfo.getClientIPAddress(); // 8.3.17+ + txtClientIpAddress.setText(clientIpAddress); + txtUsername.setText(sessionInfo.getUserName()); + txtApplication.setText(server.getApplicationName(sessionInfo.getAppId())); + + txtServer.setText(wpHostName); + txtPort.setText(wpMainPort); + txtPid.setText(wpPid); + txtConnectionNumber.setText(connectionNumber); + + var license = + sessionInfo.getLicenses().isEmpty() + ? "" //$NON-NLS-1$ + : sessionInfo.getLicenses().get(0).getFullPresentation(); + txtLicense.setText(license); + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.CLOSE_ID, IDialogConstants.CLOSE_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + close(); + } + }); + } + + private String dateToString(Date date) { + + DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); //$NON-NLS-1$ + Date emptyDate = new Date(0); + + return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java index 4e8da03..d52c28b 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java @@ -1,13 +1,11 @@ package ru.yanygin.clusterAdminLibraryUI; import java.util.Locale; - import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -17,225 +15,239 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; - import ru.yanygin.clusterAdminLibrary.ClusterProvider; import ru.yanygin.clusterAdminLibrary.Config; +/** Dialog for edit server settings. */ public class SettingsDialog extends Dialog { - - private Config config; - private Button btnShowWorkingServers; - private Button btnShowWorkingProcesses; - private Button btnExpandServers; - private Button btnExpandClusters; - private Button btnExpandInfobases; - private Button btnExpandWorkingServers; - private Button btnExpandWorkingProcesses; - private Button btnShowServerVersion; - private Button btnShowServerDescription; - private Button btnShowInfobaseDescription; - private Button btnShowLocalRasConnectInfo; - private Button btnLocaleSystem; - private Button btnLocaleEnglish; - private Button btnLocaleRussian; - private Text txtHighlightDuration; - private Button btnHighlightNewItems; - private Button btnShadowSleepSessions; - private Button btnReadClipboard; - - /** - * Create the dialog. - * @param parentShell - * @param serverParams - */ - public SettingsDialog(Shell parentShell) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - -// super.configureShell(parentShell); -// parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.config = ClusterProvider.getCommonConfig(); - } - - /** - * Create contents of the dialog. - * @param parent - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.numColumns = 3; - - Group grpShowNodesIn = new Group(container, SWT.NONE); - grpShowNodesIn.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpShowNodesIn.setText(Messages.getString("SettingsDialog.ShowNodesInTree")); //$NON-NLS-1$ - grpShowNodesIn.setLayout(new GridLayout(1, false)); - - btnShowWorkingServers = new Button(grpShowNodesIn, SWT.CHECK); - btnShowWorkingServers.setText(Messages.getString("SettingsDialog.ShowWorkingServers")); //$NON-NLS-1$ - - btnShowWorkingProcesses = new Button(grpShowNodesIn, SWT.CHECK); - btnShowWorkingProcesses.setText(Messages.getString("SettingsDialog.ShowWorkingProcesses")); //$NON-NLS-1$ - - Group grpExpandNodes = new Group(container, SWT.NONE); - grpExpandNodes.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpExpandNodes.setText(Messages.getString("SettingsDialog.ExpandNodesInTree")); //$NON-NLS-1$ - grpExpandNodes.setLayout(new GridLayout(1, false)); - - btnExpandServers = new Button(grpExpandNodes, SWT.CHECK); - btnExpandServers.setText(Messages.getString("SettingsDialog.ExpandServers")); //$NON-NLS-1$ - - btnExpandClusters = new Button(grpExpandNodes, SWT.CHECK); - btnExpandClusters.setText(Messages.getString("SettingsDialog.ExpandClusters")); //$NON-NLS-1$ - - btnExpandInfobases = new Button(grpExpandNodes, SWT.CHECK); - btnExpandInfobases.setText(Messages.getString("SettingsDialog.ExpandInfobases")); //$NON-NLS-1$ - - btnExpandWorkingServers = new Button(grpExpandNodes, SWT.CHECK); - btnExpandWorkingServers.setText(Messages.getString("SettingsDialog.ExpandWorkingServers")); //$NON-NLS-1$ - - btnExpandWorkingProcesses = new Button(grpExpandNodes, SWT.CHECK); - btnExpandWorkingProcesses.setText(Messages.getString("SettingsDialog.ExpandWorkingProcesses")); //$NON-NLS-1$ - - Group grpShowInfo = new Group(container, SWT.NONE); - grpShowInfo.setText(Messages.getString("SettingsDialog.ShowInfo")); //$NON-NLS-1$ - grpShowInfo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpShowInfo.setLayout(new GridLayout(1, false)); - - btnShowServerVersion = new Button(grpShowInfo, SWT.CHECK); - btnShowServerVersion.setText(Messages.getString("SettingsDialog.ShowServerVersion")); //$NON-NLS-1$ - - btnShowServerDescription = new Button(grpShowInfo, SWT.CHECK); - btnShowServerDescription.setText(Messages.getString("SettingsDialog.ShowServerDescription")); //$NON-NLS-1$ - - btnShowInfobaseDescription = new Button(grpShowInfo, SWT.CHECK); - btnShowInfobaseDescription.setText(Messages.getString("SettingsDialog.ShowInfobaseDescription")); //$NON-NLS-1$ - - btnShowLocalRasConnectInfo = new Button(grpShowInfo, SWT.CHECK); - btnShowLocalRasConnectInfo.setText(Messages.getString("SettingsDialog.ShowLocalRASConnectInfo")); - - Group grpLocale = new Group(container, SWT.NONE); - grpLocale.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpLocale.setText(Messages.getString("SettingsDialog.Locale")); //$NON-NLS-1$ - grpLocale.setLayout(new GridLayout(1, false)); - - btnLocaleSystem = new Button(grpLocale, SWT.RADIO); - btnLocaleSystem.setText(Messages.getString("SettingsDialog.System")); //$NON-NLS-1$ - - btnLocaleEnglish = new Button(grpLocale, SWT.RADIO); - btnLocaleEnglish.setText(Messages.getString("SettingsDialog.English")); //$NON-NLS-1$ - - btnLocaleRussian = new Button(grpLocale, SWT.RADIO); - btnLocaleRussian.setText(Messages.getString("SettingsDialog.Russian")); //$NON-NLS-1$ - - Group grpHighlight = new Group(container, SWT.NONE); - grpHighlight.setText(Messages.getString("SettingsDialog.Highlight")); //$NON-NLS-1$ - grpHighlight.setLayout(new GridLayout(2, false)); - - btnHighlightNewItems = new Button(grpHighlight, SWT.CHECK); - btnHighlightNewItems.setText(Messages.getString("SettingsDialog.HighlightNewItems")); //$NON-NLS-1$ - new Label(grpHighlight, SWT.NONE); - - Label lblHighlightDuration = new Label(grpHighlight, SWT.NONE); - lblHighlightDuration.setBounds(0, 0, 55, 15); - lblHighlightDuration.setText(Messages.getString("SettingsDialog.HighlightDuration")); - - txtHighlightDuration = new Text(grpHighlight, SWT.BORDER); - GridData gdtxtHighlightDuration = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdtxtHighlightDuration.widthHint = 20; - txtHighlightDuration.setLayoutData(gdtxtHighlightDuration); - txtHighlightDuration.setBounds(0, 0, 76, 21); - - btnShadowSleepSessions = new Button(grpHighlight, SWT.CHECK); - btnShadowSleepSessions.setText(Messages.getString("SettingsDialog.ShadowSleepSessions")); //$NON-NLS-1$ - new Label(grpHighlight, SWT.NONE); - - btnReadClipboard = new Button(container, SWT.CHECK); - btnReadClipboard.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); - btnReadClipboard.setText(Messages.getString("SettingsDialog.ReadClipboard")); - - initProperties(); - - return container; - } - - private void initProperties() { - - btnShowWorkingServers.setSelection(config.showWorkingServersTree); - btnShowWorkingProcesses.setSelection(config.showWorkingProcessesTree); - - btnExpandServers.setSelection(config.expandServersTree); - btnExpandClusters.setSelection(config.expandClustersTree); - btnExpandInfobases.setSelection(config.expandInfobasesTree); - btnExpandWorkingServers.setSelection(config.expandWorkingServersTree); - btnExpandWorkingProcesses.setSelection(config.expandWorkingProcessesTree); - - btnShowServerVersion.setSelection(config.showServerVersion); - btnShowServerDescription.setSelection(config.showServerDescription); - btnShowInfobaseDescription.setSelection(config.showInfobaseDescription); - btnShowLocalRasConnectInfo.setSelection(config.showLocalRasConnectInfo); - - btnHighlightNewItems.setSelection(config.highlightNewItems); - txtHighlightDuration.setText(Integer.toString(config.highlightNewItemsDuration)); - btnShadowSleepSessions.setSelection(config.shadowSleepSessions); - btnReadClipboard.setSelection(config.readClipboard); - - if (config.locale == null) { - btnLocaleSystem.setSelection(true); - } else { - btnLocaleEnglish.setSelection(config.locale.equals(Locale.ENGLISH.toLanguageTag())); - btnLocaleRussian.setSelection(config.locale.equals("ru-RU")); //$NON-NLS-1$ - } - } - - private void saveProperties() { - - config.showWorkingServersTree = btnShowWorkingServers.getSelection(); - config.showWorkingProcessesTree = btnShowWorkingProcesses.getSelection(); - - config.expandServersTree = btnExpandServers.getSelection(); - config.expandClustersTree = btnExpandClusters.getSelection(); - config.expandInfobasesTree = btnExpandInfobases.getSelection(); - config.expandWorkingServersTree = btnExpandWorkingServers.getSelection(); - config.expandWorkingProcessesTree = btnExpandWorkingProcesses.getSelection(); - - config.showServerVersion = btnShowServerVersion.getSelection(); - config.showServerDescription = btnShowServerDescription.getSelection(); - config.showInfobaseDescription = btnShowInfobaseDescription.getSelection(); - config.showLocalRasConnectInfo = btnShowLocalRasConnectInfo.getSelection(); - - config.highlightNewItems = btnHighlightNewItems.getSelection(); - config.highlightNewItemsDuration = Integer.parseInt(txtHighlightDuration.getText()); - config.shadowSleepSessions = btnShadowSleepSessions.getSelection(); - config.readClipboard = btnReadClipboard.getSelection(); - - if (btnLocaleSystem.getSelection()) - config.locale = null; - else if (btnLocaleEnglish.getSelection()) - config.locale = Locale.ENGLISH.toLanguageTag(); - else if (btnLocaleRussian.getSelection()) - config.locale = "ru-RU"; //$NON-NLS-1$ - } - - /** - * Create contents of the button bar. - * @param parent - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - saveProperties(); - close(); - } - }); - - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } + private Config config; + private Button btnShowWorkingServers; + private Button btnShowWorkingProcesses; + private Button btnExpandServers; + private Button btnExpandClusters; + private Button btnExpandInfobases; + private Button btnExpandWorkingServers; + private Button btnExpandWorkingProcesses; + private Button btnShowServerVersion; + private Button btnShowServerDescription; + private Button btnShowInfobaseDescription; + private Button btnShowLocalRasConnectInfo; + private Button btnLocaleSystem; + private Button btnLocaleEnglish; + private Button btnLocaleRussian; + private Text txtHighlightDuration; + private Button btnHighlightNewItems; + private Button btnShadowSleepSessions; + private Button btnReadClipboard; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + */ + public SettingsDialog(Shell parentShell) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + // super.configureShell(parentShell); + // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + + this.config = ClusterProvider.getCommonConfig(); + } + + /** + * Create contents of the dialog. + * + * @param parent - parent control + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.numColumns = 3; + + Group grpShowNodesIn = new Group(container, SWT.NONE); + grpShowNodesIn.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); + grpShowNodesIn.setText(Messages.getString("SettingsDialog.ShowNodesInTree")); //$NON-NLS-1$ + grpShowNodesIn.setLayout(new GridLayout(1, false)); + + btnShowWorkingServers = new Button(grpShowNodesIn, SWT.CHECK); + btnShowWorkingServers.setText( + Messages.getString("SettingsDialog.ShowWorkingServers")); //$NON-NLS-1$ + + btnShowWorkingProcesses = new Button(grpShowNodesIn, SWT.CHECK); + btnShowWorkingProcesses.setText( + Messages.getString("SettingsDialog.ShowWorkingProcesses")); //$NON-NLS-1$ + + Group grpExpandNodes = new Group(container, SWT.NONE); + grpExpandNodes.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); + grpExpandNodes.setText(Messages.getString("SettingsDialog.ExpandNodesInTree")); //$NON-NLS-1$ + grpExpandNodes.setLayout(new GridLayout(1, false)); + + btnExpandServers = new Button(grpExpandNodes, SWT.CHECK); + btnExpandServers.setText(Messages.getString("SettingsDialog.ExpandServers")); //$NON-NLS-1$ + + btnExpandClusters = new Button(grpExpandNodes, SWT.CHECK); + btnExpandClusters.setText(Messages.getString("SettingsDialog.ExpandClusters")); //$NON-NLS-1$ + + btnExpandInfobases = new Button(grpExpandNodes, SWT.CHECK); + btnExpandInfobases.setText(Messages.getString("SettingsDialog.ExpandInfobases")); //$NON-NLS-1$ + + btnExpandWorkingServers = new Button(grpExpandNodes, SWT.CHECK); + btnExpandWorkingServers.setText( + Messages.getString("SettingsDialog.ExpandWorkingServers")); //$NON-NLS-1$ + + btnExpandWorkingProcesses = new Button(grpExpandNodes, SWT.CHECK); + btnExpandWorkingProcesses.setText( + Messages.getString("SettingsDialog.ExpandWorkingProcesses")); //$NON-NLS-1$ + + Group grpShowInfo = new Group(container, SWT.NONE); + grpShowInfo.setText(Messages.getString("SettingsDialog.ShowInfo")); //$NON-NLS-1$ + grpShowInfo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); + grpShowInfo.setLayout(new GridLayout(1, false)); + + btnShowServerVersion = new Button(grpShowInfo, SWT.CHECK); + btnShowServerVersion.setText( + Messages.getString("SettingsDialog.ShowServerVersion")); //$NON-NLS-1$ + + btnShowServerDescription = new Button(grpShowInfo, SWT.CHECK); + btnShowServerDescription.setText( + Messages.getString("SettingsDialog.ShowServerDescription")); //$NON-NLS-1$ + + btnShowInfobaseDescription = new Button(grpShowInfo, SWT.CHECK); + btnShowInfobaseDescription.setText( + Messages.getString("SettingsDialog.ShowInfobaseDescription")); //$NON-NLS-1$ + + btnShowLocalRasConnectInfo = new Button(grpShowInfo, SWT.CHECK); + btnShowLocalRasConnectInfo.setText( + Messages.getString("SettingsDialog.ShowLocalRASConnectInfo")); + + Group grpLocale = new Group(container, SWT.NONE); + grpLocale.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); + grpLocale.setText(Messages.getString("SettingsDialog.Locale")); //$NON-NLS-1$ + grpLocale.setLayout(new GridLayout(1, false)); + + btnLocaleSystem = new Button(grpLocale, SWT.RADIO); + btnLocaleSystem.setText(Messages.getString("SettingsDialog.System")); //$NON-NLS-1$ + + btnLocaleEnglish = new Button(grpLocale, SWT.RADIO); + btnLocaleEnglish.setText(Messages.getString("SettingsDialog.English")); //$NON-NLS-1$ + + btnLocaleRussian = new Button(grpLocale, SWT.RADIO); + btnLocaleRussian.setText(Messages.getString("SettingsDialog.Russian")); //$NON-NLS-1$ + + Group grpHighlight = new Group(container, SWT.NONE); + grpHighlight.setText(Messages.getString("SettingsDialog.Highlight")); //$NON-NLS-1$ + grpHighlight.setLayout(new GridLayout(2, false)); + + btnHighlightNewItems = new Button(grpHighlight, SWT.CHECK); + btnHighlightNewItems.setText( + Messages.getString("SettingsDialog.HighlightNewItems")); //$NON-NLS-1$ + new Label(grpHighlight, SWT.NONE); + + Label lblHighlightDuration = new Label(grpHighlight, SWT.NONE); + lblHighlightDuration.setBounds(0, 0, 55, 15); + lblHighlightDuration.setText(Messages.getString("SettingsDialog.HighlightDuration")); + + txtHighlightDuration = new Text(grpHighlight, SWT.BORDER); + GridData gdtxtHighlightDuration = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdtxtHighlightDuration.widthHint = 20; + txtHighlightDuration.setLayoutData(gdtxtHighlightDuration); + txtHighlightDuration.setBounds(0, 0, 76, 21); + + btnShadowSleepSessions = new Button(grpHighlight, SWT.CHECK); + btnShadowSleepSessions.setText( + Messages.getString("SettingsDialog.ShadowSleepSessions")); //$NON-NLS-1$ + new Label(grpHighlight, SWT.NONE); + + btnReadClipboard = new Button(container, SWT.CHECK); + btnReadClipboard.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); + btnReadClipboard.setText(Messages.getString("SettingsDialog.ReadClipboard")); + + initProperties(); + + return container; + } + + private void initProperties() { + + btnShowWorkingServers.setSelection(config.isShowWorkingServersTree()); + btnShowWorkingProcesses.setSelection(config.isShowWorkingProcessesTree()); + + btnExpandServers.setSelection(config.isExpandServersTree()); + btnExpandClusters.setSelection(config.isExpandClustersTree()); + btnExpandInfobases.setSelection(config.isExpandInfobasesTree()); + btnExpandWorkingServers.setSelection(config.isExpandWorkingServersTree()); + btnExpandWorkingProcesses.setSelection(config.isExpandWorkingProcessesTree()); + + btnShowServerVersion.setSelection(config.isShowServerVersion()); + btnShowServerDescription.setSelection(config.isShowServerDescription()); + btnShowInfobaseDescription.setSelection(config.isShowInfobaseDescription()); + btnShowLocalRasConnectInfo.setSelection(config.isShowLocalRasConnectInfo()); + + btnHighlightNewItems.setSelection(config.isHighlightNewItems()); + txtHighlightDuration.setText(Integer.toString(config.getHighlightNewItemsDuration())); + btnShadowSleepSessions.setSelection(config.isShadowSleepSessions()); + btnReadClipboard.setSelection(config.isReadClipboard()); + + if (config.getLocale() == null) { + btnLocaleSystem.setSelection(true); + } else { + btnLocaleEnglish.setSelection(config.getLocale().equals(Locale.ENGLISH.toLanguageTag())); + btnLocaleRussian.setSelection(config.getLocale().equals("ru-RU")); //$NON-NLS-1$ + } + } + + private void saveProperties() { + + config.setShowWorkingServersTree(btnShowWorkingServers.getSelection()); + config.setShowWorkingProcessesTree(btnShowWorkingProcesses.getSelection()); + + config.setExpandServersTree(btnExpandServers.getSelection()); + config.setExpandClustersTree(btnExpandClusters.getSelection()); + config.setExpandInfobasesTree(btnExpandInfobases.getSelection()); + config.setExpandWorkingServersTree(btnExpandWorkingServers.getSelection()); + config.setExpandWorkingProcessesTree(btnExpandWorkingProcesses.getSelection()); + + config.setShowServerVersion(btnShowServerVersion.getSelection()); + config.setShowServerDescription(btnShowServerDescription.getSelection()); + config.setShowInfobaseDescription(btnShowInfobaseDescription.getSelection()); + config.setShowLocalRasConnectInfo(btnShowLocalRasConnectInfo.getSelection()); + + config.setHighlightNewItems(btnHighlightNewItems.getSelection()); + config.setHighlightNewItemsDuration(Integer.parseInt(txtHighlightDuration.getText())); + config.setShadowSleepSessions(btnShadowSleepSessions.getSelection()); + config.setReadClipboard(btnReadClipboard.getSelection()); + + if (btnLocaleSystem.getSelection()) { + config.setLocale(null); + } else if (btnLocaleEnglish.getSelection()) { + config.setLocale(Locale.ENGLISH.toLanguageTag()); + } else if (btnLocaleRussian.getSelection()) { + config.setLocale("ru-RU"); //$NON-NLS-1$ + } + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + saveProperties(); + close(); + } + }); + + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java index 35b95d0..8afcda2 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java @@ -1,26 +1,22 @@ package ru.yanygin.clusterAdminLibraryUI; -import java.text.Collator; +import com._1c.v8.ibis.admin.IClusterInfo; +import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; +import com._1c.v8.ibis.admin.IInfoBaseInfo; +import com._1c.v8.ibis.admin.IInfoBaseInfoShort; +import com._1c.v8.ibis.admin.IObjectLockInfo; +import com._1c.v8.ibis.admin.ISessionInfo; +import com._1c.v8.ibis.admin.IWorkingProcessInfo; +import com._1c.v8.ibis.admin.IWorkingServerInfo; import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; -import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.stream.Collectors; - import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; -import org.eclipse.swt.dnd.Clipboard; -import org.eclipse.swt.dnd.TextTransfer; -import org.eclipse.swt.dnd.Transfer; -import org.eclipse.swt.events.ControlAdapter; -import org.eclipse.swt.events.ControlEvent; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; @@ -29,19 +25,13 @@ import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Cursor; -import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; -import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; @@ -56,18 +46,8 @@ import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; -import org.eclipse.swt.widgets.Widget; - -import com._1c.v8.ibis.admin.IClusterInfo; -import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; -import com._1c.v8.ibis.admin.IInfoBaseInfo; -import com._1c.v8.ibis.admin.IInfoBaseInfoShort; -import com._1c.v8.ibis.admin.IObjectLockInfo; -import com._1c.v8.ibis.admin.IPortRangeInfo; -import com._1c.v8.ibis.admin.ISessionInfo; -import com._1c.v8.ibis.admin.IWorkingProcessInfo; -import com._1c.v8.ibis.admin.IWorkingServerInfo; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import ru.yanygin.clusterAdminLibrary.ClusterProvider; import ru.yanygin.clusterAdminLibrary.ColumnProperties; import ru.yanygin.clusterAdminLibrary.Config; @@ -79,2300 +59,2543 @@ import ru.yanygin.clusterAdminLibrary.WorkingProcessInfoExtended; import ru.yanygin.clusterAdminLibrary.WorkingServerInfoExtended; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +/** Area for viewing servers. */ public class ViewerArea extends Composite { - - Image serverIcon; - Image serverIconUp; - Image serverIconDown; - Image serverIconConnecting; - Image workingServerIcon; - Image infobaseIcon; - Image infobasesIcon; - Image clusterIcon; - Image userIcon; - Image sleepUserIcon; - Image serviceIcon; - Image connectionIcon; - Image locksIcon; - Image workingProcessesIcon; - Image workingProcessIcon; - Image connectActionIcon; - Image disconnectActionIcon; - Image editIcon; - Image addIcon; - Image deleteIcon; - Image lockUsersIcon; - Image updateIcon; - - Tree serversTree; - TreeItem currentTreeItem; - Menu serverMenu; - MenuItem menuItemConnectServer; - MenuItem menuItemDisconnectServer; - MenuItem menuItemShowConnectionError; - Menu clusterMenu; - Menu workingServerMenu; - Menu infobaseNodeMenu; - Menu infobaseMenu; - - TabItem tabSessions; - TabItem tabConnections; - TabItem tabLocks; - TabItem tabWorkingProcesses; - TabItem tabWorkingServers; - TabItem currentTabitem; - - Table tableSessions; - Table tableConnections; - Table tableLocks; - Table tableWorkingProcesses; - Table tableWorkingServers; -// Menu tableSessionsMenu; - - Map sessionColumnsMap = new LinkedHashMap<>(); - Map connectionColumnsMap = new LinkedHashMap<>(); - Map lockColumnsMap = new LinkedHashMap<>(); - Map wpColumnsMap = new LinkedHashMap<>(); - Map wsColumnsMap = new LinkedHashMap<>(); - - TreeColumn columnServer; - -// UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ - static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ - - static final Color standardColor = new Color(0, 0, 0); - static final Color newItemColor = new Color(0, 200, 0); - static final Color deletedItemColor = new Color(150,0,0); - static final Color shadowItemColor = new Color(160, 160, 160); - static final Color watchedSessionColor = new Color(0, 128, 255); - - FontData systemFontData = getDisplay().getSystemFont().getFontData()[0]; - Font fontNormal = new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.NORMAL); - Font fontBold = new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.BOLD); - TableItem lastSelectItem = null; - int lastSelectColumn; - List watchedSessions = new ArrayList<>(); - - enum TreeItemType { - SERVER, CLUSTER, INFOBASE_NODE, INFOBASE, WORKINGPROCESS_NODE, WORKINGPROCESS, WORKINGSERVER_NODE, WORKINGSERVER - } - - static final String SERVER_INFO = "ServerInfo"; //$NON-NLS-1$ - static final String CLUSTER_ID = "ClusterId"; //$NON-NLS-1$ - static final String INFOBASE_ID = "InfobaseId"; //$NON-NLS-1$ - static final String WORKINGPROCESS_ID = "WorkingProcessId"; //$NON-NLS-1$ - static final String WORKINGSERVER_ID = "WorkingServerId"; //$NON-NLS-1$ - static final String SESSION_ID = "SessionId"; //$NON-NLS-1$ - static final String CONNECTION_ID = "ConnectionId"; //$NON-NLS-1$ - - ClusterProvider clusterProvider; - - //@Slf4j - public ViewerArea(Composite parent, int style, Menu menu, ToolBar toolBar, ClusterProvider clusterProvider) { - super(parent, style); - - this.clusterProvider = clusterProvider; - - this.clusterProvider.readConfig(ClusterProvider.DEFAULT_CONFIG_PATH); - - SashForm sashForm = new SashForm(this, SWT.NONE); - - initIcon(); - -// toolBar = new ToolBar(this, SWT.FLAT | SWT.RIGHT); // Для отладки -// toolBar.setBounds(0, 0, 500, 23); // Для отладки - -// initToolbar(parent, toolBar); - initMainMenu(sashForm, menu); - - initServersTree(sashForm); - - TabFolder tabFolder = new TabFolder(sashForm, SWT.NONE); - - tabFolder.addSelectionListener(new SelectionAdapter() { - - @Override - public void widgetSelected(SelectionEvent evt) { - currentTabitem = tabFolder.getSelection()[0]; - clickItemInServerTree(1); + + Image serverIcon; + Image serverIconUp; + Image serverIconDown; + Image serverIconConnecting; + Image workingServerIcon; + Image infobaseIcon; + Image infobasesIcon; + Image clusterIcon; + Image userIcon; + Image sleepUserIcon; + Image serviceIcon; + Image connectionIcon; + Image locksIcon; + Image workingProcessesIcon; + Image workingProcessIcon; + Image connectActionIcon; + Image disconnectActionIcon; + Image editIcon; + Image addIcon; + Image deleteIcon; + Image lockUsersIcon; + Image updateIcon; + + Tree serversTree; + TreeItem currentTreeItem; + Menu serverMenu; + MenuItem menuItemConnectServer; + MenuItem menuItemDisconnectServer; + MenuItem menuItemShowConnectionError; + Menu clusterMenu; + Menu workingServerMenu; + Menu infobaseNodeMenu; + Menu infobaseMenu; + + TabItem tabSessions; + TabItem tabConnections; + TabItem tabLocks; + TabItem tabWorkingProcesses; + TabItem tabWorkingServers; + TabItem currentTabitem; + + Table tableSessions; + Table tableConnections; + Table tableLocks; + Table tableWorkingProcesses; + Table tableWorkingServers; + // Menu tableSessionsMenu; + + Map sessionColumnsMap = new LinkedHashMap<>(); + Map connectionColumnsMap = new LinkedHashMap<>(); + Map lockColumnsMap = new LinkedHashMap<>(); + Map wpColumnsMap = new LinkedHashMap<>(); + Map wsColumnsMap = new LinkedHashMap<>(); + + TreeColumn columnServer; + + static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ + + static final Color standardColor = new Color(0, 0, 0); + static final Color newItemColor = new Color(0, 200, 0); + static final Color deletedItemColor = new Color(150, 0, 0); + static final Color shadowItemColor = new Color(160, 160, 160); + static final Color watchedSessionColor = new Color(0, 128, 255); + + FontData systemFontData = getDisplay().getSystemFont().getFontData()[0]; + Font fontNormal = + new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.NORMAL); + Font fontBold = + new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.BOLD); + TableItem lastSelectItem = null; + int lastSelectColumn; + List watchedSessions = new ArrayList<>(); + + enum TreeItemType { + SERVER, + CLUSTER, + INFOBASE_NODE, + INFOBASE, + WORKINGPROCESS_NODE, + WORKINGPROCESS, + WORKINGSERVER_NODE, + WORKINGSERVER + } + + static final String SERVER_INFO = "ServerInfo"; //$NON-NLS-1$ + static final String CLUSTER_ID = "ClusterId"; //$NON-NLS-1$ + static final String INFOBASE_ID = "InfobaseId"; //$NON-NLS-1$ + static final String WORKINGPROCESS_ID = "WorkingProcessId"; //$NON-NLS-1$ + static final String WORKINGSERVER_ID = "WorkingServerId"; //$NON-NLS-1$ + static final String SESSION_ID = "SessionId"; //$NON-NLS-1$ + static final String CONNECTION_ID = "ConnectionId"; //$NON-NLS-1$ + + ClusterProvider clusterProvider; + + // @Slf4j + /** Area for viewing servers. */ + public ViewerArea( + Composite parent, int style, Menu menu, ToolBar toolBar, ClusterProvider clusterProvider) { + super(parent, style); + + this.clusterProvider = clusterProvider; + this.clusterProvider.readConfig(); + + SashForm sashForm = new SashForm(this, SWT.NONE); + + initIcon(); + + // toolBar = new ToolBar(this, SWT.FLAT | SWT.RIGHT); // Для отладки + // toolBar.setBounds(0, 0, 500, 23); // Для отладки + + // initToolbar(parent, toolBar); + initMainMenu(sashForm, menu); + + initServersTree(sashForm); + + TabFolder tabFolder = new TabFolder(sashForm, SWT.NONE); + + tabFolder.addSelectionListener( + new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent evt) { + currentTabitem = tabFolder.getSelection()[0]; + clickItemInServerTree(1); + } + }); + + initSessionTable(tabFolder); + initConnectionsTable(tabFolder); + initLocksTable(tabFolder); + initWorkingProcessesTable(tabFolder); + initWorkingServersTable(tabFolder); + + this.setLayout(new FillLayout(SWT.HORIZONTAL)); + + // Заполнение списка серверов + clusterProvider + .getServers() + .forEach( + (serverKey, server) -> { + addServerItemInServersTree(server); + }); + + // Пропорции областей + sashForm.setWeights(3, 10); + + connectToAllServers(false); + } + + @Override + public void addPaintListener(PaintListener listener) { // не работает + connectToAllServers(false); + + super.addPaintListener(listener); + } + + // public void open() { + // connectToAllServers(); + // } + + private void initIcon() { + LOGGER.info("Start init icon"); //$NON-NLS-1$ + + serverIcon = getImage("server_24.png"); //$NON-NLS-1$ + serverIconUp = getImage("server_up_24.png"); //$NON-NLS-1$ + serverIconDown = getImage("server_down_24.png"); //$NON-NLS-1$ + serverIconConnecting = getImage("server_connecting_24.png"); //$NON-NLS-1$ + workingServerIcon = getImage("working_server_24.png"); //$NON-NLS-1$ + infobaseIcon = getImage("infobase_24.png"); //$NON-NLS-1$ + infobasesIcon = getImage("infobases_24.png"); //$NON-NLS-1$ + clusterIcon = getImage("cluster_24.png"); //$NON-NLS-1$ + + userIcon = getImage("user.png"); //$NON-NLS-1$ + sleepUserIcon = getImage("sleepUser.png"); //$NON-NLS-1$ + serviceIcon = getImage("service.png"); //$NON-NLS-1$ + + connectionIcon = getImage("connection.png"); //$NON-NLS-1$ + locksIcon = getImage("lock_16.png"); //$NON-NLS-1$ + + workingProcessesIcon = getImage("wps.png"); //$NON-NLS-1$ + workingProcessIcon = getImage("wp.png"); //$NON-NLS-1$ + + connectActionIcon = getImage("connect_action_24.png"); //$NON-NLS-1$ + disconnectActionIcon = getImage("disconnect_action_24.png"); //$NON-NLS-1$ + + editIcon = getImage("edit_16.png"); //$NON-NLS-1$ + addIcon = getImage("add_16.png"); //$NON-NLS-1$ + deleteIcon = getImage("delete_16.png"); //$NON-NLS-1$ + lockUsersIcon = getImage("lock_users_16.png"); //$NON-NLS-1$ + updateIcon = getImage("update.png"); //$NON-NLS-1$ + + LOGGER.info("Icon init succesfully"); //$NON-NLS-1$ + } + + private void initToolbar(Composite parent, ToolBar toolBar) { + // ToolBar toolBar = applicationWindow.getToolBarManager().createControl(parent); + + // final Cursor handCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_HAND); + // toolBar.setCursor(handCursor); + // // Cursor needs to be explicitly disposed + // toolBar.addDisposeListener(new DisposeListener() { + // public void widgetDisposed(DisposeEvent e) { + // if (handCursor.isDisposed() == false) { + // handCursor.dispose(); + // } + // } + // }); + + ToolItem toolBarItemFindNewServers = new ToolItem(toolBar, SWT.NONE); + toolBarItemFindNewServers.setText( + Messages.getString("ViewerArea.FindNewServers")); //$NON-NLS-1$ + toolBarItemFindNewServers.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List newServers = clusterProvider.findNewServers(); + if (!newServers.isEmpty()) { + fillServersList(); + } + } + }); + + ToolItem toolBarItemConnectAllServers = new ToolItem(toolBar, SWT.NONE); + toolBarItemConnectAllServers.setText( + Messages.getString("ViewerArea.ConnectToAllServers")); //$NON-NLS-1$ + toolBarItemConnectAllServers.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + connectToAllServers(false); + } + }); + } + + private void initMainMenu(Composite parent, Menu mainMenu) { + + if (mainMenu == null) { + return; + } + Menu mainMenuServersParent = new Menu(mainMenu); + MenuItem mainMenuServers = new MenuItem(mainMenu, SWT.CASCADE); + mainMenuServers.setText(Messages.getString("ViewerArea.Servers")); //$NON-NLS-1$ + mainMenuServers.setMenu(mainMenuServersParent); + + MenuItem toolBarItemFindNewServers = new MenuItem(mainMenuServersParent, SWT.NONE); + toolBarItemFindNewServers.setText( + Messages.getString("ViewerArea.FindNewServers")); //$NON-NLS-1$ + toolBarItemFindNewServers.setEnabled(false); + toolBarItemFindNewServers.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List newServers = clusterProvider.findNewServers(); + if (!newServers.isEmpty()) { + fillServersList(); + } + } + }); + + MenuItem toolBarItemConnectAllServers = new MenuItem(mainMenuServersParent, SWT.NONE); + toolBarItemConnectAllServers.setText( + Messages.getString("ViewerArea.ConnectToAllServers")); //$NON-NLS-1$ + toolBarItemConnectAllServers.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + connectToAllServers(true); + } + }); + + MenuItem toolBarItemDisonnectAllServers = new MenuItem(mainMenuServersParent, SWT.NONE); + toolBarItemDisonnectAllServers.setText( + Messages.getString("ViewerArea.DisonnectFromAllServers")); //$NON-NLS-1$ + toolBarItemDisonnectAllServers.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + diconnectFromAllServers(); + } + }); + + Menu mainMenuServiceParent = new Menu(mainMenu); + MenuItem mainMenuService = new MenuItem(mainMenu, SWT.CASCADE); + mainMenuService.setText(Messages.getString("ViewerArea.Service")); //$NON-NLS-1$ + mainMenuService.setMenu(mainMenuServiceParent); + + MenuItem toolBarItemOpenSettings = new MenuItem(mainMenuServiceParent, SWT.NONE); + toolBarItemOpenSettings.setText(Messages.getString("ViewerArea.OpenSettings")); //$NON-NLS-1$ + toolBarItemOpenSettings.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + SettingsDialog settingsDialog; + try { + settingsDialog = new SettingsDialog(getParent().getDisplay().getActiveShell()); + } catch (Exception excp) { + LOGGER.error("Error init SettingsDialog", excp); //$NON-NLS-1$ + return; + } + int dialogResult = settingsDialog.open(); + if (dialogResult == 0) { + clusterProvider.saveConfig(); + for (TreeItem item : serversTree.getItems()) { + updateClustersInTree(item); + } + } + } + }); + + MenuItem toolBarItemOpenAbout = new MenuItem(mainMenuServiceParent, SWT.NONE); + toolBarItemOpenAbout.setText(Messages.getString("ViewerArea.About")); //$NON-NLS-1$ + toolBarItemOpenAbout.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + AboutDialog aboutDialog; + try { + aboutDialog = new AboutDialog(getParent().getDisplay().getActiveShell()); + } catch (Exception excp) { + LOGGER.error("Error init AboutDialog", excp); //$NON-NLS-1$ + return; + } + aboutDialog.open(); + } + }); + } + + private void initServersTree(SashForm sashForm) { + + serversTree = new Tree(sashForm, SWT.BORDER | SWT.FULL_SELECTION); + serversTree.setHeaderVisible(true); + serversTree.setSortDirection(SWT.UP); + + serversTree.addMouseListener( + new MouseAdapter() { + @Override + public void mouseDown(MouseEvent e) { + clickItemInServerTree(e.button); + } + }); + + initServersTreeContextMenu(); + + columnServer = new TreeColumn(serversTree, SWT.LEFT); + columnServer.setText(Messages.getString("ViewerArea.Server")); //$NON-NLS-1$ + columnServer.setWidth(350); + + ///////////////////////// + // сортировка не работает + // columnServer.addListener(SWT.Selection, sortListener); + // columnServer.addSelectionListener( + // new SelectionAdapter() { + // @Override + // public void widgetSelected(SelectionEvent e) { + // serversTree.setSortDirection( + // serversTree.getSortDirection() == SWT.UP ? SWT.DOWN : SWT.UP); + // serversTree.setSortColumn(columnServer); + // } + // }); + // + // Listener sortListener = + // new Listener() { + // public void handleEvent(Event e) { + // TreeItem[] items = serversTree.getItems(); + // Collator collator = Collator.getInstance(Locale.getDefault()); + // TreeColumn column = (TreeColumn) e.widget; + // int index = column == columnServer ? 0 : 1; + // for (int i = 1; i < items.length; i++) { + // String value1 = items[i].getText(index); + // for (int j = 0; j < i; j++) { + // String value2 = items[j].getText(index); + // if (collator.compare(value1, value2) < 0) { + // String[] values = {items[i].getText(0), items[i].getText(1)}; + // items[i].dispose(); + // TreeItem item = new TreeItem(serversTree, SWT.NONE, j); + // item.setText(values); + // items = serversTree.getItems(); + // break; + // } + // } + // } + // serversTree.setSortColumn(column); + // } + // }; + // сортировка не работает + ///////////////////////// + + } + + private void initServersTreeContextMenu() { + + // Server Menu + serverMenu = new Menu(serversTree); + + // установка активности элементов контекстного меню + serverMenu.addListener( + SWT.Show, + new Listener() { + @Override + public void handleEvent(Event event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + TreeItem serverItem = item[0]; + Server server = getCurrentServerConfig(serverItem); + boolean serverIsConnected = server.isConnected(); + boolean serverIsErrorConnected = !server.getConnectionError().isBlank(); + + MenuItem[] menuItems = serverMenu.getItems(); + + for (MenuItem menuItem : menuItems) { + if (menuItem == menuItemConnectServer) { //TODO menuItem.equals(menuItemConnectServer) + menuItem.setEnabled(!serverIsConnected); + } + if (menuItem == menuItemDisconnectServer) { + menuItem.setEnabled(serverIsConnected); + } + if (menuItem == menuItemShowConnectionError) { + menuItem.setEnabled(serverIsErrorConnected); + } + } + } + }); + + initServerMenu(); + initClusterMenu(); + initWorkingServerMenu(); + initInfobaseNodeMenu(); + initInfobaseMenu(); + + // set active menu + serversTree.setMenu(serverMenu); + } + + private void initServerMenu() { + + menuItemConnectServer = new MenuItem(serverMenu, SWT.NONE); + menuItemConnectServer.setText(Messages.getString("ViewerArea.ConnectToServer")); //$NON-NLS-1$ + menuItemConnectServer.setImage(connectActionIcon); + menuItemConnectServer.setEnabled(false); + menuItemConnectServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + connectServerItem(item[0], false); + } + }); + + menuItemDisconnectServer = new MenuItem(serverMenu, SWT.NONE); + menuItemDisconnectServer.setText( + Messages.getString("ViewerArea.DisconnectOfServer")); //$NON-NLS-1$ + menuItemDisconnectServer.setImage(disconnectActionIcon); + menuItemDisconnectServer.setEnabled(false); + menuItemDisconnectServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + disconnectServerItem(item[0]); + } + }); + + menuItemShowConnectionError = new MenuItem(serverMenu, SWT.NONE); + menuItemShowConnectionError.setText( + Messages.getString("ViewerArea.ShowConnectionError")); //$NON-NLS-1$ + menuItemShowConnectionError.setEnabled(false); + menuItemShowConnectionError.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(getCurrentServerConfig(item[0]).getConnectionError()); + messageBox.open(); + } + }); + + addMenuSeparator(serverMenu); + + MenuItem menuItemAddNewServer = new MenuItem(serverMenu, SWT.NONE); + menuItemAddNewServer.setText(Messages.getString("ViewerArea.AddServer")); //$NON-NLS-1$ + menuItemAddNewServer.setImage(addIcon); + menuItemAddNewServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + Server newServer = clusterProvider.createNewServer(); + CreateEditServerDialog connectionDialog; + try { + connectionDialog = + new CreateEditServerDialog(getParent().getDisplay().getActiveShell(), newServer); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error("Error init CreateEditServerDialog for new server", excp); //$NON-NLS-1$ + return; + } + + int dialogResult = connectionDialog.open(); + if (dialogResult != 0) { + return; + } + + clusterProvider.addNewServer(newServer); + TreeItem newServerItem = addServerItemInServersTree(newServer); + updateClustersInTree(newServerItem); + } + }); + + MenuItem menuItemEditServer = new MenuItem(serverMenu, SWT.NONE); + menuItemEditServer.setText(Messages.getString("ViewerArea.EditServer")); //$NON-NLS-1$ + menuItemEditServer.setImage(editIcon); + menuItemEditServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + TreeItem serverItem = item[0]; + Server server = getCurrentServerConfig(serverItem); + CreateEditServerDialog connectionDialog; + try { + connectionDialog = + new CreateEditServerDialog(getParent().getDisplay().getActiveShell(), server); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error( + "Error init CreateEditServerDialog for server {}", //$NON-NLS-1$ + server.getTreeDescription(), + excp); + return; + } + + int dialogResult = connectionDialog.open(); + if (dialogResult == 0) { + // перерисовать в дереве + serverItem.setText(new String[] {server.getTreeDescription()}); + clusterProvider.saveConfig(); + updateClustersInTree(serverItem); + } + } + }); + + MenuItem menuItemUpdateServer = new MenuItem(serverMenu, SWT.NONE); + menuItemUpdateServer.setText(Messages.getString("ViewerArea.Update")); //$NON-NLS-1$ + menuItemUpdateServer.setImage(updateIcon); + menuItemUpdateServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + updateClustersInTree(item[0]); + } + }); + + addMenuSeparator(serverMenu); + + MenuItem menuItemDeleteServer = new MenuItem(serverMenu, SWT.NONE); + menuItemDeleteServer.setText(Messages.getString("ViewerArea.RemoveServer")); //$NON-NLS-1$ + menuItemDeleteServer.setImage(deleteIcon); + menuItemDeleteServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + TreeItem serverItem = item[0]; + Server server = getCurrentServerConfig(serverItem); + clusterProvider.removeServer(server); + disposeTreeItemWithChildren(serverItem); + } + }); + } + + private void initClusterMenu() { + // Cluster Menu + clusterMenu = new Menu(serversTree); + + MenuItem menuItemCreateCluster = new MenuItem(clusterMenu, SWT.NONE); + menuItemCreateCluster.setText(Messages.getString("ViewerArea.CreateCluster")); //$NON-NLS-1$ + menuItemCreateCluster.setImage(addIcon); + menuItemCreateCluster.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + + CreateEditClusterDialog editClusterDialog; + try { + editClusterDialog = + new CreateEditClusterDialog( + getParent().getDisplay().getActiveShell(), server, null); + } catch (Exception excp) { + LOGGER.error( + "Error init CreateEditClusterDialog for new cluster", //$NON-NLS-1$ + excp); + return; + } + + int dialogResult = editClusterDialog.open(); + if (dialogResult == 0) { + updateClustersInTree(item[0].getParentItem()); + } + } + }); + + MenuItem menuItemEditCluster = new MenuItem(clusterMenu, SWT.NONE); + menuItemEditCluster.setText(Messages.getString("ViewerArea.EditCluster")); //$NON-NLS-1$ + menuItemEditCluster.setImage(editIcon); + menuItemEditCluster.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + + CreateEditClusterDialog editClusterDialog; + try { + editClusterDialog = + new CreateEditClusterDialog( + getParent().getDisplay().getActiveShell(), server, clusterId); + } catch (Exception excp) { + LOGGER.error( + "Error init CreateEditClusterDialog for cluster id {}", //$NON-NLS-1$ + clusterId, + excp); + return; + } + + int dialogResult = editClusterDialog.open(); + if (dialogResult == 0) { + updateClustersInTree(item[0]); + } + } + }); + + MenuItem menuItemUpdateCluster = new MenuItem(clusterMenu, SWT.NONE); + menuItemUpdateCluster.setText(Messages.getString("ViewerArea.Update")); //$NON-NLS-1$ + menuItemUpdateCluster.setImage(updateIcon); + menuItemUpdateCluster.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + fillChildrenItemsOfCluster(item[0], server); + } + }); + + addMenuSeparator(clusterMenu); + + MenuItem menuItemDeleteCluster = new MenuItem(clusterMenu, SWT.NONE); + menuItemDeleteCluster.setText(Messages.getString("ViewerArea.DeleteCluster")); //$NON-NLS-1$ + menuItemDeleteCluster.setImage(deleteIcon); + menuItemDeleteCluster.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + + var messageBox = + new MessageBox( + Display.getDefault().getActiveShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); + messageBox.setMessage( + Messages.getString("ViewerArea.DeleteClusterQuestion")); //$NON-NLS-1$ + int rc = messageBox.open(); + + if (rc == SWT.YES && server.unregCluster(clusterId)) { + item[0].dispose(); + } + } + }); + } + + private void initWorkingServerMenu() { + + workingServerMenu = new Menu(serversTree); + + MenuItem menuItemCreateWorkingServer = new MenuItem(workingServerMenu, SWT.NONE); + menuItemCreateWorkingServer.setText( + Messages.getString("ViewerArea.CreateWorkingServer")); //$NON-NLS-1$ + menuItemCreateWorkingServer.setImage(addIcon); + menuItemCreateWorkingServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + + CreateEditWorkingServerDialog editWorkingServerDialog; + try { + editWorkingServerDialog = + new CreateEditWorkingServerDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, null); + } catch (Exception excp) { + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + clusterId, + excp); + return; + } + + int dialogResult = editWorkingServerDialog.open(); + if (dialogResult == 0) { + var newWorkingServerUuid = editWorkingServerDialog.getNewWorkingServerId(); + if (newWorkingServerUuid != null) { + IWorkingServerInfo workingServerInfo = + server.getWorkingServerInfo(clusterId, newWorkingServerUuid); + addWorkingServerItemInNode(item[0].getParentItem(), workingServerInfo); + } + } + } + }); + + MenuItem menuItemEditWorkingServer = new MenuItem(workingServerMenu, SWT.NONE); + menuItemEditWorkingServer.setText( + Messages.getString("ViewerArea.EditWorkingServer")); //$NON-NLS-1$ + menuItemEditWorkingServer.setImage(editIcon); + menuItemEditWorkingServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID workingServerId = getCurrentWorkingServerId(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + + CreateEditWorkingServerDialog editClusterDialog; + try { + editClusterDialog = + new CreateEditWorkingServerDialog( + getParent().getDisplay().getActiveShell(), + server, + clusterId, + workingServerId); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + workingServerId, + excp); + return; + } + + editClusterDialog.open(); + } + }); + } + + private void initInfobaseNodeMenu() { + + infobaseNodeMenu = new Menu(serversTree); + + MenuItem menuItemNewInfobase = new MenuItem(infobaseNodeMenu, SWT.NONE); + menuItemNewInfobase.setText(Messages.getString("ViewerArea.CreateInfobase")); //$NON-NLS-1$ + menuItemNewInfobase.setImage(addIcon); + menuItemNewInfobase.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + + CreateInfobaseDialog infobaseDialog; + try { + infobaseDialog = + new CreateInfobaseDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, null); + } catch (Exception excp) { + LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ + return; + } + + int dialogResult = infobaseDialog.open(); + if (dialogResult == 0) { + var newInfobaseUuid = infobaseDialog.getNewInfobaseUuid(); + if (newInfobaseUuid != null) { + IInfoBaseInfoShort infoBaseInfo = + server.getInfoBaseShortInfo(clusterId, newInfobaseUuid); + addInfobaseItemInInfobaseNode(item[0], infoBaseInfo); + } + } + } + }); + + MenuItem menuItemUpdateInfobases = new MenuItem(infobaseNodeMenu, SWT.NONE); + menuItemUpdateInfobases.setText( + Messages.getString("ViewerArea.UpdateInfobases")); //$NON-NLS-1$ + menuItemUpdateInfobases.setImage(updateIcon); + menuItemUpdateInfobases.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + fillInfobasesOfCluster(item[0].getParentItem(), server); + } + }); + } + + private void initInfobaseMenu() { + + infobaseMenu = new Menu(serversTree); + + MenuItem menuItemCopyInfobase = new MenuItem(infobaseMenu, SWT.NONE); + menuItemCopyInfobase.setText( + Messages.getString("ViewerArea.CreateNewInfobaseUsingThis")); //$NON-NLS-1$ + menuItemCopyInfobase.setImage(addIcon); + menuItemCopyInfobase.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + UUID sampleInfobaseId = getCurrentInfobaseId(item[0]); + + CreateInfobaseDialog infobaseDialog; + try { + infobaseDialog = + new CreateInfobaseDialog( + getParent().getDisplay().getActiveShell(), + server, + clusterId, + sampleInfobaseId); + } catch (Exception excp) { + LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ + return; + } + + int dialogResult = infobaseDialog.open(); + if (dialogResult == 0) { + var newInfobaseUuid = infobaseDialog.getNewInfobaseUuid(); + if (newInfobaseUuid != null) { + IInfoBaseInfoShort infoBaseInfo = + server.getInfoBaseShortInfo(clusterId, newInfobaseUuid); + addInfobaseItemInInfobaseNode(item[0].getParentItem(), infoBaseInfo); + } + } + } + }); + + MenuItem menuItemEditInfobase = new MenuItem(infobaseMenu, SWT.NONE); + menuItemEditInfobase.setText(Messages.getString("ViewerArea.EditInfobase")); //$NON-NLS-1$ + menuItemEditInfobase.setImage(editIcon); + menuItemEditInfobase.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + UUID infobaseId = getCurrentInfobaseId(item[0]); + + EditInfobaseDialog infobaseDialog; + try { + infobaseDialog = + new EditInfobaseDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); + } catch (Exception excp) { + excp.printStackTrace(); + return; + } + + int dialogResult = infobaseDialog.open(); + if (dialogResult == 0) { + // TODO обновить в дереве description инфобазы + // server.clusterConnector.updateInfoBase(server.clusterID, infoBaseInfo); + } + } + }); + + MenuItem menuItemDeleteInfobase = new MenuItem(infobaseMenu, SWT.NONE); + menuItemDeleteInfobase.setText(Messages.getString("ViewerArea.DeleteInfobase")); //$NON-NLS-1$ + menuItemDeleteInfobase.setImage(deleteIcon); + menuItemDeleteInfobase.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + UUID infobaseId = getCurrentInfobaseId(item[0]); + + DropInfobaseDialog infobaseDialog; + try { + infobaseDialog = + new DropInfobaseDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); + } catch (Exception excp) { + excp.printStackTrace(); + return; + } + + int dialogResult = infobaseDialog.open(); + if (dialogResult == 0) { + item[0].dispose(); + } + } + }); + + // Создание вложенных подпунктов меню + Menu infobaseSubMenuSessionManage = new Menu(infobaseMenu); + + MenuItem infobaseMenuSessionManage = new MenuItem(infobaseMenu, SWT.CASCADE); + infobaseMenuSessionManage.setText( + Messages.getString("ViewerArea.SessionManage")); //$NON-NLS-1$ + infobaseMenuSessionManage.setMenu(infobaseSubMenuSessionManage); + // infobaseSubMenuSessionManage.setImage(terminateSessionIcon); + + MenuItem menuItemLockUserSessionsNow = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); + menuItemLockUserSessionsNow.setText( + Messages.getString("ViewerArea.LockSessionsNow")); //$NON-NLS-1$ + menuItemLockUserSessionsNow.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + TreeItem selectItem = item[0]; + + Server server = getCurrentServerConfig(selectItem); + UUID clusterId = getCurrentClusterId(selectItem); + UUID infobaseId = getCurrentInfobaseId(selectItem); + + IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infobaseId); + if (infoBaseInfo == null) { + return; + } + + infoBaseInfo.setScheduledJobsDenied(true); + infoBaseInfo.setSessionsDenied(true); + infoBaseInfo.setDeniedFrom(null); + infoBaseInfo.setDeniedTo(null); + infoBaseInfo.setDeniedMessage(""); //$NON-NLS-1$ + infoBaseInfo.setDeniedParameter(""); //$NON-NLS-1$ + infoBaseInfo.setPermissionCode(""); //$NON-NLS-1$ + + server.updateInfoBase(clusterId, infoBaseInfo); + } + }); + + MenuItem menuItemTerminateAllSessions = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); + menuItemTerminateAllSessions.setText( + Messages.getString("ViewerArea.TerminateAllSessions")); //$NON-NLS-1$ + menuItemTerminateAllSessions.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + UUID infobaseId = getCurrentInfobaseId(item[0]); + + server.terminateAllSessionsOfInfobase(clusterId, infobaseId, false); + } + }); + + MenuItem menuItemTerminateUserSessions = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); + menuItemTerminateUserSessions.setText( + Messages.getString("ViewerArea.TerminateUsersSessions")); //$NON-NLS-1$ + menuItemTerminateUserSessions.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getCurrentServerConfig(item[0]); + UUID clusterId = getCurrentClusterId(item[0]); + UUID infobaseId = getCurrentInfobaseId(item[0]); + + server.terminateAllSessionsOfInfobase(clusterId, infobaseId, true); + } + }); + } + + private void initSessionTable(TabFolder tabFolder) { + + tabSessions = new TabItem(tabFolder, SWT.NONE); + tabSessions.setText(Messages.getString("ViewerArea.Sessions")); //$NON-NLS-1$ + + tableSessions = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK); + tabSessions.setControl(tableSessions); + tableSessions.setHeaderVisible(true); + tableSessions.setLinesVisible(true); + + initSessionsTableContextMenu(); + + SessionInfoExtended.initColumnsName(sessionColumnsMap); + + ColumnProperties columnProperties = + ClusterProvider.getCommonConfig().getSessionColumnProperties(); + + String[] columnNameList = sessionColumnsMap.keySet().toArray(new String[0]); + for (String columnName : columnNameList) { + addTableColumn( + tableSessions, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + } + + int[] columnOrder = columnProperties.getOrder(); + if (columnOrder != null && tableSessions.getColumnCount() == columnOrder.length) { + tableSessions.setColumnOrder(columnOrder); + } + } + + private void initSessionsTableContextMenu() { + + Menu tableSessionsMenu = new Menu(tableSessions); + tableSessions.setMenu(tableSessionsMenu); + tableSessions.addKeyListener(keyListener); + + tableSessions.addListener( + SWT.Selection, + new Listener() { + @Override + public void handleEvent(Event event) { + if (event.detail == SWT.CHECK) { + TableItem item = (TableItem) event.item; + String id = item.getText(1).concat("*").concat(item.getText(2)); //$NON-NLS-1$ + if (item.getChecked()) { + watchedSessions.add(id); + item.setForeground(watchedSessionColor); + } else { + watchedSessions.remove(id); + item.setForeground(standardColor); + } + } + } + }); + + // Выделение одной ячейки, для копирования значения из нее через CTRL+C + // Из-за добавления этого Listener-а пропадает прямоугольник выделения строк (передвигая мышь с + // зажатой ЛКМ) + // tableSessions.addListener( + // SWT.MouseDown, + // new Listener() { + // @Override + // public void handleEvent(Event event) { + // Table currentTable = (Table) event.widget; + // + // Point pt = new Point(event.x, event.y); + // TableItem item = currentTable.getItem(pt); + // if (item != null) { + // for (int col = 0; col < currentTable.getColumnCount(); col++) { + // Rectangle rect = item.getBounds(col); + // if (rect.contains(pt)) { + // + // if (Objects.nonNull(lastSelectItem) && !lastSelectItem.isDisposed()) { + // lastSelectItem.setForeground(lastSelectColumn, new Color(0, 0, 0)); + // } + // + // // System.out.println("item clicked."); + // // System.out.println("column is " + col); + // System.out.println(item.getText(col)); + // + // // Color blue = display.getSystemColor(SWT.COLOR_BLUE); + // item.setForeground(col, new Color(0, 100, 128)); + // // item.setFont(col, fontBold); + // + // lastSelectItem = item; + // lastSelectColumn = col; + // break; + // } + // } + // } + // } + // }); + + MenuItem menuItemUpdateList = new MenuItem(tableSessionsMenu, SWT.NONE); + menuItemUpdateList.setText( + Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? + menuItemUpdateList.setImage(updateIcon); + menuItemUpdateList.addSelectionListener(updateItemListener); + + MenuItem menuItemViewSession = new MenuItem(tableSessionsMenu, SWT.NONE); + menuItemViewSession.setText( + Messages.getString("ViewerArea.ViewSession").concat("\tF2")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemViewSession.setAccelerator(SWT.F2); + menuItemViewSession.setImage(editIcon); + menuItemViewSession.addSelectionListener(editItemListener); + + MenuItem menuItemKillSession = new MenuItem(tableSessionsMenu, SWT.NONE); + menuItemKillSession.setText( + Messages.getString("ViewerArea.KillSession").concat("\tDEL")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemKillSession.setAccelerator(SWT.DEL); + menuItemKillSession.setImage(deleteIcon); + menuItemKillSession.addSelectionListener(deleteItemListener); + } + + private void deleteSelectSession() { + + Table currentTable = null; + + if (currentTabitem.equals(tabSessions)) { + currentTable = tableSessions; + } else if (currentTabitem.equals(tabConnections)) { + currentTable = tableConnections; + } else if (currentTabitem.equals(tabWorkingServers)) { + currentTable = tableWorkingServers; + } + + if (currentTable == null) { + return; + } + + TableItem[] selectedItems = currentTable.getSelection(); + if (selectedItems.length == 0) { + return; + } + + for (TableItem item : selectedItems) { + item.setForeground(deletedItemColor); + + if (currentTable.equals(tableSessions)) { + Server server = (Server) item.getData(SERVER_INFO); + UUID clusterId = (UUID) item.getData(CLUSTER_ID); + UUID sessionId = (UUID) item.getData(SESSION_ID); + + if (server.terminateSession(clusterId, sessionId)) { + item.dispose(); // update tableSessions + } + + } else if (currentTable.equals(tableConnections)) { + Server server = (Server) item.getData(SERVER_INFO); + UUID clusterId = (UUID) item.getData(CLUSTER_ID); + UUID pricessId = (UUID) item.getData(WORKINGPROCESS_ID); + UUID connectionId = (UUID) item.getData(CONNECTION_ID); + UUID infobaseId = (UUID) item.getData(INFOBASE_ID); + + if (server.disconnectConnection(clusterId, pricessId, connectionId, infobaseId)) { + item.dispose(); // update tableConnections + } + + } else if (currentTable.equals(tableWorkingServers)) { + Server server = (Server) item.getData(SERVER_INFO); + UUID clusterId = (UUID) item.getData(CLUSTER_ID); + UUID workingServerId = (UUID) item.getData(WORKINGSERVER_ID); + + if (server.unregWorkingServer(clusterId, workingServerId)) { + item.dispose(); // update tableWorkingServers + } + } else { + break; + } + } + } + + private void initConnectionsTable(TabFolder tabFolder) { + + tabConnections = new TabItem(tabFolder, SWT.NONE); + tabConnections.setText(Messages.getString("ViewerArea.Connections")); //$NON-NLS-1$ + + tableConnections = + new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK + tabConnections.setControl(tableConnections); + tableConnections.setHeaderVisible(true); + tableConnections.setLinesVisible(true); + + initConnectionsTableContextMenu(); + + ConnectionInfoExtended.initColumnsName(connectionColumnsMap); + + ColumnProperties columnProperties = + ClusterProvider.getCommonConfig().getConnectionColumnProperties(); + + String[] columnNameList = connectionColumnsMap.keySet().toArray(new String[0]); + for (String columnName : columnNameList) { + addTableColumn( + tableConnections, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + } + + int[] columnOrder = columnProperties.getOrder(); + if (columnOrder != null && tableConnections.getColumnCount() == columnOrder.length) { + tableConnections.setColumnOrder(columnOrder); + } + } + + private void initConnectionsTableContextMenu() { + + Menu tableConnectionsMenu = new Menu(tableConnections); + tableConnections.setMenu(tableConnectionsMenu); + tableConnections.addKeyListener(keyListener); + + MenuItem menuItemUpdateList = new MenuItem(tableConnectionsMenu, SWT.NONE); + menuItemUpdateList.setText( + Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? + menuItemUpdateList.setImage(updateIcon); + menuItemUpdateList.addSelectionListener(updateItemListener); + + MenuItem menuItemKillSession = new MenuItem(tableConnectionsMenu, SWT.NONE); + menuItemKillSession.setText( + Messages.getString("ViewerArea.KillConnection").concat("\tDEL")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemKillSession.setAccelerator(SWT.DEL); + menuItemKillSession.setImage(deleteIcon); + menuItemKillSession.addSelectionListener(deleteItemListener); + } + + private void initLocksTable(TabFolder tabFolder) { + + tabLocks = new TabItem(tabFolder, SWT.NONE); + tabLocks.setText(Messages.getString("ViewerArea.Locks")); //$NON-NLS-1$ + + tableLocks = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK + tabLocks.setControl(tableLocks); + tableLocks.setHeaderVisible(true); + tableLocks.setLinesVisible(true); + + initLocksTableContextMenu(); + + LockInfoExtended.initColumnsName(lockColumnsMap); + + ColumnProperties columnProperties = ClusterProvider.getCommonConfig().getLockColumnProperties(); + + String[] columnNameList = lockColumnsMap.keySet().toArray(new String[0]); + for (String columnName : columnNameList) { + addTableColumn( + tableLocks, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + } + + int[] columnOrder = columnProperties.getOrder(); + if (columnOrder != null && tableLocks.getColumnCount() == columnOrder.length) { + tableLocks.setColumnOrder(columnOrder); + } + } + + private void initLocksTableContextMenu() { + + Menu tableLocksMenu = new Menu(tableLocks); + tableLocks.setMenu(tableLocksMenu); + tableLocks.addKeyListener(keyListener); + + MenuItem menuItemUpdateList = new MenuItem(tableLocksMenu, SWT.NONE); + menuItemUpdateList.setText( + Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? + menuItemUpdateList.setImage(updateIcon); + menuItemUpdateList.addSelectionListener(updateItemListener); + } + + private void initWorkingProcessesTable(TabFolder tabFolder) { + + tabWorkingProcesses = new TabItem(tabFolder, SWT.NONE); + tabWorkingProcesses.setText(Messages.getString("ViewerArea.WorkingProcesses")); //$NON-NLS-1$ + + tableWorkingProcesses = + new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK + tabWorkingProcesses.setControl(tableWorkingProcesses); + tableWorkingProcesses.setHeaderVisible(true); + tableWorkingProcesses.setLinesVisible(true); + + initWorkingProcessesTableContextMenu(); + + WorkingProcessInfoExtended.initColumnsName(wpColumnsMap); + + ColumnProperties columnProperties = ClusterProvider.getCommonConfig().getWpColumnProperties(); + + String[] columnNameList = wpColumnsMap.keySet().toArray(new String[0]); + for (String columnName : columnNameList) { + addTableColumn( + tableWorkingProcesses, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + } + + int[] columnOrder = columnProperties.getOrder(); + if (columnOrder != null && tableWorkingProcesses.getColumnCount() == columnOrder.length) { + tableWorkingProcesses.setColumnOrder(columnOrder); + } + } + + private void initWorkingProcessesTableContextMenu() { + + Menu tableWorkingProcessesMenu = new Menu(tableWorkingProcesses); + tableWorkingProcesses.setMenu(tableWorkingProcessesMenu); + tableWorkingProcesses.addKeyListener(keyListener); + + MenuItem menuItemUpdateList = new MenuItem(tableWorkingProcessesMenu, SWT.NONE); + menuItemUpdateList.setText( + Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? + menuItemUpdateList.setImage(updateIcon); + menuItemUpdateList.addSelectionListener(updateItemListener); + } + + private void initWorkingServersTable(TabFolder tabFolder) { + + tabWorkingServers = new TabItem(tabFolder, SWT.NONE); + tabWorkingServers.setText(Messages.getString("ViewerArea.WorkingServers")); //$NON-NLS-1$ + + tableWorkingServers = + new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK + tabWorkingServers.setControl(tableWorkingServers); + tableWorkingServers.setHeaderVisible(true); + tableWorkingServers.setLinesVisible(true); + + initWorkingServersTableContextMenu(); + + WorkingServerInfoExtended.initColumnsName(wsColumnsMap); + + ColumnProperties columnProperties = ClusterProvider.getCommonConfig().getWsColumnProperties(); + + String[] columnNameList = wsColumnsMap.keySet().toArray(new String[0]); + for (String columnName : columnNameList) { + addTableColumn( + tableWorkingServers, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + } + + int[] columnOrder = columnProperties.getOrder(); + if (columnOrder != null && tableWorkingServers.getColumnCount() == columnOrder.length) { + tableWorkingServers.setColumnOrder(columnOrder); + } + } + + private void initWorkingServersTableContextMenu() { + + Menu workingServersMenu = new Menu(tableWorkingServers); + tableWorkingServers.setMenu(workingServersMenu); + tableWorkingServers.addKeyListener(keyListener); + + MenuItem menuItemUpdateList = new MenuItem(workingServersMenu, SWT.NONE); + menuItemUpdateList.setText( + Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? + menuItemUpdateList.setImage(updateIcon); + menuItemUpdateList.addSelectionListener(updateItemListener); + + MenuItem menuItemCreateWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); + menuItemCreateWorkingServer.setText( + Messages.getString("ViewerArea.CreateWorkingServer")); //$NON-NLS-1$ + menuItemCreateWorkingServer.setImage(addIcon); + menuItemCreateWorkingServer.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TableItem[] item = tableWorkingServers.getSelection(); + if (item.length == 0) { + return; + } + + Server server = (Server) item[0].getData(SERVER_INFO); + UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); + + CreateEditWorkingServerDialog editWorkingServerDialog; + try { + editWorkingServerDialog = + new CreateEditWorkingServerDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, null); + } catch (Exception excp) { + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + clusterId, + excp); + return; + } + + int dialogResult = editWorkingServerDialog.open(); + if (dialogResult == 0) { + var newWorkingServerUuid = editWorkingServerDialog.getNewWorkingServerId(); + if (newWorkingServerUuid != null) { + IWorkingServerInfo workingServerInfo = + server.getWorkingServerInfo(clusterId, newWorkingServerUuid); + addWorkingServerInTable(server, clusterId, workingServerInfo); + } } + } }); - - initSessionTable(tabFolder); - initConnectionsTable(tabFolder); - initLocksTable(tabFolder); - initWorkingProcessesTable(tabFolder); - initWorkingServersTable(tabFolder); - - this.setLayout(new FillLayout(SWT.HORIZONTAL)); - - // Заполнение списка серверов - clusterProvider.getServers().forEach((serverKey, server) -> { - addServerItemInServersTree(server); - }); - - // Пропорции областей - sashForm.setWeights(3, 10); - - connectToAllServers(false); - - } - - @Override - public void addPaintListener(PaintListener listener) { // не работает - connectToAllServers(false); - - super.addPaintListener(listener); - } - -// public void open() { -// connectToAllServers(); -// } - - private void initIcon() { - LOGGER.info("Start init icon"); //$NON-NLS-1$ - - serverIcon = getImage("server_24.png"); //$NON-NLS-1$ - serverIconUp = getImage("server_up_24.png"); //$NON-NLS-1$ - serverIconDown = getImage("server_down_24.png"); //$NON-NLS-1$ - serverIconConnecting = getImage("server_connecting_24.png"); //$NON-NLS-1$ - workingServerIcon = getImage("working_server_24.png"); //$NON-NLS-1$ - infobaseIcon = getImage("infobase_24.png"); //$NON-NLS-1$ - infobasesIcon = getImage("infobases_24.png"); //$NON-NLS-1$ - clusterIcon = getImage("cluster_24.png"); //$NON-NLS-1$ - - userIcon = getImage("user.png"); //$NON-NLS-1$ - sleepUserIcon = getImage("sleepUser.png"); //$NON-NLS-1$ - serviceIcon = getImage("service.png"); //$NON-NLS-1$ - - connectionIcon = getImage("connection.png"); //$NON-NLS-1$ - locksIcon = getImage("lock_16.png"); //$NON-NLS-1$ - - workingProcessesIcon = getImage("wps.png"); //$NON-NLS-1$ - workingProcessIcon = getImage("wp.png"); //$NON-NLS-1$ - - connectActionIcon = getImage("connect_action_24.png"); //$NON-NLS-1$ - disconnectActionIcon = getImage("disconnect_action_24.png"); //$NON-NLS-1$ - - editIcon = getImage("edit_16.png"); //$NON-NLS-1$ - addIcon = getImage("add_16.png"); //$NON-NLS-1$ - deleteIcon = getImage("delete_16.png"); //$NON-NLS-1$ - lockUsersIcon = getImage("lock_users_16.png"); //$NON-NLS-1$ - updateIcon = getImage("update.png"); //$NON-NLS-1$ - - LOGGER.info("Icon init succesfully"); //$NON-NLS-1$ - } - - private void initToolbar(Composite parent, ToolBar toolBar) { -// ToolBar toolBar = applicationWindow.getToolBarManager().createControl(parent); - -// final Cursor handCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_HAND); -// toolBar.setCursor(handCursor); -// // Cursor needs to be explicitly disposed -// toolBar.addDisposeListener(new DisposeListener() { -// public void widgetDisposed(DisposeEvent e) { -// if (handCursor.isDisposed() == false) { -// handCursor.dispose(); -// } -// } -// }); - - ToolItem toolBarItemFindNewServers = new ToolItem(toolBar, SWT.NONE); - toolBarItemFindNewServers.setText(Messages.getString("ViewerArea.FindNewServers")); //$NON-NLS-1$ - toolBarItemFindNewServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - List newServers = clusterProvider.findNewServers(); - if (!newServers.isEmpty()) { - fillServersList(); - } - } - }); - - ToolItem toolBarItemConnectAllServers = new ToolItem(toolBar, SWT.NONE); - toolBarItemConnectAllServers.setText(Messages.getString("ViewerArea.ConnectToAllServers")); //$NON-NLS-1$ - toolBarItemConnectAllServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - connectToAllServers(false); - } - }); - } - - private void initMainMenu(Composite parent, Menu mainMenu) { - - if (mainMenu == null) { - return; - } - Menu mainMenuServersParent = new Menu(mainMenu); - MenuItem mainMenuServers = new MenuItem(mainMenu, SWT.CASCADE); - mainMenuServers.setText(Messages.getString("ViewerArea.Servers")); //$NON-NLS-1$ - mainMenuServers.setMenu(mainMenuServersParent); - - MenuItem toolBarItemFindNewServers = new MenuItem(mainMenuServersParent, SWT.NONE); - toolBarItemFindNewServers.setText(Messages.getString("ViewerArea.FindNewServers")); //$NON-NLS-1$ - toolBarItemFindNewServers.setEnabled(false); - toolBarItemFindNewServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - List newServers = clusterProvider.findNewServers(); - if (!newServers.isEmpty()) { - fillServersList(); - } - } - }); - - MenuItem toolBarItemConnectAllServers = new MenuItem(mainMenuServersParent, SWT.NONE); - toolBarItemConnectAllServers.setText(Messages.getString("ViewerArea.ConnectToAllServers")); //$NON-NLS-1$ - toolBarItemConnectAllServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - connectToAllServers(true); - } - }); - - MenuItem toolBarItemDisonnectAllServers = new MenuItem(mainMenuServersParent, SWT.NONE); - toolBarItemDisonnectAllServers.setText(Messages.getString("ViewerArea.DisonnectFromAllServers")); //$NON-NLS-1$ - toolBarItemDisonnectAllServers.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - diconnectFromAllServers(); - } - }); - - Menu mainMenuServiceParent = new Menu(mainMenu); - MenuItem mainMenuService = new MenuItem(mainMenu, SWT.CASCADE); - mainMenuService.setText(Messages.getString("ViewerArea.Service")); //$NON-NLS-1$ - mainMenuService.setMenu(mainMenuServiceParent); - - MenuItem toolBarItemOpenSettings = new MenuItem(mainMenuServiceParent, SWT.NONE); - toolBarItemOpenSettings.setText(Messages.getString("ViewerArea.OpenSettings")); //$NON-NLS-1$ - toolBarItemOpenSettings.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - - SettingsDialog settingsDialog; - try { - settingsDialog = new SettingsDialog(getParent().getDisplay().getActiveShell()); - } catch (Exception excp) { - LOGGER.error("Error init SettingsDialog", excp); //$NON-NLS-1$ - return; - } - int dialogResult = settingsDialog.open(); - if (dialogResult == 0) { - clusterProvider.saveConfig(); - for (TreeItem item : serversTree.getItems()) { - updateClustersInTree(item); - } - } - } - }); - - MenuItem toolBarItemOpenAbout = new MenuItem(mainMenuServiceParent, SWT.NONE); - toolBarItemOpenAbout.setText(Messages.getString("ViewerArea.About")); //$NON-NLS-1$ - toolBarItemOpenAbout.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - - AboutDialog aboutDialog; - try { - aboutDialog = new AboutDialog(getParent().getDisplay().getActiveShell()); - } catch (Exception excp) { - LOGGER.error("Error init AboutDialog", excp); //$NON-NLS-1$ - return; - } - int dialogResult = aboutDialog.open(); - if (dialogResult == 0) { - } - } - }); - } - - private void initServersTree(SashForm sashForm) { - - serversTree = new Tree(sashForm, SWT.BORDER | SWT.FULL_SELECTION); - serversTree.setHeaderVisible(true); - serversTree.setSortDirection(SWT.UP); - - serversTree.addMouseListener(new MouseAdapter() { - @Override - public void mouseDown(MouseEvent e) { - clickItemInServerTree(e.button); - } - }); - - initServersTreeContextMenu(); - - columnServer = new TreeColumn(serversTree, SWT.LEFT); - columnServer.setText(Messages.getString("ViewerArea.Server")); //$NON-NLS-1$ - columnServer.setWidth(350); - - ///////////////////////// - // сортировка не работает -// columnServer.addListener(SWT.Selection, sortListener); -// columnServer.addSelectionListener(new SelectionAdapter() { -// @Override -// public void widgetSelected(SelectionEvent e) { -// serversTree.setSortDirection(serversTree.getSortDirection() == SWT.UP ? SWT.DOWN : SWT.UP); -// serversTree.setSortColumn(columnServer); -// } -// }); - -// Listener sortListener = new Listener() { -// public void handleEvent(Event e) { -// TreeItem[] items = serversTree.getItems(); -// Collator collator = Collator.getInstance(Locale.getDefault()); -// TreeColumn column = (TreeColumn) e.widget; -// int index = column == columnServer ? 0 : 1; -// for (int i = 1; i < items.length; i++) { -// String value1 = items[i].getText(index); -// for (int j = 0; j < i; j++) { -// String value2 = items[j].getText(index); -// if (collator.compare(value1, value2) < 0) { -// String[] values = { items[i].getText(0), items[i].getText(1) }; -// items[i].dispose(); -// TreeItem item = new TreeItem(serversTree, SWT.NONE, j); -// item.setText(values); -// items = serversTree.getItems(); -// break; -// } -// } -// } -// serversTree.setSortColumn(column); -// } -// }; - ///////////////////////// - - } - - private void initServersTreeContextMenu() { - - // Server Menu - serverMenu = new Menu(serversTree); - - // установка активности элементов контекстного меню - serverMenu.addListener(SWT.Show, new Listener() { - @Override - public void handleEvent(Event event) { - - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - TreeItem serverItem = item[0]; - Server server = getCurrentServerConfig(serverItem); - boolean serverIsConnected = server.isConnected(); - boolean serverIsErrorConnected = !server.getConnectionError().isBlank(); - - MenuItem[] menuItems = serverMenu.getItems(); - - for (MenuItem menuItem : menuItems) { - if (menuItem == menuItemConnectServer) // menuItem.equals(menuItemConnectServer) - menuItem.setEnabled(!serverIsConnected); - - if (menuItem == menuItemDisconnectServer) - menuItem.setEnabled(serverIsConnected); - - if (menuItem == menuItemShowConnectionError) - menuItem.setEnabled(serverIsErrorConnected); - } - - } - }); - - initServerMenu(); - initClusterMenu(); - initWorkingServerMenu(); - initInfobaseNodeMenu(); - initInfobaseMenu(); - - // set active menu - serversTree.setMenu(serverMenu); - } - - private void initServerMenu() { - - menuItemConnectServer = new MenuItem(serverMenu, SWT.NONE); - menuItemConnectServer.setText(Messages.getString("ViewerArea.ConnectToServer")); //$NON-NLS-1$ - menuItemConnectServer.setImage(connectActionIcon); - menuItemConnectServer.setEnabled(false); - menuItemConnectServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - connectServerItem(item[0], false); - - } - }); - - menuItemDisconnectServer = new MenuItem(serverMenu, SWT.NONE); - menuItemDisconnectServer.setText(Messages.getString("ViewerArea.DisconnectOfServer")); //$NON-NLS-1$ - menuItemDisconnectServer.setImage(disconnectActionIcon); - menuItemDisconnectServer.setEnabled(false); - menuItemDisconnectServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - disconnectServerItem(item[0]); - } - }); - - menuItemShowConnectionError = new MenuItem(serverMenu, SWT.NONE); - menuItemShowConnectionError.setText(Messages.getString("ViewerArea.ShowConnectionError")); //$NON-NLS-1$ - menuItemShowConnectionError.setEnabled(false); - menuItemShowConnectionError.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(getCurrentServerConfig(item[0]).getConnectionError()); - messageBox.open(); - - } - - }); - - addMenuSeparator(serverMenu); - - MenuItem menuItemAddNewServer = new MenuItem(serverMenu, SWT.NONE); - menuItemAddNewServer.setText(Messages.getString("ViewerArea.AddServer")); //$NON-NLS-1$ - menuItemAddNewServer.setImage(addIcon); - menuItemAddNewServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - - Server newServer = clusterProvider.createNewServer(); - CreateEditServerDialog connectionDialog; - try { - connectionDialog = new CreateEditServerDialog(getParent().getDisplay().getActiveShell(), newServer); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error init CreateEditServerDialog for new server", excp); //$NON-NLS-1$ - return; - } - - int dialogResult = connectionDialog.open(); - if (dialogResult != 0) - return; - - clusterProvider.addNewServer(newServer); - TreeItem newServerItem = addServerItemInServersTree(newServer); - updateClustersInTree(newServerItem); - - } - }); - - MenuItem menuItemEditServer = new MenuItem(serverMenu, SWT.NONE); - menuItemEditServer.setText(Messages.getString("ViewerArea.EditServer")); //$NON-NLS-1$ - menuItemEditServer.setImage(editIcon); - menuItemEditServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - TreeItem serverItem = item[0]; - Server server = getCurrentServerConfig(serverItem); - CreateEditServerDialog connectionDialog; - try { - connectionDialog = new CreateEditServerDialog(getParent().getDisplay().getActiveShell(), server); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error init CreateEditServerDialog for server {}", server.getDescription(), excp); //$NON-NLS-1$ - return; - } - - int dialogResult = connectionDialog.open(); - if (dialogResult == 0) { - // перерисовать в дереве - serverItem.setText(new String[] { server.getDescription() }); - clusterProvider.saveConfig(); - updateClustersInTree(serverItem); - } - - } - - }); - - MenuItem menuItemUpdateServer = new MenuItem(serverMenu, SWT.NONE); - menuItemUpdateServer.setText(Messages.getString("ViewerArea.Update")); //$NON-NLS-1$ - menuItemUpdateServer.setImage(updateIcon); - menuItemUpdateServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - updateClustersInTree(item[0]); - } - }); - - addMenuSeparator(serverMenu); - - MenuItem menuItemDeleteServer = new MenuItem(serverMenu, SWT.NONE); - menuItemDeleteServer.setText(Messages.getString("ViewerArea.RemoveServer")); //$NON-NLS-1$ - menuItemDeleteServer.setImage(deleteIcon); - menuItemDeleteServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - TreeItem serverItem = item[0]; - Server server = getCurrentServerConfig(serverItem); - clusterProvider.removeServer(server); - disposeTreeItemWithChildren(serverItem); - } - }); - } - - private void initClusterMenu() { - // Cluster Menu - clusterMenu = new Menu(serversTree); - - MenuItem menuItemCreateCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemCreateCluster.setText(Messages.getString("ViewerArea.CreateCluster")); //$NON-NLS-1$ - menuItemCreateCluster.setImage(addIcon); - menuItemCreateCluster.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - - CreateEditClusterDialog editClusterDialog; - try { - editClusterDialog = new CreateEditClusterDialog(getParent().getDisplay().getActiveShell(), server, null); - } catch (Exception excp) { - LOGGER.error("Error init CreateEditClusterDialog for new cluster", excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - updateClustersInTree(item[0].getParentItem()); - } - } - }); - - MenuItem menuItemEditCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemEditCluster.setText(Messages.getString("ViewerArea.EditCluster")); //$NON-NLS-1$ - menuItemEditCluster.setImage(editIcon); - menuItemEditCluster.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - - CreateEditClusterDialog editClusterDialog; - try { - editClusterDialog = new CreateEditClusterDialog(getParent().getDisplay().getActiveShell(), server, clusterId); - } catch (Exception excp) { - LOGGER.error("Error init CreateEditClusterDialog for cluster id {}", clusterId, excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - updateClustersInTree(item[0]); - } - } - }); - - MenuItem menuItemUpdateCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemUpdateCluster.setText(Messages.getString("ViewerArea.Update")); //$NON-NLS-1$ - menuItemUpdateCluster.setImage(updateIcon); - menuItemUpdateCluster.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - fillChildrenItemsOfCluster(item[0], server); - - } - }); - - addMenuSeparator(clusterMenu); - - MenuItem menuItemDeleteCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemDeleteCluster.setText(Messages.getString("ViewerArea.DeleteCluster")); //$NON-NLS-1$ - menuItemDeleteCluster.setImage(deleteIcon); - menuItemDeleteCluster.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell(), SWT.ICON_QUESTION |SWT.YES | SWT.NO); - messageBox.setMessage(Messages.getString("ViewerArea.DeleteClusterQuestion")); //$NON-NLS-1$ - int rc = messageBox.open(); - - if (rc == SWT.YES && server.unregCluster(clusterId)) - item[0].dispose(); - - } - }); - - } - - private void initWorkingServerMenu() { - - workingServerMenu = new Menu(serversTree); - - MenuItem menuItemCreateWorkingServer = new MenuItem(workingServerMenu, SWT.NONE); - menuItemCreateWorkingServer.setText(Messages.getString("ViewerArea.CreateWorkingServer")); //$NON-NLS-1$ - menuItemCreateWorkingServer.setImage(addIcon); - menuItemCreateWorkingServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - - CreateEditWorkingServerDialog editWorkingServerDialog; - try { - editWorkingServerDialog = new CreateEditWorkingServerDialog(getParent().getDisplay().getActiveShell(), server, clusterId, null); - } catch (Exception excp) { - LOGGER.error("Error init WorkingServerDialog for cluster id {}", clusterId, excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editWorkingServerDialog.open(); - if (dialogResult == 0) { - var newWorkingServerUuid = editWorkingServerDialog.getNewWorkingServerId(); - if (newWorkingServerUuid != null) { - IWorkingServerInfo workingServerInfo = server.getWorkingServerInfo(clusterId, newWorkingServerUuid); - addWorkingServerItemInNode(item[0].getParentItem(), workingServerInfo); - } - } - } - }); - - MenuItem menuItemEditWorkingServer = new MenuItem(workingServerMenu, SWT.NONE); - menuItemEditWorkingServer.setText(Messages.getString("ViewerArea.EditWorkingServer")); //$NON-NLS-1$ - menuItemEditWorkingServer.setImage(editIcon); - menuItemEditWorkingServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID workingServerId = getCurrentWorkingServerId(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - - CreateEditWorkingServerDialog editClusterDialog; - try { - editClusterDialog = new CreateEditWorkingServerDialog(getParent().getDisplay().getActiveShell(), server, clusterId, workingServerId); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error init WorkingServerDialog for cluster id {}", workingServerId, excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - } - } - }); - } - - private void initInfobaseNodeMenu() { - - infobaseNodeMenu = new Menu(serversTree); - - MenuItem menuItemNewInfobase = new MenuItem(infobaseNodeMenu, SWT.NONE); - menuItemNewInfobase.setText(Messages.getString("ViewerArea.CreateInfobase")); //$NON-NLS-1$ - menuItemNewInfobase.setImage(addIcon); - menuItemNewInfobase.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - - CreateInfobaseDialog infobaseDialog; - try { - infobaseDialog = new CreateInfobaseDialog(getParent().getDisplay().getActiveShell(), server, clusterId, null); - } catch (Exception excp) { - LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ - return; - } - - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - var newInfobaseUuid = infobaseDialog.getNewInfobaseUUID(); - if (newInfobaseUuid != null) { - IInfoBaseInfoShort infoBaseInfo = server.getInfoBaseShortInfo(clusterId, newInfobaseUuid); - addInfobaseItemInInfobaseNode(item[0], infoBaseInfo); - } - } - } - }); - - MenuItem menuItemUpdateInfobases = new MenuItem(infobaseNodeMenu, SWT.NONE); - menuItemUpdateInfobases.setText(Messages.getString("ViewerArea.UpdateInfobases")); //$NON-NLS-1$ - menuItemUpdateInfobases.setImage(updateIcon); - menuItemUpdateInfobases.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - fillInfobasesOfCluster(item[0].getParentItem(), server); - } - }); - } - - private void initInfobaseMenu() { - - infobaseMenu = new Menu(serversTree); - - MenuItem menuItemCopyInfobase = new MenuItem(infobaseMenu, SWT.NONE); - menuItemCopyInfobase.setText(Messages.getString("ViewerArea.CreateNewInfobaseUsingThis")); //$NON-NLS-1$ - menuItemCopyInfobase.setImage(addIcon); - menuItemCopyInfobase.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID sampleInfobaseId = getCurrentInfobaseId(item[0]); - - CreateInfobaseDialog infobaseDialog; - try { - infobaseDialog = new CreateInfobaseDialog(getParent().getDisplay().getActiveShell(), server, clusterId, sampleInfobaseId); - } catch (Exception excp) { - LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ - return; - } - - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - var newInfobaseUuid = infobaseDialog.getNewInfobaseUUID(); - if (newInfobaseUuid != null) { - IInfoBaseInfoShort infoBaseInfo = server.getInfoBaseShortInfo(clusterId, newInfobaseUuid); - addInfobaseItemInInfobaseNode(item[0].getParentItem(), infoBaseInfo); - } - } - } - }); - - MenuItem menuItemEditInfobase = new MenuItem(infobaseMenu, SWT.NONE); - menuItemEditInfobase.setText(Messages.getString("ViewerArea.EditInfobase")); //$NON-NLS-1$ - menuItemEditInfobase.setImage(editIcon); - menuItemEditInfobase.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); - - EditInfobaseDialog infobaseDialog; - try { - infobaseDialog = new EditInfobaseDialog(getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); - } catch (Exception excp) { - excp.printStackTrace(); - return; - } - - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { -// server.clusterConnector.updateInfoBase(server.clusterID, infoBaseInfo); - } - } - }); - - MenuItem menuItemDeleteInfobase = new MenuItem(infobaseMenu, SWT.NONE); - menuItemDeleteInfobase.setText(Messages.getString("ViewerArea.DeleteInfobase")); //$NON-NLS-1$ - menuItemDeleteInfobase.setImage(deleteIcon); - menuItemDeleteInfobase.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); - - DropInfobaseDialog infobaseDialog; - try { - infobaseDialog = new DropInfobaseDialog(getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); - } catch (Exception excp) { - excp.printStackTrace(); - return; - } - - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - item[0].dispose(); - } - } - }); - - // Создание вложенных подпунктов меню - Menu infobaseSubMenuSessionManage = new Menu(infobaseMenu); - - MenuItem infobaseMenuSessionManage = new MenuItem(infobaseMenu, SWT.CASCADE); - infobaseMenuSessionManage.setText(Messages.getString("ViewerArea.SessionManage")); //$NON-NLS-1$ - infobaseMenuSessionManage.setMenu(infobaseSubMenuSessionManage); -// infobaseSubMenuSessionManage.setImage(terminateSessionIcon); - - MenuItem menuItemLockUserSessionsNow = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); - menuItemLockUserSessionsNow.setText(Messages.getString("ViewerArea.LockSessionsNow")); //$NON-NLS-1$ - menuItemLockUserSessionsNow.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - TreeItem selectItem = item[0]; - - Server server = getCurrentServerConfig(selectItem); - UUID clusterId = getCurrentClusterId(selectItem); - UUID infobaseId = getCurrentInfobaseId(selectItem); - - IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infobaseId); - if (infoBaseInfo == null) - return; - - infoBaseInfo.setScheduledJobsDenied(true); - infoBaseInfo.setSessionsDenied(true); - infoBaseInfo.setDeniedFrom(null); - infoBaseInfo.setDeniedTo(null); - infoBaseInfo.setDeniedMessage(""); //$NON-NLS-1$ - infoBaseInfo.setDeniedParameter(""); //$NON-NLS-1$ - infoBaseInfo.setPermissionCode(""); //$NON-NLS-1$ - - server.updateInfoBase(clusterId, infoBaseInfo); - } - }); - - MenuItem menuItemTerminateAllSessions = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); - menuItemTerminateAllSessions.setText(Messages.getString("ViewerArea.TerminateAllSessions")); //$NON-NLS-1$ - menuItemTerminateAllSessions.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); - - server.terminateAllSessionsOfInfobase(clusterId, infobaseId, false); - } - }); - - MenuItem menuItemTerminateUserSessions = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); - menuItemTerminateUserSessions.setText(Messages.getString("ViewerArea.TerminateUsersSessions")); //$NON-NLS-1$ - menuItemTerminateUserSessions.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); - - server.terminateAllSessionsOfInfobase(clusterId, infobaseId, true); - } - }); - } - - private void initSessionTable(TabFolder tabFolder) { - - tabSessions = new TabItem(tabFolder, SWT.NONE); - tabSessions.setText(Messages.getString("ViewerArea.Sessions")); //$NON-NLS-1$ - - tableSessions = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK); - tabSessions.setControl(tableSessions); - tableSessions.setHeaderVisible(true); - tableSessions.setLinesVisible(true); - - initSessionsTableContextMenu(); - - SessionInfoExtended.initColumnsName(sessionColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().sessionColumnProperties; - - String[] columnNameList = sessionColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) - addTableColumn(tableSessions, columnName, columnProperties.width, columnProperties.visible); - - int[] columnOrder = columnProperties.order; - if (columnOrder != null && tableSessions.getColumnCount() == columnOrder.length) - tableSessions.setColumnOrder(columnOrder); - - } - - private void initSessionsTableContextMenu() { - - Menu tableSessionsMenu = new Menu(tableSessions); - tableSessions.setMenu(tableSessionsMenu); - tableSessions.addKeyListener(keyListener); - - tableSessions.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - if (event.detail == SWT.CHECK) { - TableItem item = (TableItem) event.item; - String id = item.getText(1).concat("*").concat(item.getText(2)); - if (item.getChecked()) { - watchedSessions.add(id); - item.setForeground(watchedSessionColor); - } else { - watchedSessions.remove(id); - item.setForeground(standardColor); - } - } - } - }); - - // Выделение одной ячейки, для копирования значения из нее через CTRL+C - // Из-за добавления этого Listener пропадает прямоугольник выделения строк (передвигая мышь с зажатой ЛКМ) -// tableSessions.addListener(SWT.MouseDown, new Listener() { -// @Override -// public void handleEvent(Event event) { -// Table currentTable = (Table) event.widget; -// -// Point pt = new Point(event.x, event.y); -// TableItem item = currentTable.getItem(pt); -// if(item != null) { -// for (int col = 0; col < currentTable.getColumnCount(); col++) { -// Rectangle rect = item.getBounds(col); -// if (rect.contains(pt)) { -// -// if (Objects.nonNull(lastSelectItem) && !lastSelectItem.isDisposed()) { -// lastSelectItem.setForeground(lastSelectColumn, new Color(0, 0, 0)); -// } -// -//// System.out.println("item clicked."); -//// System.out.println("column is " + col); -// System.out.println(item.getText(col)); -// -//// Color blue = display.getSystemColor(SWT.COLOR_BLUE); -// item.setForeground(col, new Color(0, 100, 128)); -//// item.setFont(col, fontBold); -// -// lastSelectItem = item; -// lastSelectColumn = col; -// break; -// } -// } -// } -// } -// }); - - MenuItem menuItemUpdateList = new MenuItem(tableSessionsMenu, SWT.NONE); - menuItemUpdateList.setText(Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ - menuItemUpdateList.setAccelerator(SWT.F5);//TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - MenuItem menuItemViewSession = new MenuItem(tableSessionsMenu, SWT.NONE); - menuItemViewSession.setText(Messages.getString("ViewerArea.ViewSession").concat("\tF2")); //$NON-NLS-1$ - menuItemViewSession.setAccelerator(SWT.F2); - menuItemViewSession.setImage(editIcon); - menuItemViewSession.addSelectionListener(editItemListener); -// menuItemViewSession.addSelectionListener(new SelectionAdapter() { -// @Override -// public void widgetSelected(SelectionEvent event) { -// TableItem[] item = tableSessions.getSelection(); -// if (item.length == 0) -// return; -// -// Server server = (Server) item[0].getData(SERVER_INFO); -// UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); -// UUID sessionId = (UUID) item[0].getData(SESSION_ID); -// ISessionInfo sessionInfo = (ISessionInfo) item[0].getData("sessionInfo"); -// -// SessionInfoDialog editClusterDialog; -// try { -// editClusterDialog = new SessionInfoDialog(getParent().getDisplay().getActiveShell(), server, clusterId, sessionId, sessionInfo); -// } catch (Exception excp) { -// excp.printStackTrace(); -// LOGGER.error("Error init SessionInfoDialog for session id {}", sessionId, excp); //$NON-NLS-1$ -// return; -// } -// -// int dialogResult = editClusterDialog.open(); -// if (dialogResult == 0) { -// } -// } -// }); - - MenuItem menuItemKillSession = new MenuItem(tableSessionsMenu, SWT.NONE); - menuItemKillSession.setText(Messages.getString("ViewerArea.KillSession").concat("\tDEL")); //$NON-NLS-1$ - menuItemKillSession.setAccelerator(SWT.DEL); - menuItemKillSession.setImage(deleteIcon); - menuItemKillSession.addSelectionListener(deleteItemListener); - - } - - private void deleteSelectSession() { - - Table currentTable = null; - - if (currentTabitem.equals(tabSessions)) - currentTable = tableSessions; - else if (currentTabitem.equals(tabConnections)) - currentTable = tableConnections; - else if (currentTabitem.equals(tabWorkingServers)) - currentTable = tableWorkingServers; - - if (currentTable == null) - return; - - TableItem[] selectedItems = currentTable.getSelection(); - if (selectedItems.length == 0) - return; - - for (TableItem item : selectedItems) { - item.setForeground(deletedItemColor); - - if (currentTable.equals(tableSessions)) { - Server server = (Server) item.getData(SERVER_INFO); - UUID clusterId = (UUID) item.getData(CLUSTER_ID); - UUID sessionId = (UUID) item.getData(SESSION_ID); - - if (server.terminateSession(clusterId, sessionId)) - item.dispose(); // update tableSessions - - } else if (currentTable.equals(tableConnections)) { - Server server = (Server) item.getData(SERVER_INFO); - UUID clusterId = (UUID) item.getData(CLUSTER_ID); - UUID pricessId = (UUID) item.getData(WORKINGPROCESS_ID); - UUID connectionId = (UUID) item.getData(CONNECTION_ID); - UUID infobaseId = (UUID) item.getData(INFOBASE_ID); - - if (server.disconnectConnection(clusterId, pricessId, connectionId, infobaseId)) - item.dispose(); // update tableConnections - - } else if (currentTable.equals(tableWorkingServers)) { - Server server = (Server) item.getData(SERVER_INFO); - UUID clusterId = (UUID) item.getData(CLUSTER_ID); - UUID workingServerId = (UUID) item.getData(WORKINGSERVER_ID); - - if (server.unregWorkingServer(clusterId, workingServerId)) - item.dispose(); // update tableWorkingServers - } else { - break; - } - } - } - - private void initConnectionsTable(TabFolder tabFolder) { - - tabConnections = new TabItem(tabFolder, SWT.NONE); - tabConnections.setText(Messages.getString("ViewerArea.Connections")); //$NON-NLS-1$ - - tableConnections = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabConnections.setControl(tableConnections); - tableConnections.setHeaderVisible(true); - tableConnections.setLinesVisible(true); - - initConnectionsTableContextMenu(); - - ConnectionInfoExtended.initColumnsName(connectionColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().connectionColumnProperties; - - String[] columnNameList = connectionColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) - addTableColumn(tableConnections, columnName, columnProperties.width, columnProperties.visible); - - int[] columnOrder = columnProperties.order; - if (columnOrder != null && tableConnections.getColumnCount() == columnOrder.length) - tableConnections.setColumnOrder(columnOrder); - - } - - private void initConnectionsTableContextMenu() { - - Menu tableConnectionsMenu = new Menu(tableConnections); - tableConnections.setMenu(tableConnectionsMenu); - tableConnections.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(tableConnectionsMenu, SWT.NONE); - menuItemUpdateList.setText(Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ - menuItemUpdateList.setAccelerator(SWT.F5);//TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - MenuItem menuItemKillSession = new MenuItem(tableConnectionsMenu, SWT.NONE); - menuItemKillSession.setText(Messages.getString("ViewerArea.KillConnection").concat("\tDEL")); //$NON-NLS-1$ - menuItemKillSession.setAccelerator(SWT.DEL); - menuItemKillSession.setImage(deleteIcon); - menuItemKillSession.addSelectionListener(deleteItemListener); - - } - - private void initLocksTable(TabFolder tabFolder) { - - tabLocks = new TabItem(tabFolder, SWT.NONE); - tabLocks.setText(Messages.getString("ViewerArea.Locks")); //$NON-NLS-1$ - - tableLocks = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabLocks.setControl(tableLocks); - tableLocks.setHeaderVisible(true); - tableLocks.setLinesVisible(true); - - initLocksTableContextMenu(); - - LockInfoExtended.initColumnsName(lockColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().lockColumnProperties; - - String[] columnNameList = lockColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) - addTableColumn(tableLocks, columnName, columnProperties.width, columnProperties.visible); - - int[] columnOrder = columnProperties.order; - if (columnOrder != null && tableLocks.getColumnCount() == columnOrder.length) - tableLocks.setColumnOrder(columnOrder); - - } - - private void initLocksTableContextMenu() { - - Menu tableLocksMenu = new Menu(tableLocks); - tableLocks.setMenu(tableLocksMenu); - tableLocks.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(tableLocksMenu, SWT.NONE); - menuItemUpdateList.setText(Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ - menuItemUpdateList.setAccelerator(SWT.F5);//TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - } - - private void initWorkingProcessesTable(TabFolder tabFolder) { - - tabWorkingProcesses = new TabItem(tabFolder, SWT.NONE); - tabWorkingProcesses.setText(Messages.getString("ViewerArea.WorkingProcesses")); //$NON-NLS-1$ - - tableWorkingProcesses = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabWorkingProcesses.setControl(tableWorkingProcesses); - tableWorkingProcesses.setHeaderVisible(true); - tableWorkingProcesses.setLinesVisible(true); - - initWorkingProcessesTableContextMenu(); - - WorkingProcessInfoExtended.initColumnsName(wpColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().wpColumnProperties; - - String[] columnNameList = wpColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) - addTableColumn(tableWorkingProcesses, columnName, columnProperties.width, columnProperties.visible); - - int[] columnOrder = columnProperties.order; - if (columnOrder != null && tableWorkingProcesses.getColumnCount() == columnOrder.length) - tableWorkingProcesses.setColumnOrder(columnOrder); - - } - - private void initWorkingProcessesTableContextMenu() { - - Menu tableWorkingProcessesMenu = new Menu(tableWorkingProcesses); - tableWorkingProcesses.setMenu(tableWorkingProcessesMenu); - tableWorkingProcesses.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(tableWorkingProcessesMenu, SWT.NONE); - menuItemUpdateList.setText(Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ - menuItemUpdateList.setAccelerator(SWT.F5);//TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - } - - private void initWorkingServersTable(TabFolder tabFolder) { - - tabWorkingServers = new TabItem(tabFolder, SWT.NONE); - tabWorkingServers.setText(Messages.getString("ViewerArea.WorkingServers")); //$NON-NLS-1$ - - tableWorkingServers = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabWorkingServers.setControl(tableWorkingServers); - tableWorkingServers.setHeaderVisible(true); - tableWorkingServers.setLinesVisible(true); - - initWorkingServersTableContextMenu(); - - WorkingServerInfoExtended.initColumnsName(wsColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().wsColumnProperties; - - String[] columnNameList = wsColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) - addTableColumn(tableWorkingServers, columnName, columnProperties.width, columnProperties.visible); - - int[] columnOrder = columnProperties.order; - if (columnOrder != null && tableWorkingServers.getColumnCount() == columnOrder.length) - tableWorkingServers.setColumnOrder(columnOrder); - - } - - private void initWorkingServersTableContextMenu() { - - Menu workingServersMenu = new Menu(tableWorkingServers); - tableWorkingServers.setMenu(workingServersMenu); - tableWorkingServers.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(workingServersMenu, SWT.NONE); - menuItemUpdateList.setText(Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ - menuItemUpdateList.setAccelerator(SWT.F5);//TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - MenuItem menuItemCreateWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); - menuItemCreateWorkingServer.setText(Messages.getString("ViewerArea.CreateWorkingServer")); //$NON-NLS-1$ - menuItemCreateWorkingServer.setImage(addIcon); - menuItemCreateWorkingServer.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TableItem[] item = tableWorkingServers.getSelection(); - if (item.length == 0) - return; - - Server server = (Server) item[0].getData(SERVER_INFO); - UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); - - CreateEditWorkingServerDialog editWorkingServerDialog; - try { - editWorkingServerDialog = new CreateEditWorkingServerDialog(getParent().getDisplay().getActiveShell(), server, clusterId, null); - } catch (Exception excp) { - LOGGER.error("Error init WorkingServerDialog for cluster id {}", clusterId, excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editWorkingServerDialog.open(); - if (dialogResult == 0) { - var newWorkingServerUuid = editWorkingServerDialog.getNewWorkingServerId(); - if (newWorkingServerUuid != null) { - IWorkingServerInfo workingServerInfo = server.getWorkingServerInfo(clusterId, newWorkingServerUuid); - addWorkingServerInTable(server, clusterId, workingServerInfo); - } - } - } - }); - - MenuItem menuItemEditWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); - menuItemEditWorkingServer.setText(Messages.getString("ViewerArea.EditWorkingServer").concat("\tF2")); //$NON-NLS-1$ - menuItemEditWorkingServer.setImage(editIcon); - menuItemEditWorkingServer.addSelectionListener(editItemListener); - - MenuItem menuItemDeleteWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); - menuItemDeleteWorkingServer.setText(Messages.getString("ViewerArea.DeleteWorkingServer").concat("\tDEL")); //$NON-NLS-1$ - menuItemDeleteWorkingServer.setImage(deleteIcon); - menuItemDeleteWorkingServer.addSelectionListener(deleteItemListener); - - } - - private void fillServersList() { - // TODO Auto-generated method stub - } - - private void updateClustersInTree(TreeItem serverItem) { - - Server server = getCurrentServerConfig(serverItem); - TreeItem[] clustersItems = serverItem.getItems(); - - // у отключенного сервера удаляем все дочерние элементы - if (!server.isConnected()) { - for (TreeItem clusterItem : clustersItems) { - disposeTreeItemWithChildren(clusterItem); - } - return; - } - - List clusters = server.getClusters(); - - // удаление несуществующих элементов - for (TreeItem clusterItem : clustersItems) { - UUID currentClusterId = getCurrentClusterId(clusterItem); - List foundCluster = clusters.stream() - .filter(c -> c.getClusterId().equals(currentClusterId)) - .collect(Collectors.toList()); - - if (foundCluster.isEmpty()) { - disposeTreeItemWithChildren(clusterItem); - } - } - - // добавление новых элементов - clusters.forEach(clusterInfo -> { - var itemFound = false; - TreeItem currentClusterItem = null; - for (TreeItem clusterItem : serverItem.getItems()) { - if (getCurrentClusterId(clusterItem).equals(clusterInfo.getClusterId())) { - currentClusterItem = clusterItem; - itemFound = true; - break; - } - } - - if (!itemFound) - currentClusterItem = addClusterItemInServersTree(serverItem, clusterInfo); - - // Заполнение дерева кластера - if (currentClusterItem != null) - fillChildrenItemsOfCluster(currentClusterItem, server); - - }); - - - // Разворачиваем дерево, если включена настройка - serverItem.setExpanded(ClusterProvider.getCommonConfig().expandServersTree); - } - - private void fillChildrenItemsOfCluster(TreeItem clusterItem, Server server) { - - fillInfobasesOfCluster(clusterItem, server); - fillWorkingProcessesInCluster(clusterItem, server); - fillWorkingServersInCluster(clusterItem, server); - - clusterItem.setExpanded(ClusterProvider.getCommonConfig().expandClustersTree); - } - - private void fillInfobasesOfCluster(TreeItem clusterItem, Server server) { - - TreeItem infobasesNode = null; - for (TreeItem treeItem : clusterItem.getItems()) { - if (treeItem.getData("Type") == TreeItemType.INFOBASE_NODE) { //$NON-NLS-1$ - infobasesNode = treeItem; - break; - } - } - - if (infobasesNode == null) { - infobasesNode = new TreeItem(clusterItem, SWT.NONE); - infobasesNode.setData("Type", TreeItemType.INFOBASE_NODE); //$NON-NLS-1$ - infobasesNode.setImage(infobasesIcon); - infobasesNode.setChecked(false); - } - - UUID clusterId = getCurrentClusterId(infobasesNode); - List infoBases = server.getInfoBasesShort(clusterId); - - var infobasesNodeTitle = String.format(Messages.getString("ViewerArea.InfobasesCount"), infoBases.size()); //$NON-NLS-1$ - infobasesNode.setText(new String[] { infobasesNodeTitle }); - - if (infoBases.isEmpty()) { - for (TreeItem infobase : infobasesNode.getItems()) { - infobase.dispose(); - } - return; - } - - // удаление несуществующих элементов - for (TreeItem infobaseItem : infobasesNode.getItems()) { - UUID currentInfobaseId = getCurrentInfobaseId(infobaseItem); - List foundItems = infoBases.stream() - .filter(c -> c.getInfoBaseId().equals(currentInfobaseId)) - .collect(Collectors.toList()); - - if (foundItems.isEmpty()) - infobaseItem.dispose(); - - } - - // добавление новых элементов - for (IInfoBaseInfoShort infoBaseInfo : infoBases) { -// infoBases.forEach(infoBaseInfo -> { - - var itemFound = false; - for (TreeItem infobaseItem : infobasesNode.getItems()) { - if (getCurrentInfobaseId(infobaseItem).equals(infoBaseInfo.getInfoBaseId())) { - itemFound = true; - break; - } - } - - if (!itemFound) - addInfobaseItemInInfobaseNode(infobasesNode, infoBaseInfo); - } - - infobasesNode.setExpanded(ClusterProvider.getCommonConfig().expandInfobasesTree); - - } - - private void fillWorkingProcessesInCluster(TreeItem clusterItem, Server server) { - - TreeItem workingProcessesNode = null; - for (TreeItem treeItem : clusterItem.getItems()) { - if (treeItem.getData("Type") == TreeItemType.WORKINGPROCESS_NODE) { //$NON-NLS-1$ - workingProcessesNode = treeItem; - break; - } - } - - if (!ClusterProvider.getCommonConfig().showWorkingProcessesTree) { - if (workingProcessesNode != null) - workingProcessesNode.dispose(); - return; - } - - if (workingProcessesNode == null) { - workingProcessesNode = new TreeItem(clusterItem, SWT.NONE); - workingProcessesNode.setData("Type", TreeItemType.WORKINGPROCESS_NODE); //$NON-NLS-1$ - workingProcessesNode.setImage(workingProcessesIcon); - workingProcessesNode.setChecked(false); - } - - UUID clusterId = getCurrentClusterId(workingProcessesNode); - List wProcesses = server.getWorkingProcesses(clusterId); - - var workingProcessesNodeTitle = String.format(Messages.getString("ViewerArea.WorkingProcessesCount"), wProcesses.size()); //$NON-NLS-1$ - workingProcessesNode.setText(new String[] { workingProcessesNodeTitle }); - - if (wProcesses.isEmpty()) { - for (TreeItem workingProcess : workingProcessesNode.getItems()) { - workingProcess.dispose(); - } - return; - } - - // удаление несуществующих элементов - for (TreeItem workingProcessItem : workingProcessesNode.getItems()) { - UUID currentWorkingProcessId = getCurrentWorkingProcessId(workingProcessItem); - List foundItems = wProcesses.stream() - .filter(c -> c.getWorkingProcessId().equals(currentWorkingProcessId)) - .collect(Collectors.toList()); - - if (foundItems.isEmpty()) - workingProcessItem.dispose(); - - } - - // добавление новых элементов - for (IWorkingProcessInfo workingProcessInfo : wProcesses) { -// wProcesses.forEach(workingProcessInfo -> { - - var itemFound = false; - for (TreeItem workingProcessItem : workingProcessesNode.getItems()) { - if (getCurrentWorkingProcessId(workingProcessItem).equals(workingProcessInfo.getWorkingProcessId())) { - itemFound = true; - break; - } - } - - if (!itemFound) - addWorkingProcessItemInNode(workingProcessesNode, workingProcessInfo); - }; - - } - - private void fillWorkingServersInCluster(TreeItem clusterItem, Server server) { - - TreeItem workingServersNode = null; - for (TreeItem treeItem : clusterItem.getItems()) { - if (treeItem.getData("Type") == TreeItemType.WORKINGSERVER_NODE) { //$NON-NLS-1$ - workingServersNode = treeItem; - break; - } - } - - if (!ClusterProvider.getCommonConfig().showWorkingServersTree) { - if (workingServersNode != null) - workingServersNode.dispose(); - return; - } - - if (workingServersNode == null) { - workingServersNode = new TreeItem(clusterItem, SWT.NONE); - workingServersNode.setData("Type", TreeItemType.WORKINGSERVER_NODE); //$NON-NLS-1$ - workingServersNode.setImage(workingServerIcon); - workingServersNode.setChecked(false); - } - - UUID clusterId = getCurrentClusterId(workingServersNode); - List wServers = server.getWorkingServers(clusterId); - - var workingServerNodeTitle = String.format(Messages.getString("ViewerArea.WorkingServersCount"), wServers.size()); //$NON-NLS-1$ - workingServersNode.setText(new String[] { workingServerNodeTitle }); - - if (wServers.isEmpty()) { - for (TreeItem workingServerItem : workingServersNode.getItems()) { - workingServerItem.dispose(); - } - return; - } - - // удаление несуществующих элементов - for (TreeItem workingServerItem : workingServersNode.getItems()) { - UUID currentWorkingServerId = getCurrentWorkingServerId(workingServerItem); - List foundItems = wServers.stream() - .filter(c -> c.getWorkingServerId().equals(currentWorkingServerId)) - .collect(Collectors.toList()); - - if (foundItems.isEmpty()) - workingServerItem.dispose(); - - } - - // добавление новых элементов - for (IWorkingServerInfo workingServerInfo : wServers) { -// wServers.forEach(workingServerInfo -> { - - var itemFound = false; - for (TreeItem workingServerItem : workingServersNode.getItems()) { - if (getCurrentWorkingServerId(workingServerItem).equals(workingServerInfo.getWorkingServerId())) { - itemFound = true; - break; - } - } - - if (!itemFound) - addWorkingServerItemInNode(workingServersNode, workingServerInfo); - } - - } - - private TreeItem addServerItemInServersTree(Server server) { - - var item = new TreeItem(serversTree, SWT.NONE); - item.setText(new String[] { server.getDescription() }); - item.setData("Type", TreeItemType.SERVER); //$NON-NLS-1$ - item.setData(SERVER_INFO, server); - - item.setImage(server.isConnected() ? serverIconUp : serverIcon); - - return item; - } - - private TreeItem addClusterItemInServersTree(TreeItem serverItem, IClusterInfo clusterInfo) { - - var clusterTitle = String.format("%s (%s)", clusterInfo.getName(), clusterInfo.getMainPort()); //$NON-NLS-1$ - - var clusterItem = new TreeItem(serverItem, SWT.NONE); - clusterItem.setText(new String[] { clusterTitle }); - clusterItem.setData("Type", TreeItemType.CLUSTER); //$NON-NLS-1$ - clusterItem.setData(CLUSTER_ID, clusterInfo.getClusterId()); - clusterItem.setImage(clusterIcon); - - return clusterItem; - } - - private void addInfobaseItemInInfobaseNode(TreeItem infobaseNode, IInfoBaseInfoShort ibInfo) { - - String infobaseTitle; - if (ClusterProvider.getCommonConfig().showInfobaseDescription && !ibInfo.getDescr().isBlank()) - infobaseTitle = String.format("%s (%s)", ibInfo.getName(), ibInfo.getDescr()); //$NON-NLS-1$ - else - infobaseTitle = String.format("%s", ibInfo.getName()); //$NON-NLS-1$ - - var item = new TreeItem(infobaseNode, SWT.NONE); - item.setText(new String[] { infobaseTitle }); - item.setData("Type", TreeItemType.INFOBASE); //$NON-NLS-1$ - item.setData(INFOBASE_ID, ibInfo.getInfoBaseId()); - item.setImage(0, infobaseIcon); - item.setChecked(false); - -// item.setImage(1, ibInfo.isSessionsDenied() ? lockUsersIcon : null); - - } - - private void addWorkingProcessItemInNode(TreeItem wpNodeItem, IWorkingProcessInfo wpInfo) { - - var itemTitle = String.format("%s (%s)", wpInfo.getHostName(), wpInfo.getMainPort()); //$NON-NLS-1$ - - var item = new TreeItem(wpNodeItem, SWT.NONE); - item.setText(new String[] { itemTitle}); - item.setData("Type", TreeItemType.WORKINGPROCESS); //$NON-NLS-1$ - item.setData(WORKINGPROCESS_ID, wpInfo.getWorkingProcessId()); - item.setImage(workingProcessIcon); - item.setChecked(false); - } - - private void addWorkingServerItemInNode(TreeItem wsNodeItem, IWorkingServerInfo wpInfo) { - - var itemTitle = String.format("%s (%s)", wpInfo.getHostName(), wpInfo.getMainPort()); //$NON-NLS-1$ - - var item = new TreeItem(wsNodeItem, SWT.NONE); - item.setText(new String[] { itemTitle}); - item.setData("Type", TreeItemType.WORKINGSERVER); //$NON-NLS-1$ - item.setData(WORKINGSERVER_ID, wpInfo.getWorkingServerId()); - item.setImage(workingServerIcon); - item.setChecked(false); - } - - private void addSessionInTable(Server server, UUID clusterId, UUID infobaseId, ISessionInfo sessionInfo, List connections) { - - SessionInfoExtended sessionInfoExtended = new SessionInfoExtended(server, clusterId, infobaseId, sessionInfo, connections, sessionColumnsMap); - - var sessionItem = new TableItem(tableSessions, SWT.NONE); - sessionItem.setText(sessionInfoExtended.getExtendedInfo()); - sessionItem.setData(SERVER_INFO, server); - sessionItem.setData(CLUSTER_ID, clusterId); - sessionItem.setData(SESSION_ID, sessionInfo.getSid()); // sessionInfo.getSessionId() ??? - sessionItem.setData("sessionInfo", sessionInfo); // agentConnection.getSessionInfo(clusterId, sid); ошибка... - sessionItem.setImage(userIcon); - sessionItem.setChecked(false); - - - if (IInfoExtended.highlightItem(sessionInfo.getStartedAt())) - sessionItem.setForeground(newItemColor); - - Config commonConfig = ClusterProvider.getCommonConfig(); - if (commonConfig.shadowSleepSessions && sessionInfo.getHibernate()) - sessionItem.setForeground(shadowItemColor); - - String id = sessionItem.getText(1).concat("*").concat(sessionItem.getText(2)); - if (watchedSessions.contains(id)) { - sessionItem.setChecked(true); - sessionItem.setForeground(watchedSessionColor); - } - - switch (sessionInfo.getAppId()) { - case Server.THIN_CLIENT: - case Server.THICK_CLIENT: - case Server.DESIGNER: - sessionItem.setImage(sessionInfo.getHibernate() ? sleepUserIcon : userIcon); - break; - case Server.SERVER_CONSOLE: - case Server.RAS_CONSOLE: - case Server.JOBSCHEDULER: - sessionItem.setImage(serviceIcon); - break; - default: - sessionItem.setImage(sessionInfo.getHibernate() ? sleepUserIcon : userIcon); - } - } - - private void addConnectionInTable(Server server, UUID clusterId, UUID infobaseId, IInfoBaseConnectionShort connectionInfo, List workingProcesses) { - - ConnectionInfoExtended sessionInfoExtended = new ConnectionInfoExtended(server, clusterId, infobaseId, connectionInfo, workingProcesses, connectionColumnsMap); - - var connectionItem = new TableItem(tableConnections, SWT.NONE); - connectionItem.setText(sessionInfoExtended.getExtendedInfo()); - connectionItem.setData(SERVER_INFO, server); - connectionItem.setData(CLUSTER_ID, clusterId); - connectionItem.setData(WORKINGPROCESS_ID, connectionInfo.getWorkingProcessId()); - connectionItem.setData(INFOBASE_ID, connectionInfo.getInfoBaseId()); - connectionItem.setData(CONNECTION_ID, connectionInfo.getInfoBaseConnectionId()); - connectionItem.setImage(connectionIcon); - connectionItem.setChecked(false); - - if (IInfoExtended.highlightItem(connectionInfo.getConnectedAt())) - connectionItem.setForeground(newItemColor); - - } - - private void addLocksInTable(Server server, UUID clusterId, UUID infobaseId, IObjectLockInfo lockInfo, List sessionsInfo, List connections) { - - LockInfoExtended lockInfoExtended = new LockInfoExtended(server, clusterId, infobaseId, lockInfo, sessionsInfo, connections, lockColumnsMap); - - var lockItem = new TableItem(tableLocks, SWT.NONE); - lockItem.setText(lockInfoExtended.getExtendedInfo()); - lockItem.setData(CLUSTER_ID, clusterId); - lockItem.setData(INFOBASE_ID, infobaseId); - lockItem.setData("IObjectLockInfo", lockInfo); //$NON-NLS-1$ - lockItem.setImage(locksIcon); - lockItem.setChecked(false); - - if (IInfoExtended.highlightItem(lockInfo.getLockedAt())) - lockItem.setForeground(newItemColor); - - } - - private void addWorkingProcessInTable(Server server, UUID clusterId, IWorkingProcessInfo workingProcessInfo) { - - WorkingProcessInfoExtended wpInfoExtended = new WorkingProcessInfoExtended(server, clusterId, workingProcessInfo, wpColumnsMap); - - var wpItem = new TableItem(tableWorkingProcesses, SWT.NONE); - wpItem.setText(wpInfoExtended.getExtendedInfo()); - wpItem.setData(SERVER_INFO, server); - wpItem.setData(CLUSTER_ID, clusterId); - wpItem.setData(WORKINGPROCESS_ID, workingProcessInfo.getWorkingProcessId()); - wpItem.setImage(workingProcessIcon); - wpItem.setChecked(false); - - if (IInfoExtended.highlightItem(workingProcessInfo.getStartedAt())) - wpItem.setForeground(newItemColor); - - } - - private void addWorkingServerInTable(Server server, UUID clusterId, IWorkingServerInfo workingServerInfo) { - - WorkingServerInfoExtended wsInfoExtended = new WorkingServerInfoExtended(server, clusterId, workingServerInfo, wsColumnsMap); - - var connectionItem = new TableItem(tableWorkingServers, SWT.NONE); - connectionItem.setText(wsInfoExtended.getExtendedInfo()); - connectionItem.setData(SERVER_INFO, server); - connectionItem.setData(CLUSTER_ID, clusterId); - connectionItem.setData(WORKINGSERVER_ID, workingServerInfo.getWorkingServerId()); - connectionItem.setImage(workingServerIcon); - connectionItem.setChecked(false); - } - - private void addTableColumn(Table table, String text, int[] columnWidth, boolean[] columnVisible) { - var newColumn = new TableColumn(table, SWT.NONE); - newColumn.setText(text); - newColumn.setMoveable(true); - newColumn.setAlignment(SWT.RIGHT); - - int numOfColumn = table.getColumnCount() - 1; - - if (columnVisible != null && columnVisible[numOfColumn]) { - newColumn.setResizable(true); - newColumn.setWidth( -// columnWidth == null -// || columnWidth.length <= table.getColumnCount() -// || - columnWidth[numOfColumn] == 0 - ? 100 : columnWidth[numOfColumn]); - } else { - newColumn.setResizable(false); - newColumn.setWidth(0); - } - - newColumn.addListener(SWT.Move, columnMoveListener); - newColumn.addListener(SWT.Resize, columnResizeListener); -// newColumn.addControlListener(columnResizeListener); - - } - - private TreeItemType getTreeItemType(TreeItem item) { - return (TreeItemType) item.getData("Type"); //$NON-NLS-1$ - } - - private Server getCurrentServerConfig(TreeItem item) { - - if (getTreeItemType(item) == TreeItemType.SERVER) - return (Server) item.getData(SERVER_INFO); - - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { - - if (getTreeItemType(parentItem) == TreeItemType.SERVER) - return (Server) parentItem.getData(SERVER_INFO); - else - parentItem = parentItem.getParentItem(); - } - throw new IllegalStateException("Error get ServerConfig from item."); //$NON-NLS-1$ -// return null; - } - - - private UUID getCurrentClusterId(TreeItem item) { - - if (getTreeItemType(item) == TreeItemType.CLUSTER) - return (UUID) item.getData(CLUSTER_ID); - - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { - - if (getTreeItemType(parentItem) == TreeItemType.CLUSTER) - return (UUID) parentItem.getData(CLUSTER_ID); - else - parentItem = parentItem.getParentItem(); - } - return null; - } - - - private UUID getCurrentWorkingProcessId(TreeItem item) { - - if (getTreeItemType(item) == TreeItemType.WORKINGPROCESS) - return (UUID) item.getData(WORKINGPROCESS_ID); - - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { - - if (getTreeItemType(parentItem) == TreeItemType.WORKINGPROCESS) - return (UUID) parentItem.getData(WORKINGPROCESS_ID); - else - parentItem = parentItem.getParentItem(); - } - return null; - } - - private UUID getCurrentWorkingServerId(TreeItem item) { - - if (getTreeItemType(item) == TreeItemType.WORKINGSERVER) - return (UUID) item.getData(WORKINGSERVER_ID); - - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { - - if (getTreeItemType(parentItem) == TreeItemType.WORKINGSERVER) - return (UUID) parentItem.getData(WORKINGSERVER_ID); - else - parentItem = parentItem.getParentItem(); - } - return null; - } - - private UUID getCurrentInfobaseId(TreeItem item) { - if (getTreeItemType(item) == TreeItemType.INFOBASE) - return (UUID) item.getData(INFOBASE_ID); - else - return null; - } - - private void disposeTreeItemWithChildren(TreeItem item) { - TreeItem[] childItems = item.getItems(); - for (TreeItem childItem : childItems) { - disposeTreeItemWithChildren(childItem); - childItem.dispose(); - } - item.dispose(); - } - - private Image getImage(String name) { - return new Image(getParent().getDisplay(), this.getClass().getResourceAsStream("/icons/".concat(name))); //$NON-NLS-1$ - } - - private void connectToAllServers(boolean connectAll) { - - TreeItem[] serversItem = serversTree.getItems(); - - for (TreeItem serverItem : serversItem) { - Server server = getCurrentServerConfig(serverItem); - if ((connectAll || server.autoconnect) && !server.isConnected()) - connectServerItem(serverItem, true); - } - } - - private void diconnectFromAllServers() { - - TreeItem[] serversItem = serversTree.getItems(); - - for (TreeItem serverItem : serversItem) { - disconnectServerItem(serverItem); - } - } - - private void connectServerItem(TreeItem serverItem, boolean silentMode) { - - // async не работает асинхронно - serverItem.setImage(serverIconConnecting); - Display.getDefault().asyncExec(new Runnable() { - -// @Override - public void run() { - - Server server = getCurrentServerConfig(serverItem); - server.connectToServer(false, silentMode); - - serverItem.setImage(server.isConnected() ? serverIconUp : serverIconDown); - serverItem.setText(new String[] { server.getDescription()}); - updateClustersInTree(serverItem); - } - }); - } - - private void disconnectServerItem(TreeItem serverItem) { - Server server = getCurrentServerConfig(serverItem); - server.disconnectFromAgent(); - serverItem.setImage(serverIconDown); - - TreeItem[] clusterItems = serverItem.getItems(); - for (TreeItem clusterItem : clusterItems) { - disposeTreeItemWithChildren(clusterItem); - } - } - - private void fillTabs(TreeItem treeItem) { - - highlightTreeItem(treeItem); - - Server server; - UUID clusterId; - UUID infobaseId; - UUID workingProcessId; - - List sessions; - List connections; - List locks; - List workingProcesses; - List workingServers; - - clearTabs(); - switch (getTreeItemType(treeItem)) { - case SERVER: - return; - - case CLUSTER: - case INFOBASE_NODE: - case WORKINGPROCESS_NODE: - - server = getCurrentServerConfig(treeItem); - clusterId = getCurrentClusterId(treeItem); - infobaseId = null; - - sessions = server.getSessions(clusterId); - connections = server.getConnectionsShort(clusterId); - locks = server.getLocks(clusterId); - workingProcesses = server.getWorkingProcesses(clusterId); - workingServers = server.getWorkingServers(clusterId); - break; - - case WORKINGPROCESS: - - server = getCurrentServerConfig(treeItem); - clusterId = getCurrentClusterId(treeItem); - infobaseId = null; - workingProcessId = getCurrentWorkingProcessId(treeItem); - - sessions = server.getWorkingProcessSessions(clusterId, workingProcessId); - connections = server.getWorkingProcessConnectionsShort(clusterId, workingProcessId); - locks = new ArrayList<>(); -// locks = serverConfig.getInfoBaseLocks(clusterInfo.getClusterId(), infoBaseInfo.getInfoBaseId()); - - workingProcesses = new ArrayList<>(); - workingProcesses.add(server.getWorkingProcessInfo(clusterId, workingProcessId)); - workingServers = server.getWorkingServers(clusterId); - break; - - case INFOBASE: - server = getCurrentServerConfig(treeItem); - clusterId = getCurrentClusterId(treeItem); - infobaseId = getCurrentInfobaseId(treeItem); - - sessions = server.getInfoBaseSessions(clusterId, infobaseId); - connections = server.getInfoBaseConnectionsShort(clusterId, infobaseId); - locks = server.getInfoBaseLocks(clusterId, infobaseId); - - workingProcesses = server.getWorkingProcesses(clusterId); // TODO отметить рп обслуживающий базу - workingServers = server.getWorkingServers(clusterId); - break; - - default: - return; - } - - tabSessions.setText(String.format(Messages.getString("ViewerArea.SessionsCount"), sessions.size())); //$NON-NLS-1$ - tabConnections.setText(String.format(Messages.getString("ViewerArea.ConnectionsCount"), connections.size())); //$NON-NLS-1$ - tabLocks.setText(String.format(Messages.getString("ViewerArea.LocksCount"), locks.size())); //$NON-NLS-1$ - tabWorkingProcesses.setText(String.format(Messages.getString("ViewerArea.WorkingProcessesCount"), workingProcesses.size())); //$NON-NLS-1$ - tabWorkingServers.setText(String.format(Messages.getString("ViewerArea.WorkingServersCount"), workingServers.size())); //$NON-NLS-1$ - - if (currentTabitem.equals(tabSessions)) - sessions.forEach(session -> addSessionInTable(server, clusterId, infobaseId, session, connections)); - else if (currentTabitem.equals(tabConnections)) - connections.forEach(connection -> addConnectionInTable(server, clusterId, infobaseId, connection, workingProcesses)); - else if (currentTabitem.equals(tabLocks)) - locks.forEach(lock -> addLocksInTable(server, clusterId, infobaseId, lock, sessions, connections)); - else if (currentTabitem.equals(tabWorkingProcesses)) - workingProcesses.forEach(workingProcess -> addWorkingProcessInTable(server, clusterId, workingProcess)); - else if (currentTabitem.equals(tabWorkingServers)) - workingServers.forEach(workingServer -> addWorkingServerInTable(server, clusterId, workingServer)); - - } - - private void addMenuSeparator(Menu menu) { - new MenuItem(menu, SWT.SEPARATOR); - } - - private void highlightTreeItem(TreeItem treeItem) { - if (Objects.isNull(currentTreeItem) || !currentTreeItem.equals(treeItem)) { - - if (Objects.nonNull(currentTreeItem) && !currentTreeItem.isDisposed()) { - currentTreeItem.setFont(fontNormal); - } - treeItem.setFont(fontBold); - currentTreeItem = treeItem; - } - } - - private void setContestMenuInTree(TreeItem treeItem) { - - switch (getTreeItemType(treeItem)) { - case SERVER: - serversTree.setMenu(serverMenu); - return; - case CLUSTER: -// case WORKINGPROCESS_NODE: - serversTree.setMenu(clusterMenu); - break; - case INFOBASE_NODE: - serversTree.setMenu(infobaseNodeMenu); - break; - case INFOBASE: - serversTree.setMenu(infobaseMenu); - break; - case WORKINGPROCESS: - serversTree.setMenu(null); - break; - case WORKINGSERVER: - serversTree.setMenu(workingServerMenu); - break; - default: - serversTree.setMenu(null); - return; - } - } - - private void clearTabs() { - tabSessions.setText(Messages.getString("ViewerArea.Sessions")); //$NON-NLS-1$ - tabConnections.setText(Messages.getString("ViewerArea.Connections")); //$NON-NLS-1$ - tabLocks.setText(Messages.getString("ViewerArea.Locks")); //$NON-NLS-1$ - tabWorkingProcesses.setText(Messages.getString("ViewerArea.WorkingProcesses")); //$NON-NLS-1$ - tabWorkingServers.setText(Messages.getString("ViewerArea.WorkingServers")); //$NON-NLS-1$ - - tableSessions.removeAll(); - tableConnections.removeAll(); - tableLocks.removeAll(); - tableWorkingProcesses.removeAll(); - tableWorkingServers.removeAll(); - } - - private void clickItemInServerTree(int mouseButton) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) - return; - - TreeItem treeItem = item[0]; - - switch (mouseButton) { - case 1: // left click - fillTabs(treeItem); - break; - - case 3: // right click - setContestMenuInTree(treeItem); - break; - - default: - break; - } - } - - Listener columnMoveListener = new Listener() { - public void handleEvent(Event e) { - - TableColumn column = (TableColumn) e.widget; - Table currentTable = column.getParent(); - - if (currentTable.equals(tableSessions)) - ClusterProvider.getCommonConfig().setSessionsColumnOrder(tableSessions.getColumnOrder()); - else if (currentTable.equals(tableConnections)) - ClusterProvider.getCommonConfig().setConnectionsColumnOrder(tableConnections.getColumnOrder()); - else if (currentTable.equals(tableLocks)) - ClusterProvider.getCommonConfig().setLocksColumnOrder(tableLocks.getColumnOrder()); - else if (currentTable.equals(tableWorkingProcesses)) - ClusterProvider.getCommonConfig().setWorkingProcessesColumnOrder(tableWorkingProcesses.getColumnOrder()); - else if (currentTable.equals(tableWorkingServers)) - ClusterProvider.getCommonConfig().setWorkingServersColumnOrder(tableWorkingServers.getColumnOrder()); - -// clusterProvider.saveConfig(); - } - }; - - Listener columnResizeListener = new Listener() { - public void handleEvent(Event e) { - - TableColumn column = (TableColumn) e.widget; - int newWidth = column.getWidth(); - Table currentTable = column.getParent(); - TableColumn[] columns = currentTable.getColumns(); - - for (int i = 0; i < columns.length; i++) { - if (columns[i].getText().equals(column.getText())) { - if (currentTable.equals(tableSessions)) - ClusterProvider.getCommonConfig().setSessionsColumnWidth(i, newWidth); - else if (currentTable.equals(tableConnections)) - ClusterProvider.getCommonConfig().setConnectionsColumnWidth(i, newWidth); - else if (currentTable.equals(tableLocks)) - ClusterProvider.getCommonConfig().setLocksColumnWidth(i, newWidth); - else if (currentTable.equals(tableWorkingProcesses)) - ClusterProvider.getCommonConfig().setWorkingProcessesColumnWidth(i, newWidth); - else if (currentTable.equals(tableWorkingServers)) - ClusterProvider.getCommonConfig().setWorkingServersColumnWidth(i, newWidth); - break; - } - } -// clusterProvider.saveConfig(); - } - }; - -// ControlAdapter columnResizeListener = new ControlAdapter() { -// @Override -// public void controlResized(ControlEvent e) { -// TableColumn w = (TableColumn) e.widget; -// int width = w.getWidth(); -// TableColumn[] columns = w.getParent().getColumns(); -// -// for (int i = 0; i < columns.length; i++) { -// if (columns[i].getText().equals(w.getText())) { -// ClusterProvider.getCommonConfig().setSessionsColumnWidth(i, width); -// break; -// } -// } -//// clusterProvider.saveConfig(); -// } -// }; - - SelectionAdapter deleteItemListener = new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - deleteSelectSession(); - } - }; - - SelectionAdapter updateItemListener = new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - clickItemInServerTree(1); - } - }; - - SelectionAdapter editItemListener = new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - - Table currentTable = null; - - if (currentTabitem.equals(tabSessions)) - currentTable = tableSessions; - else if (currentTabitem.equals(tabConnections)) - currentTable = tableConnections; - else if (currentTabitem.equals(tabWorkingServers)) - currentTable = tableWorkingServers; - - if (currentTable == null) - return; - - TableItem[] item = currentTable.getSelection(); - if (item.length == 0) - return; - - if (currentTable.equals(tableSessions)) { - - Server server = (Server) item[0].getData(SERVER_INFO); - UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); - UUID sessionId = (UUID) item[0].getData(SESSION_ID); - ISessionInfo sessionInfo = (ISessionInfo) item[0].getData("sessionInfo"); - - SessionInfoDialog editClusterDialog; - try { - editClusterDialog = new SessionInfoDialog(getParent().getDisplay().getActiveShell(), server, clusterId, sessionId, sessionInfo); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error init SessionInfoDialog for session id {}", sessionId, excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - } - } else if (currentTable.equals(tableWorkingServers)) { - Server server = (Server) item[0].getData(SERVER_INFO); - UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); - UUID workingServerId = (UUID) item[0].getData(WORKINGSERVER_ID); - - CreateEditWorkingServerDialog editClusterDialog; - try { - editClusterDialog = new CreateEditWorkingServerDialog(getParent().getDisplay().getActiveShell(), server, clusterId, workingServerId); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error init WorkingServerDialog for cluster id {}", workingServerId, excp); //$NON-NLS-1$ - return; - } - - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - } - - } - - } - }; - - KeyAdapter keyListener = new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - - final int keyC = 99; - - switch (e.keyCode) { - case SWT.F2: - editItemListener.widgetSelected(null); - break; - - case SWT.F5: - clickItemInServerTree(1); - break; - - case SWT.DEL: -// deleteSelectSession(); - deleteItemListener.widgetSelected(null); - break; - - case keyC: -// if (e.stateMask == SWT.CTRL) { -// TableItem[] selection = tableSessions.getSelection(); -// -// if (selection.length > 0) { -// Clipboard clipboard = new Clipboard(Display.getDefault()); -// clipboard.setContents(new Object[] { selection[0].getText() }, new Transfer[] { TextTransfer.getInstance() }); -// clipboard.dispose(); -// } -// } - break; - - default: - break; - } - } - }; - - - + + MenuItem menuItemEditWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); + menuItemEditWorkingServer.setText( + Messages.getString("ViewerArea.EditWorkingServer").concat("\tF2")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemEditWorkingServer.setImage(editIcon); + menuItemEditWorkingServer.addSelectionListener(editItemListener); + + MenuItem menuItemDeleteWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); + menuItemDeleteWorkingServer.setText( + Messages.getString("ViewerArea.DeleteWorkingServer").concat("\tDEL")); //$NON-NLS-1$ //$NON-NLS-2$ + menuItemDeleteWorkingServer.setImage(deleteIcon); + menuItemDeleteWorkingServer.addSelectionListener(deleteItemListener); + } + + private void fillServersList() { + // TODO Auto-generated method stub + } + + private void updateClustersInTree(TreeItem serverItem) { + + Server server = getCurrentServerConfig(serverItem); + TreeItem[] clustersItems = serverItem.getItems(); + + // у отключенного сервера удаляем все дочерние элементы + if (!server.isConnected()) { + for (TreeItem clusterItem : clustersItems) { + disposeTreeItemWithChildren(clusterItem); + } + return; + } + + List clusters = server.getClusters(); + + // удаление несуществующих элементов + for (TreeItem clusterItem : clustersItems) { + UUID currentClusterId = getCurrentClusterId(clusterItem); + List foundCluster = + clusters.stream() + .filter(c -> c.getClusterId().equals(currentClusterId)) + .collect(Collectors.toList()); + + if (foundCluster.isEmpty()) { + disposeTreeItemWithChildren(clusterItem); + } + } + + // добавление новых элементов + clusters.forEach( + clusterInfo -> { + var itemFound = false; + TreeItem currentClusterItem = null; + for (TreeItem clusterItem : serverItem.getItems()) { + if (getCurrentClusterId(clusterItem).equals(clusterInfo.getClusterId())) { + currentClusterItem = clusterItem; + itemFound = true; + break; + } + } + + if (!itemFound) { + currentClusterItem = addClusterItemInServersTree(serverItem, clusterInfo); + } + + // Заполнение дерева кластера + if (currentClusterItem != null) { + fillChildrenItemsOfCluster(currentClusterItem, server); + } + }); + + // Разворачиваем дерево, если включена настройка + serverItem.setExpanded(ClusterProvider.getCommonConfig().isExpandServersTree()); + } + + private void fillChildrenItemsOfCluster(TreeItem clusterItem, Server server) { + + fillInfobasesOfCluster(clusterItem, server); + fillWorkingProcessesInCluster(clusterItem, server); + fillWorkingServersInCluster(clusterItem, server); + + clusterItem.setExpanded(ClusterProvider.getCommonConfig().isExpandClustersTree()); + } + + private void fillInfobasesOfCluster(TreeItem clusterItem, Server server) { + + TreeItem infobasesNode = null; + for (TreeItem treeItem : clusterItem.getItems()) { + if (treeItem.getData("Type") == TreeItemType.INFOBASE_NODE) { //$NON-NLS-1$ + infobasesNode = treeItem; + break; + } + } + + if (infobasesNode == null) { + infobasesNode = new TreeItem(clusterItem, SWT.NONE); + infobasesNode.setData("Type", TreeItemType.INFOBASE_NODE); //$NON-NLS-1$ + infobasesNode.setImage(infobasesIcon); + infobasesNode.setChecked(false); + } + + UUID clusterId = getCurrentClusterId(infobasesNode); + List infoBases = server.getInfoBasesShort(clusterId); + + var infobasesNodeTitle = + String.format( + Messages.getString("ViewerArea.InfobasesCount"), infoBases.size()); //$NON-NLS-1$ + infobasesNode.setText(new String[] {infobasesNodeTitle}); + + if (infoBases.isEmpty()) { + for (TreeItem infobase : infobasesNode.getItems()) { + infobase.dispose(); + } + return; + } + + // удаление несуществующих элементов + for (TreeItem infobaseItem : infobasesNode.getItems()) { + UUID currentInfobaseId = getCurrentInfobaseId(infobaseItem); + List foundItems = + infoBases.stream() + .filter(c -> c.getInfoBaseId().equals(currentInfobaseId)) + .collect(Collectors.toList()); + + if (foundItems.isEmpty()) { + infobaseItem.dispose(); + } + } + + // добавление новых элементов + for (IInfoBaseInfoShort infoBaseInfo : infoBases) { + // infoBases.forEach(infoBaseInfo -> { + + var itemFound = false; + for (TreeItem infobaseItem : infobasesNode.getItems()) { + if (getCurrentInfobaseId(infobaseItem).equals(infoBaseInfo.getInfoBaseId())) { + itemFound = true; + break; + } + } + + if (!itemFound) { + addInfobaseItemInInfobaseNode(infobasesNode, infoBaseInfo); + } + } + + infobasesNode.setExpanded(ClusterProvider.getCommonConfig().isExpandInfobasesTree()); + } + + private void fillWorkingProcessesInCluster(TreeItem clusterItem, Server server) { + + TreeItem workingProcessesNode = null; + for (TreeItem treeItem : clusterItem.getItems()) { + if (treeItem.getData("Type") == TreeItemType.WORKINGPROCESS_NODE) { //$NON-NLS-1$ + workingProcessesNode = treeItem; + break; + } + } + + if (!ClusterProvider.getCommonConfig().isShowWorkingProcessesTree()) { + if (workingProcessesNode != null) { + workingProcessesNode.dispose(); + } + return; + } + + if (workingProcessesNode == null) { + workingProcessesNode = new TreeItem(clusterItem, SWT.NONE); + workingProcessesNode.setData("Type", TreeItemType.WORKINGPROCESS_NODE); //$NON-NLS-1$ + workingProcessesNode.setImage(workingProcessesIcon); + workingProcessesNode.setChecked(false); + } + + UUID clusterId = getCurrentClusterId(workingProcessesNode); + List workingProcesses = server.getWorkingProcesses(clusterId); + + var workingProcessesNodeTitle = + String.format( + Messages.getString("ViewerArea.WorkingProcessesCount"), //$NON-NLS-1$ + workingProcesses.size()); + workingProcessesNode.setText(new String[] {workingProcessesNodeTitle}); + + if (workingProcesses.isEmpty()) { + for (TreeItem workingProcess : workingProcessesNode.getItems()) { + workingProcess.dispose(); + } + return; + } + + // удаление несуществующих элементов + for (TreeItem workingProcessItem : workingProcessesNode.getItems()) { + UUID currentWorkingProcessId = getCurrentWorkingProcessId(workingProcessItem); + List foundItems = + workingProcesses.stream() + .filter(c -> c.getWorkingProcessId().equals(currentWorkingProcessId)) + .collect(Collectors.toList()); + + if (foundItems.isEmpty()) { + workingProcessItem.dispose(); + } + } + + // добавление новых элементов + for (IWorkingProcessInfo workingProcessInfo : workingProcesses) { + // wProcesses.forEach(workingProcessInfo -> { + + var itemFound = false; + for (TreeItem workingProcessItem : workingProcessesNode.getItems()) { + if (getCurrentWorkingProcessId(workingProcessItem) + .equals(workingProcessInfo.getWorkingProcessId())) { + itemFound = true; + break; + } + } + + if (!itemFound) { + addWorkingProcessItemInNode(workingProcessesNode, workingProcessInfo); + } + } + } + + private void fillWorkingServersInCluster(TreeItem clusterItem, Server server) { + + TreeItem workingServersNode = null; + for (TreeItem treeItem : clusterItem.getItems()) { + if (treeItem.getData("Type") == TreeItemType.WORKINGSERVER_NODE) { //$NON-NLS-1$ + workingServersNode = treeItem; + break; + } + } + + if (!ClusterProvider.getCommonConfig().isShowWorkingServersTree()) { + if (workingServersNode != null) { + workingServersNode.dispose(); + } + return; + } + + if (workingServersNode == null) { + workingServersNode = new TreeItem(clusterItem, SWT.NONE); + workingServersNode.setData("Type", TreeItemType.WORKINGSERVER_NODE); //$NON-NLS-1$ + workingServersNode.setImage(workingServerIcon); + workingServersNode.setChecked(false); + } + + UUID clusterId = getCurrentClusterId(workingServersNode); + List workingServers = server.getWorkingServers(clusterId); + + var workingServerNodeTitle = + String.format( + Messages.getString("ViewerArea.WorkingServersCount"), //$NON-NLS-1$ + workingServers.size()); + workingServersNode.setText(new String[] {workingServerNodeTitle}); + + if (workingServers.isEmpty()) { + for (TreeItem workingServerItem : workingServersNode.getItems()) { + workingServerItem.dispose(); + } + return; + } + + // удаление несуществующих элементов + for (TreeItem workingServerItem : workingServersNode.getItems()) { + UUID currentWorkingServerId = getCurrentWorkingServerId(workingServerItem); + List foundItems = + workingServers.stream() + .filter(c -> c.getWorkingServerId().equals(currentWorkingServerId)) + .collect(Collectors.toList()); + + if (foundItems.isEmpty()) { + workingServerItem.dispose(); + } + } + + // добавление новых элементов + for (IWorkingServerInfo workingServerInfo : workingServers) { + // wServers.forEach(workingServerInfo -> { + + var itemFound = false; + for (TreeItem workingServerItem : workingServersNode.getItems()) { + if (getCurrentWorkingServerId(workingServerItem) + .equals(workingServerInfo.getWorkingServerId())) { + itemFound = true; + break; + } + } + + if (!itemFound) { + addWorkingServerItemInNode(workingServersNode, workingServerInfo); + } + } + } + + private TreeItem addServerItemInServersTree(Server server) { + + var item = new TreeItem(serversTree, SWT.NONE); + item.setText(new String[] {server.getTreeDescription()}); + item.setData("Type", TreeItemType.SERVER); //$NON-NLS-1$ + item.setData(SERVER_INFO, server); + + item.setImage(server.isConnected() ? serverIconUp : serverIcon); + + return item; + } + + private TreeItem addClusterItemInServersTree(TreeItem serverItem, IClusterInfo clusterInfo) { + + var clusterTitle = + String.format("%s (%s)", clusterInfo.getName(), clusterInfo.getMainPort()); //$NON-NLS-1$ + + var clusterItem = new TreeItem(serverItem, SWT.NONE); + clusterItem.setText(new String[] {clusterTitle}); + clusterItem.setData("Type", TreeItemType.CLUSTER); //$NON-NLS-1$ + clusterItem.setData(CLUSTER_ID, clusterInfo.getClusterId()); + clusterItem.setImage(clusterIcon); + + return clusterItem; + } + + private void addInfobaseItemInInfobaseNode(TreeItem infobaseNode, IInfoBaseInfoShort ibInfo) { + + String infobaseTitle; + if (ClusterProvider.getCommonConfig().isShowInfobaseDescription() && !ibInfo.getDescr().isBlank()) { + infobaseTitle = String.format("%s (%s)", ibInfo.getName(), ibInfo.getDescr()); //$NON-NLS-1$ + } else { + infobaseTitle = String.format("%s", ibInfo.getName()); //$NON-NLS-1$ + } + + var item = new TreeItem(infobaseNode, SWT.NONE); + item.setText(new String[] {infobaseTitle}); + item.setData("Type", TreeItemType.INFOBASE); //$NON-NLS-1$ + item.setData(INFOBASE_ID, ibInfo.getInfoBaseId()); + item.setImage(0, infobaseIcon); + item.setChecked(false); + + // item.setImage(1, ibInfo.isSessionsDenied() ? lockUsersIcon : null); + + } + + private void addWorkingProcessItemInNode(TreeItem wpNodeItem, IWorkingProcessInfo wpInfo) { + + var itemTitle = + String.format("%s (%s)", wpInfo.getHostName(), wpInfo.getMainPort()); //$NON-NLS-1$ + + var item = new TreeItem(wpNodeItem, SWT.NONE); + item.setText(new String[] {itemTitle}); + item.setData("Type", TreeItemType.WORKINGPROCESS); //$NON-NLS-1$ + item.setData(WORKINGPROCESS_ID, wpInfo.getWorkingProcessId()); + item.setImage(workingProcessIcon); + item.setChecked(false); + } + + private void addWorkingServerItemInNode(TreeItem wsNodeItem, IWorkingServerInfo wpInfo) { + + var itemTitle = + String.format("%s (%s)", wpInfo.getHostName(), wpInfo.getMainPort()); //$NON-NLS-1$ + + var item = new TreeItem(wsNodeItem, SWT.NONE); + item.setText(new String[] {itemTitle}); + item.setData("Type", TreeItemType.WORKINGSERVER); //$NON-NLS-1$ + item.setData(WORKINGSERVER_ID, wpInfo.getWorkingServerId()); + item.setImage(workingServerIcon); + item.setChecked(false); + } + + private void addSessionInTable( + Server server, + UUID clusterId, + UUID infobaseId, + ISessionInfo sessionInfo, + List connections) { + + SessionInfoExtended sessionInfoExtended = + new SessionInfoExtended( + server, clusterId, infobaseId, sessionInfo, connections, sessionColumnsMap); + + var sessionItem = new TableItem(tableSessions, SWT.NONE); + sessionItem.setText(sessionInfoExtended.getExtendedInfo()); + sessionItem.setData(SERVER_INFO, server); + sessionItem.setData(CLUSTER_ID, clusterId); + sessionItem.setData(SESSION_ID, sessionInfo.getSid()); // sessionInfo.getSessionId() ??? + // agentConnection.getSessionInfo(clusterId, sid); ошибка... + sessionItem.setData("sessionInfo", sessionInfo); //$NON-NLS-1$ + sessionItem.setImage(userIcon); + sessionItem.setChecked(false); + + if (IInfoExtended.highlightItem(sessionInfo.getStartedAt())) { + sessionItem.setForeground(newItemColor); + } + + Config commonConfig = ClusterProvider.getCommonConfig(); + if (commonConfig.isShadowSleepSessions() && sessionInfo.getHibernate()) { + sessionItem.setForeground(shadowItemColor); + } + + String id = sessionItem.getText(1).concat("*").concat(sessionItem.getText(2)); //$NON-NLS-1$ + if (watchedSessions.contains(id)) { + sessionItem.setChecked(true); + sessionItem.setForeground(watchedSessionColor); + } + + switch (sessionInfo.getAppId()) { + case Server.THIN_CLIENT: + case Server.THICK_CLIENT: + case Server.DESIGNER: + sessionItem.setImage(sessionInfo.getHibernate() ? sleepUserIcon : userIcon); + break; + case Server.SERVER_CONSOLE: + case Server.RAS_CONSOLE: + case Server.JOBSCHEDULER: + sessionItem.setImage(serviceIcon); + break; + default: + sessionItem.setImage(sessionInfo.getHibernate() ? sleepUserIcon : userIcon); + } + } + + private void addConnectionInTable( + Server server, + UUID clusterId, + UUID infobaseId, + IInfoBaseConnectionShort connectionInfo, + List workingProcesses) { + + ConnectionInfoExtended sessionInfoExtended = + new ConnectionInfoExtended( + server, clusterId, infobaseId, connectionInfo, workingProcesses, connectionColumnsMap); + + var connectionItem = new TableItem(tableConnections, SWT.NONE); + connectionItem.setText(sessionInfoExtended.getExtendedInfo()); + connectionItem.setData(SERVER_INFO, server); + connectionItem.setData(CLUSTER_ID, clusterId); + connectionItem.setData(WORKINGPROCESS_ID, connectionInfo.getWorkingProcessId()); + connectionItem.setData(INFOBASE_ID, connectionInfo.getInfoBaseId()); + connectionItem.setData(CONNECTION_ID, connectionInfo.getInfoBaseConnectionId()); + connectionItem.setImage(connectionIcon); + connectionItem.setChecked(false); + + if (IInfoExtended.highlightItem(connectionInfo.getConnectedAt())) { + connectionItem.setForeground(newItemColor); + } + } + + private void addLocksInTable( + Server server, + UUID clusterId, + UUID infobaseId, + IObjectLockInfo lockInfo, + List sessionsInfo, + List connections) { + + LockInfoExtended lockInfoExtended = + new LockInfoExtended( + server, clusterId, infobaseId, lockInfo, sessionsInfo, connections, lockColumnsMap); + + var lockItem = new TableItem(tableLocks, SWT.NONE); + lockItem.setText(lockInfoExtended.getExtendedInfo()); + lockItem.setData(CLUSTER_ID, clusterId); + lockItem.setData(INFOBASE_ID, infobaseId); + lockItem.setData("IObjectLockInfo", lockInfo); //$NON-NLS-1$ + lockItem.setImage(locksIcon); + lockItem.setChecked(false); + + if (IInfoExtended.highlightItem(lockInfo.getLockedAt())) { + lockItem.setForeground(newItemColor); + } + } + + private void addWorkingProcessInTable( + Server server, UUID clusterId, IWorkingProcessInfo workingProcessInfo) { + + WorkingProcessInfoExtended wpInfoExtended = + new WorkingProcessInfoExtended(server, clusterId, workingProcessInfo, wpColumnsMap); + + var wpItem = new TableItem(tableWorkingProcesses, SWT.NONE); + wpItem.setText(wpInfoExtended.getExtendedInfo()); + wpItem.setData(SERVER_INFO, server); + wpItem.setData(CLUSTER_ID, clusterId); + wpItem.setData(WORKINGPROCESS_ID, workingProcessInfo.getWorkingProcessId()); + wpItem.setImage(workingProcessIcon); + wpItem.setChecked(false); + + if (IInfoExtended.highlightItem(workingProcessInfo.getStartedAt())) { + wpItem.setForeground(newItemColor); + } + } + + private void addWorkingServerInTable( + Server server, UUID clusterId, IWorkingServerInfo workingServerInfo) { + + WorkingServerInfoExtended wsInfoExtended = + new WorkingServerInfoExtended(server, clusterId, workingServerInfo, wsColumnsMap); + + var connectionItem = new TableItem(tableWorkingServers, SWT.NONE); + connectionItem.setText(wsInfoExtended.getExtendedInfo()); + connectionItem.setData(SERVER_INFO, server); + connectionItem.setData(CLUSTER_ID, clusterId); + connectionItem.setData(WORKINGSERVER_ID, workingServerInfo.getWorkingServerId()); + connectionItem.setImage(workingServerIcon); + connectionItem.setChecked(false); + } + + private void addTableColumn( + Table table, String text, int[] columnWidth, boolean[] columnVisible) { // TODO properties + var newColumn = new TableColumn(table, SWT.NONE); + newColumn.setText(text); + newColumn.setMoveable(true); + newColumn.setAlignment(SWT.RIGHT); + + int numOfColumn = table.getColumnCount() - 1; + + if (columnVisible != null && columnVisible[numOfColumn]) { + newColumn.setResizable(true); + newColumn.setWidth( + // columnWidth == null //TODO нужно ли это еще + // || columnWidth.length <= table.getColumnCount() + // || + columnWidth[numOfColumn] == 0 ? 100 : columnWidth[numOfColumn]); + } else { + newColumn.setResizable(false); + newColumn.setWidth(0); + } + + newColumn.addListener(SWT.Move, columnMoveListener); + newColumn.addListener(SWT.Resize, columnResizeListener); + // newColumn.addControlListener(columnResizeListener); + + } + + private TreeItemType getTreeItemType(TreeItem item) { + return (TreeItemType) item.getData("Type"); //$NON-NLS-1$ + } + + private Server getCurrentServerConfig(TreeItem item) { + + if (getTreeItemType(item) == TreeItemType.SERVER) { + return (Server) item.getData(SERVER_INFO); + } + + TreeItem parentItem = item.getParentItem(); + while (parentItem != null) { + + if (getTreeItemType(parentItem) == TreeItemType.SERVER) { + return (Server) parentItem.getData(SERVER_INFO); + } else { + parentItem = parentItem.getParentItem(); + } + } + throw new IllegalStateException("Error get ServerConfig from item."); //$NON-NLS-1$ + // return null; + } + + private UUID getCurrentClusterId(TreeItem item) { + + if (getTreeItemType(item) == TreeItemType.CLUSTER) { + return (UUID) item.getData(CLUSTER_ID); + } + + TreeItem parentItem = item.getParentItem(); + while (parentItem != null) { + + if (getTreeItemType(parentItem) == TreeItemType.CLUSTER) { + return (UUID) parentItem.getData(CLUSTER_ID); + } else { + parentItem = parentItem.getParentItem(); + } + } + return null; + } + + private UUID getCurrentWorkingProcessId(TreeItem item) { + + if (getTreeItemType(item) == TreeItemType.WORKINGPROCESS) { + return (UUID) item.getData(WORKINGPROCESS_ID); + } + + TreeItem parentItem = item.getParentItem(); + while (parentItem != null) { + + if (getTreeItemType(parentItem) == TreeItemType.WORKINGPROCESS) { + return (UUID) parentItem.getData(WORKINGPROCESS_ID); + } else { + parentItem = parentItem.getParentItem(); + } + } + return null; + } + + private UUID getCurrentWorkingServerId(TreeItem item) { + + if (getTreeItemType(item) == TreeItemType.WORKINGSERVER) { + return (UUID) item.getData(WORKINGSERVER_ID); + } + + TreeItem parentItem = item.getParentItem(); + while (parentItem != null) { + + if (getTreeItemType(parentItem) == TreeItemType.WORKINGSERVER) { + return (UUID) parentItem.getData(WORKINGSERVER_ID); + } else { + parentItem = parentItem.getParentItem(); + } + } + return null; + } + + private UUID getCurrentInfobaseId(TreeItem item) { + if (getTreeItemType(item) == TreeItemType.INFOBASE) { + return (UUID) item.getData(INFOBASE_ID); + } else { + return null; + } + } + + private void disposeTreeItemWithChildren(TreeItem item) { + TreeItem[] childItems = item.getItems(); + for (TreeItem childItem : childItems) { + disposeTreeItemWithChildren(childItem); + childItem.dispose(); + } + item.dispose(); + } + + private Image getImage(String name) { + return new Image( + getParent().getDisplay(), + this.getClass().getResourceAsStream("/icons/".concat(name))); //$NON-NLS-1$ + } + + private void connectToAllServers(boolean connectAll) { + + TreeItem[] serversItem = serversTree.getItems(); + + for (TreeItem serverItem : serversItem) { + Server server = getCurrentServerConfig(serverItem); + if ((connectAll || server.getAutoconnect()) && !server.isConnected()) { + connectServerItem(serverItem, true); + } + } + } + + private void diconnectFromAllServers() { + + TreeItem[] serversItem = serversTree.getItems(); + + for (TreeItem serverItem : serversItem) { + disconnectServerItem(serverItem); + } + } + + private void connectServerItem(TreeItem serverItem, boolean silentMode) { + + // async не работает асинхронно + serverItem.setImage(serverIconConnecting); + Display.getDefault() + .asyncExec( + new Runnable() { + + @Override + public void run() { + + Server server = getCurrentServerConfig(serverItem); + server.connectToServer(false, silentMode); + + serverItem.setImage(server.isConnected() ? serverIconUp : serverIconDown); + serverItem.setText(new String[] {server.getTreeDescription()}); + updateClustersInTree(serverItem); + } + }); + } + + private void disconnectServerItem(TreeItem serverItem) { + Server server = getCurrentServerConfig(serverItem); + server.disconnectFromAgent(); + serverItem.setImage(serverIconDown); + + TreeItem[] clusterItems = serverItem.getItems(); + for (TreeItem clusterItem : clusterItems) { + disposeTreeItemWithChildren(clusterItem); + } + } + + private void fillTabs(TreeItem treeItem) { + + highlightTreeItem(treeItem); + + Server server; + UUID clusterId; + UUID infobaseId; + UUID workingProcessId; + + List sessions; + List connections; + List locks; + List workingProcesses; + List workingServers; + + clearTabs(); + switch (getTreeItemType(treeItem)) { + case SERVER: + return; + + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + server = getCurrentServerConfig(treeItem); + clusterId = getCurrentClusterId(treeItem); + infobaseId = null; + + sessions = server.getSessions(clusterId); + connections = server.getConnectionsShort(clusterId); + locks = server.getLocks(clusterId); + workingProcesses = server.getWorkingProcesses(clusterId); + workingServers = server.getWorkingServers(clusterId); + break; + + case WORKINGPROCESS: + server = getCurrentServerConfig(treeItem); + clusterId = getCurrentClusterId(treeItem); + infobaseId = null; + workingProcessId = getCurrentWorkingProcessId(treeItem); + + sessions = server.getWorkingProcessSessions(clusterId, workingProcessId); + connections = server.getWorkingProcessConnectionsShort(clusterId, workingProcessId); + locks = new ArrayList<>(); + // locks = serverConfig.getInfoBaseLocks(clusterInfo.getClusterId(), + // infoBaseInfo.getInfoBaseId()); + + workingProcesses = new ArrayList<>(); + workingProcesses.add(server.getWorkingProcessInfo(clusterId, workingProcessId)); + workingServers = server.getWorkingServers(clusterId); + break; + + case INFOBASE: + server = getCurrentServerConfig(treeItem); + clusterId = getCurrentClusterId(treeItem); + infobaseId = getCurrentInfobaseId(treeItem); + + sessions = server.getInfoBaseSessions(clusterId, infobaseId); + connections = server.getInfoBaseConnectionsShort(clusterId, infobaseId); + locks = server.getInfoBaseLocks(clusterId, infobaseId); + + // TODO отметить рп обслуживающий базу + workingProcesses = server.getWorkingProcesses(clusterId); + workingServers = server.getWorkingServers(clusterId); + break; + + default: + return; + } + + tabSessions.setText( + String.format( + Messages.getString("ViewerArea.SessionsCount"), //$NON-NLS-1$ + sessions.size())); + tabConnections.setText( + String.format( + Messages.getString("ViewerArea.ConnectionsCount"), //$NON-NLS-1$ + connections.size())); + tabLocks.setText( + String.format( + Messages.getString("ViewerArea.LocksCount"), //$NON-NLS-1$ + locks.size())); + tabWorkingProcesses.setText( + String.format( + Messages.getString("ViewerArea.WorkingProcessesCount"), //$NON-NLS-1$ + workingProcesses.size())); + tabWorkingServers.setText( + String.format( + Messages.getString("ViewerArea.WorkingServersCount"), //$NON-NLS-1$ + workingServers.size())); + + if (currentTabitem.equals(tabSessions)) { + sessions.forEach( + session -> addSessionInTable(server, clusterId, infobaseId, session, connections)); + } else if (currentTabitem.equals(tabConnections)) { + connections.forEach( + connection -> + addConnectionInTable(server, clusterId, infobaseId, connection, workingProcesses)); + } else if (currentTabitem.equals(tabLocks)) { + locks.forEach( + lock -> addLocksInTable(server, clusterId, infobaseId, lock, sessions, connections)); + } else if (currentTabitem.equals(tabWorkingProcesses)) { + workingProcesses.forEach( + workingProcess -> addWorkingProcessInTable(server, clusterId, workingProcess)); + } else if (currentTabitem.equals(tabWorkingServers)) { + workingServers.forEach( + workingServer -> addWorkingServerInTable(server, clusterId, workingServer)); + } + } + + private void addMenuSeparator(Menu menu) { + new MenuItem(menu, SWT.SEPARATOR); + } + + private void highlightTreeItem(TreeItem treeItem) { + if (Objects.isNull(currentTreeItem) || !currentTreeItem.equals(treeItem)) { + + if (Objects.nonNull(currentTreeItem) && !currentTreeItem.isDisposed()) { + currentTreeItem.setFont(fontNormal); + } + treeItem.setFont(fontBold); + currentTreeItem = treeItem; + } + } + + private void setContestMenuInTree(TreeItem treeItem) { + + switch (getTreeItemType(treeItem)) { + case SERVER: + serversTree.setMenu(serverMenu); + return; + case CLUSTER: + // case WORKINGPROCESS_NODE: + serversTree.setMenu(clusterMenu); + break; + case INFOBASE_NODE: + serversTree.setMenu(infobaseNodeMenu); + break; + case INFOBASE: + serversTree.setMenu(infobaseMenu); + break; + case WORKINGPROCESS: + serversTree.setMenu(null); + break; + case WORKINGSERVER: + serversTree.setMenu(workingServerMenu); + break; + default: + serversTree.setMenu(null); + return; + } + } + + private void clearTabs() { + tabSessions.setText(Messages.getString("ViewerArea.Sessions")); //$NON-NLS-1$ + tabConnections.setText(Messages.getString("ViewerArea.Connections")); //$NON-NLS-1$ + tabLocks.setText(Messages.getString("ViewerArea.Locks")); //$NON-NLS-1$ + tabWorkingProcesses.setText(Messages.getString("ViewerArea.WorkingProcesses")); //$NON-NLS-1$ + tabWorkingServers.setText(Messages.getString("ViewerArea.WorkingServers")); //$NON-NLS-1$ + + tableSessions.removeAll(); + tableConnections.removeAll(); + tableLocks.removeAll(); + tableWorkingProcesses.removeAll(); + tableWorkingServers.removeAll(); + } + + private void clickItemInServerTree(int mouseButton) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + TreeItem treeItem = item[0]; + + switch (mouseButton) { + case 1: // left click + fillTabs(treeItem); + break; + + case 3: // right click + setContestMenuInTree(treeItem); + break; + + default: + break; + } + } + + Listener columnMoveListener = + new Listener() { + @Override + public void handleEvent(Event e) { + + TableColumn column = (TableColumn) e.widget; + Table currentTable = column.getParent(); + Config commonConfig = ClusterProvider.getCommonConfig(); + + if (currentTable.equals(tableSessions)) { + commonConfig.setSessionsColumnOrder(tableSessions.getColumnOrder()); + } else if (currentTable.equals(tableConnections)) { + commonConfig.setConnectionsColumnOrder(tableConnections.getColumnOrder()); + } else if (currentTable.equals(tableLocks)) { + commonConfig.setLocksColumnOrder(tableLocks.getColumnOrder()); + } else if (currentTable.equals(tableWorkingProcesses)) { + commonConfig.setWorkingProcessesColumnOrder(tableWorkingProcesses.getColumnOrder()); + } else if (currentTable.equals(tableWorkingServers)) { + commonConfig.setWorkingServersColumnOrder(tableWorkingServers.getColumnOrder()); + } + + // clusterProvider.saveConfig(); + } + }; + + Listener columnResizeListener = + new Listener() { + @Override + public void handleEvent(Event e) { + + TableColumn column = (TableColumn) e.widget; + int newWidth = column.getWidth(); + Table currentTable = column.getParent(); + TableColumn[] columns = currentTable.getColumns(); + Config commonConfig = ClusterProvider.getCommonConfig(); + + for (int i = 0; i < columns.length; i++) { + if (columns[i].getText().equals(column.getText())) { + if (currentTable.equals(tableSessions)) { + commonConfig.setSessionsColumnWidth(i, newWidth); + } else if (currentTable.equals(tableConnections)) { + commonConfig.setConnectionsColumnWidth(i, newWidth); + } else if (currentTable.equals(tableLocks)) { + commonConfig.setLocksColumnWidth(i, newWidth); + } else if (currentTable.equals(tableWorkingProcesses)) { + commonConfig.setWorkingProcessesColumnWidth(i, newWidth); + } else if (currentTable.equals(tableWorkingServers)) { + commonConfig.setWorkingServersColumnWidth(i, newWidth); + } + break; + } + } + // clusterProvider.saveConfig(); + } + }; + + // ControlAdapter columnResizeListener = + // new ControlAdapter() { + // @Override + // public void controlResized(ControlEvent e) { + // TableColumn w = (TableColumn) e.widget; + // int width = w.getWidth(); + // TableColumn[] columns = w.getParent().getColumns(); + // + // for (int i = 0; i < columns.length; i++) { + // if (columns[i].getText().equals(w.getText())) { + // ClusterProvider.getCommonConfig().setSessionsColumnWidth(i, width); + // break; + // } + // } + // // clusterProvider.saveConfig(); + // } + // }; + + SelectionAdapter deleteItemListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + deleteSelectSession(); + } + }; + + SelectionAdapter updateItemListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + clickItemInServerTree(1); + } + }; + + SelectionAdapter editItemListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + Table currentTable = null; + + if (currentTabitem.equals(tabSessions)) { + currentTable = tableSessions; + } else if (currentTabitem.equals(tabConnections)) { + currentTable = tableConnections; + } else if (currentTabitem.equals(tabWorkingServers)) { + currentTable = tableWorkingServers; + } + + if (currentTable == null) { + return; + } + + TableItem[] item = currentTable.getSelection(); + if (item.length == 0) { + return; + } + + if (currentTable.equals(tableSessions)) { + + Server server = (Server) item[0].getData(SERVER_INFO); + UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); + UUID sessionId = (UUID) item[0].getData(SESSION_ID); + ISessionInfo sessionInfo = (ISessionInfo) item[0].getData("sessionInfo"); //$NON-NLS-1$ + + SessionInfoDialog editClusterDialog; + try { + editClusterDialog = + new SessionInfoDialog( + getParent().getDisplay().getActiveShell(), + server, + clusterId, + sessionId, + sessionInfo); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error( + "Error init SessionInfoDialog for session id {}", //$NON-NLS-1$ + sessionId, + excp); + return; + } + + editClusterDialog.open(); + + } else if (currentTable.equals(tableWorkingServers)) { + Server server = (Server) item[0].getData(SERVER_INFO); + UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); + UUID workingServerId = (UUID) item[0].getData(WORKINGSERVER_ID); + + CreateEditWorkingServerDialog editClusterDialog; + try { + editClusterDialog = + new CreateEditWorkingServerDialog( + getParent().getDisplay().getActiveShell(), + server, + clusterId, + workingServerId); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + workingServerId, + excp); + return; + } + + int dialogResult = editClusterDialog.open(); + if (dialogResult == 0) { + clickItemInServerTree(0); + } + } + } + }; + + KeyAdapter keyListener = + new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + + final int keyC = 99; + + switch (e.keyCode) { + case SWT.F2: + editItemListener.widgetSelected(null); + break; + + case SWT.F5: + clickItemInServerTree(1); + break; + + case SWT.DEL: + // deleteSelectSession(); + deleteItemListener.widgetSelected(null); + break; + + case keyC: + // if (e.stateMask == SWT.CTRL) { + // TableItem[] selection = tableSessions.getSelection(); + // + // if (selection.length > 0) { + // Clipboard clipboard = new Clipboard(Display.getDefault()); + // clipboard.setContents(new Object[] { selection[0].getText() }, new + // Transfer[] { TextTransfer.getInstance() }); + // clipboard.dispose(); + // } + // } + break; + + default: + break; + } + } + }; } diff --git a/clusterAdminLibrary/src/main/resources/logback.xml b/clusterAdminLibrary/src/main/resources/logback.xml index e10e12e..e9aa088 100644 --- a/clusterAdminLibrary/src/main/resources/logback.xml +++ b/clusterAdminLibrary/src/main/resources/logback.xml @@ -28,8 +28,8 @@ - - + + From d8002381440f6e0ff3401cf9a3d00b323ad7d100 Mon Sep 17 00:00:00 2001 From: YanSergey Date: Mon, 25 Oct 2021 21:16:49 +0300 Subject: [PATCH 3/6] =?UTF-8?q?=D0=9F=D0=BE=D0=B2=D1=8B=D1=88=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D0=B8=20=D0=B4?= =?UTF-8?q?=D0=BE=200.3.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- clusterAdminApplication/pom.xml | 4 ++-- clusterAdminLibrary/pom.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clusterAdminApplication/pom.xml b/clusterAdminApplication/pom.xml index d71ace0..288dcd5 100644 --- a/clusterAdminApplication/pom.xml +++ b/clusterAdminApplication/pom.xml @@ -6,7 +6,7 @@ ru.yanygin ru.yanygin.clusterAdminApplication - 0.2.0 + 0.3.0 jar @@ -88,7 +88,7 @@ ru.yanygin ${clusterAdminLibrary.artifactId} - 0.2.0-SNAPSHOT + ${project.version}-SNAPSHOT diff --git a/clusterAdminLibrary/pom.xml b/clusterAdminLibrary/pom.xml index adf114b..215a2ea 100644 --- a/clusterAdminLibrary/pom.xml +++ b/clusterAdminLibrary/pom.xml @@ -6,7 +6,7 @@ ru.yanygin ${artifactId} - 0.2.0-SNAPSHOT + 0.3.0-SNAPSHOT jar From 7a7df81f6eba3968b51e058a0157154ff38ede51 Mon Sep 17 00:00:00 2001 From: YanSergey Date: Mon, 25 Oct 2021 21:18:44 +0300 Subject: [PATCH 4/6] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BA=D0=BE=D0=BD=D0=BA=D0=B8?= =?UTF-8?q?=20=D0=BE=D1=82=D0=BA=D0=BB=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20=D0=BE=D1=82=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java index 8afcda2..e211051 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java @@ -2192,7 +2192,7 @@ public void run() { private void disconnectServerItem(TreeItem serverItem) { Server server = getCurrentServerConfig(serverItem); server.disconnectFromAgent(); - serverItem.setImage(serverIconDown); + serverItem.setImage(serverIcon); TreeItem[] clusterItems = serverItem.getItems(); for (TreeItem clusterItem : clusterItems) { From 122c2583a1e98d68484623743f9b8b3202673b37 Mon Sep 17 00:00:00 2001 From: YanSergey Date: Tue, 23 Aug 2022 08:52:44 +0300 Subject: [PATCH 5/6] =?UTF-8?q?=D0=B4=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- clusterAdminApplication/.classpath | 17 + clusterAdminApplication/.gitignore | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 1 + clusterAdminApplication/pom.xml | 16 - .../clusterAdminApplication/ClusterAdmin.java | 2 +- .../ClusterViewer.java | 15 +- clusterAdminLibrary/.classpath | 23 + clusterAdminLibrary/.gitignore | 1 + .../org.eclipse.core.resources.prefs | 1 + .../.settings/org.eclipse.jdt.core.prefs | 1 + clusterAdminLibrary/pom.xml | 68 +- .../eclipse/wb/swt/SWTResourceManager.java | 13 - .../clusterAdminLibrary/BaseInfoExtended.java | 297 ++ .../clusterAdminLibrary/CellValue.java | 176 + .../clusterAdminLibrary/ClusterProvider.java | 480 +- .../clusterAdminLibrary/ColumnProperties.java | 251 +- .../yanygin/clusterAdminLibrary/Config.java | 1022 ++-- .../ConnectionInfoExtended.java | 202 +- .../yanygin/clusterAdminLibrary/Helper.java | 206 + .../clusterAdminLibrary/IInfoExtended.java | 134 - .../InfoBaseInfoShortExt.java | 141 + .../clusterAdminLibrary/LockInfoExtended.java | 202 +- .../yanygin/clusterAdminLibrary/Server.java | 1943 +++++--- .../SessionInfoExtended.java | 724 +-- .../clusterAdminLibrary/UserPassPair.java | 137 + .../WorkingProcessInfoExtended.java | 275 +- .../WorkingServerInfoExtended.java | 252 +- .../clusterAdminLibrary/messages.properties | 9 + .../messages_ru_RU.properties | 11 +- .../clusterAdminLibraryUI/AboutDialog.java | 132 +- .../AuthenticateDialog.java | 124 +- ...tClusterDialog.java => ClusterDialog.java} | 214 +- .../CreateEditServerDialog.java | 427 -- .../CreateInfobaseDialog.java | 216 +- .../DropInfobaseDialog.java | 48 +- ...nfobaseDialog.java => InfobaseDialog.java} | 213 +- .../clusterAdminLibraryUI/ServerDialog.java | 650 +++ .../SessionInfoDialog.java | 149 +- .../clusterAdminLibraryUI/SettingsDialog.java | 198 +- .../clusterAdminLibraryUI/ViewerArea.java | 4169 +++++++++-------- ...erDialog.java => WorkingServerDialog.java} | 312 +- .../clusterAdminLibraryUI/messages.properties | 373 +- .../messages_ru_RU.properties | 371 +- .../src/main/resources/icons/favorites.png | Bin 0 -> 677 bytes .../src/main/resources/icons/hiddenPass.png | Bin 0 -> 668 bytes .../icons/{infobase_24.png => infobase.png} | Bin .../resources/icons/infobase_favorite.png | Bin 0 -> 670 bytes .../icons/infobase_favorite_left.png | Bin 0 -> 661 bytes .../main/resources/icons/lock_users_16.png | Bin 786 -> 893 bytes .../src/main/resources/icons/move_down.png | Bin 0 -> 496 bytes .../src/main/resources/icons/move_up.png | Bin 0 -> 455 bytes ...rver_up_24.png => server_connected_24.png} | Bin ...r_down_24.png => server_disconnect_24.png} | Bin .../src/main/resources/icons/sort.png | Bin 0 -> 505 bytes .../src/main/resources/icons/visiblePass.png | Bin 0 -> 594 bytes .../clusterAdminLibrary/ConfigTest.java | 81 + .../clusterAdminLibrary/InvocationTest.java | 126 - .../src/test/resources/config_0.2.0.json | 391 ++ .../resources/config_0.2.0_convert_0.3.0.json | 400 ++ 59 files changed, 9509 insertions(+), 5707 deletions(-) create mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/BaseInfoExtended.java create mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/CellValue.java create mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Helper.java delete mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java create mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/InfoBaseInfoShortExt.java create mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/UserPassPair.java rename clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/{CreateEditClusterDialog.java => ClusterDialog.java} (71%) delete mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java rename clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/{EditInfobaseDialog.java => InfobaseDialog.java} (70%) create mode 100644 clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ServerDialog.java rename clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/{CreateEditWorkingServerDialog.java => WorkingServerDialog.java} (72%) create mode 100644 clusterAdminLibrary/src/main/resources/icons/favorites.png create mode 100644 clusterAdminLibrary/src/main/resources/icons/hiddenPass.png rename clusterAdminLibrary/src/main/resources/icons/{infobase_24.png => infobase.png} (100%) create mode 100644 clusterAdminLibrary/src/main/resources/icons/infobase_favorite.png create mode 100644 clusterAdminLibrary/src/main/resources/icons/infobase_favorite_left.png create mode 100644 clusterAdminLibrary/src/main/resources/icons/move_down.png create mode 100644 clusterAdminLibrary/src/main/resources/icons/move_up.png rename clusterAdminLibrary/src/main/resources/icons/{server_up_24.png => server_connected_24.png} (100%) rename clusterAdminLibrary/src/main/resources/icons/{server_down_24.png => server_disconnect_24.png} (100%) create mode 100644 clusterAdminLibrary/src/main/resources/icons/sort.png create mode 100644 clusterAdminLibrary/src/main/resources/icons/visiblePass.png create mode 100644 clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/ConfigTest.java delete mode 100644 clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/InvocationTest.java create mode 100644 clusterAdminLibrary/src/test/resources/config_0.2.0.json create mode 100644 clusterAdminLibrary/src/test/resources/config_0.2.0_convert_0.3.0.json diff --git a/clusterAdminApplication/.classpath b/clusterAdminApplication/.classpath index 3721ade..82bedd0 100644 --- a/clusterAdminApplication/.classpath +++ b/clusterAdminApplication/.classpath @@ -23,5 +23,22 @@ + + + + + + + + + + + + + + + + + diff --git a/clusterAdminApplication/.gitignore b/clusterAdminApplication/.gitignore index d1bde9d..1c25b7d 100644 --- a/clusterAdminApplication/.gitignore +++ b/clusterAdminApplication/.gitignore @@ -1,4 +1,4 @@ /logs/ /bin/ -/config.json +/config*.json /target/ diff --git a/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs b/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs index 1f04118..25db14b 100644 --- a/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs +++ b/clusterAdminApplication/.settings/org.eclipse.jdt.core.prefs @@ -11,6 +11,7 @@ org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=11 org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns=false diff --git a/clusterAdminApplication/pom.xml b/clusterAdminApplication/pom.xml index f6ad4c1..6d61176 100644 --- a/clusterAdminApplication/pom.xml +++ b/clusterAdminApplication/pom.xml @@ -47,22 +47,6 @@ OneS_ClusterAdmin-${project.version}-macOS - - windows-x86 - - - windows - x86 - - - - ru.yanygin.clusterAdminLibrary.windows_x86 - org.eclipse.swt.win32.win32.x86 - - - OneS_ClusterAdmin-${project.version}-windows-x86 - - windows-x86_64 diff --git a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java index 051636e..3796ebf 100644 --- a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java +++ b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterAdmin.java @@ -17,7 +17,7 @@ public class ClusterAdmin { public static void main(String[] args) { try { - ClusterViewer window = new ClusterViewer(); + ClusterViewer window = new ClusterViewer(null); window.setBlockOnOpen(true); window.open(); Display.getCurrent().dispose(); diff --git a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java index 75819a4..55f8e6c 100644 --- a/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java +++ b/clusterAdminApplication/src/main/java/ru/yanygin/clusterAdminApplication/ClusterViewer.java @@ -12,6 +12,7 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import ru.yanygin.clusterAdminLibrary.ClusterProvider; +import ru.yanygin.clusterAdminLibrary.Config; import ru.yanygin.clusterAdminLibraryUI.ViewerArea; /** Application window class. */ @@ -20,20 +21,26 @@ public class ClusterViewer extends ApplicationWindow { Composite mainForm; ClusterProvider clusterProvider = new ClusterProvider(); + Config config; - /** Create the application window. */ - public ClusterViewer() { + /** + * Create the application window. + * + * @param configPath - путь к файлу конфигурации + */ + public ClusterViewer(String configPath) { super(null); createActions(); addToolBar(SWT.FLAT | SWT.WRAP); addMenuBar(); addStatusLine(); + this.config = Config.readConfig(configPath); } @Override public boolean close() { - clusterProvider.close(); + config.close(); return super.close(); } @@ -50,7 +57,7 @@ protected Control createContents(Composite parent) { Menu menu = this.getMenuBarManager().getMenu(); - ViewerArea container = new ViewerArea(parent, SWT.NONE, menu, toolBar, clusterProvider); + ViewerArea container = new ViewerArea(parent, SWT.NONE, menu, toolBar, clusterProvider, config); return container; } diff --git a/clusterAdminLibrary/.classpath b/clusterAdminLibrary/.classpath index 3c5b1ca..7b3c828 100644 --- a/clusterAdminLibrary/.classpath +++ b/clusterAdminLibrary/.classpath @@ -28,5 +28,28 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/clusterAdminLibrary/.gitignore b/clusterAdminLibrary/.gitignore index 92145bc..50aa492 100644 --- a/clusterAdminLibrary/.gitignore +++ b/clusterAdminLibrary/.gitignore @@ -1,2 +1,3 @@ +/logs/ /bin/ /target/ \ No newline at end of file diff --git a/clusterAdminLibrary/.settings/org.eclipse.core.resources.prefs b/clusterAdminLibrary/.settings/org.eclipse.core.resources.prefs index 3ec2daa..3773d39 100644 --- a/clusterAdminLibrary/.settings/org.eclipse.core.resources.prefs +++ b/clusterAdminLibrary/.settings/org.eclipse.core.resources.prefs @@ -4,4 +4,5 @@ encoding//src/main/java/ru/yanygin/clusterAdminLibrary=UTF-8 encoding//src/main/java/ru/yanygin/clusterAdminLibraryUI=UTF-8 encoding//src/main/resources=UTF-8 encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 encoding/=UTF-8 diff --git a/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs b/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs index 4304b63..7c60ea6 100644 --- a/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs +++ b/clusterAdminLibrary/.settings/org.eclipse.jdt.core.prefs @@ -12,6 +12,7 @@ org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=11 org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns=false diff --git a/clusterAdminLibrary/pom.xml b/clusterAdminLibrary/pom.xml index 83ca05f..d82dc7f 100644 --- a/clusterAdminLibrary/pom.xml +++ b/clusterAdminLibrary/pom.xml @@ -47,22 +47,6 @@ ru.yanygin.clusterAdminLibrary.macOS-${project.version} - - windows-x86 - - - windows - x86 - - - - ru.yanygin.clusterAdminLibrary.windows_x86 - org.eclipse.swt.win32.win32.x86 - - - ru.yanygin.clusterAdminLibrary.windows_x86-${project.version} - - windows-x86_64 @@ -113,11 +97,12 @@ 3.116.0 + - junit - junit - 3.8.1 - test + org.junit.jupiter + junit-jupiter-api + 5.8.2 + test @@ -225,7 +210,28 @@ com._1c.v8.swp 1.0.3-SNAPSHOT - + + + + org.apache.maven + maven-model + 3.8.5 + + + + + org.json + json + 20220320 + + + + + org.apache.httpcomponents + fluent-hc + 4.5.13 + + @@ -236,6 +242,7 @@ ${basedir}/src/main/java/ru/yanygin/clusterAdminLibrary + true /ru/yanygin/clusterAdminLibrary **/*.properties @@ -395,6 +402,25 @@ + + + org.apache.maven.plugins + maven-surefire-plugin + 2.21.0 + + + org.junit.platform + junit-platform-surefire-provider + 1.2.0-M1 + + + org.junit.jupiter + junit-jupiter-engine + 5.2.0-M1 + + + + diff --git a/clusterAdminLibrary/src/main/java/org/eclipse/wb/swt/SWTResourceManager.java b/clusterAdminLibrary/src/main/java/org/eclipse/wb/swt/SWTResourceManager.java index 1b84706..d8a2858 100644 --- a/clusterAdminLibrary/src/main/java/org/eclipse/wb/swt/SWTResourceManager.java +++ b/clusterAdminLibrary/src/main/java/org/eclipse/wb/swt/SWTResourceManager.java @@ -444,17 +444,4 @@ public static void dispose() { disposeFonts(); disposeCursors(); } - - public static Color getWhiteColor() { - return getColor(255, 255, 255); - } - - public static Color getPinkColor() { - return getColor(255, 204, 204); - } - - public static Color getLightGreenColor() { - return getColor(128, 255, 128); - } - } \ No newline at end of file diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/BaseInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/BaseInfoExtended.java new file mode 100644 index 0000000..64ed60e --- /dev/null +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/BaseInfoExtended.java @@ -0,0 +1,297 @@ +package ru.yanygin.clusterAdminLibrary; + +import java.text.Collator; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableItem; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import ru.yanygin.clusterAdminLibrary.CellValue.CELL_VALUE_TYPE; +import ru.yanygin.clusterAdminLibraryUI.ViewerArea; + +/** Базовый класс для расширенной информации. */ +public abstract class BaseInfoExtended implements Comparable { + private static final Logger LOGGER = LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ + + protected static final Color newItemColor = new Color(0, 200, 0); + protected static final Color shadowItemColor = new Color(160, 160, 160); + protected static final Color watchedSessionColor = new Color(0, 128, 255); + protected static final Color standardColor = new Color(0, 0, 0); + + protected Server server; + protected UUID clusterId; + + protected Map data = new LinkedHashMap<>(); + + protected Image currentIcon; + + /** + * Добавление этого экземпляра в таблицу. + * + * @param table - Таблица + * @param index - индекс для вставки + */ + public abstract void addToTable(Table table, int index); + + /** + * Добавление этого экземпляра в таблицу на последнюю позицию. + * + * @param table - Таблица + */ + public void addToTable(Table table) { + try { + addToTable(table, -1); + } catch (Exception excp) { + LOGGER.error("Error:", excp); //$NON-NLS-1$ + } + } + + /** + * Получение сервера. + * + * @return Сервер + */ + public Server getServer() { + return server; + } + + /** + * Получение Cluster ID. + * + * @return the clusterId + */ + public UUID getClusterId() { + return clusterId; + } + + /** + * Получение расширенной информации. + * + * @return the sessionData1 + */ + public Map getExtendedData() { + // TODO не используется + return data; + } + + /** + * Получение расширенной информации в виде массива строк. + * + * @return расширенная информация в виде массива строк + */ + public String[] getExtendedInfo() { + + ColumnProperties columnProperties = Config.currentConfig.getColumnsProperties(this.getClass()); + + String[] columnsName = columnProperties.getColumnsName(); + + String[] value = new String[columnsName.length]; + int index = 0; + for (String columnName : columnsName) { + try { + value[index] = data.get(columnName).value; + } catch (Exception e) { + value[index] = ""; + } + index++; + } + return value; + } + + /** + * Convert UUID to string. + * + * @param uuid - UUID + * @return string + */ + public String convertUuidToString(UUID uuid) { + // TODO не используется + return uuid.equals(Helper.EMPTY_UUID) ? "" : uuid.toString(); //$NON-NLS-1$ + } + + @Override + public int compareTo(BaseInfoExtended o) { + + ColumnProperties columnProperties = Config.currentConfig.getColumnsProperties(this.getClass()); + + int sortColumn = columnProperties.getSortColumn(); + int sortColumnDirection = columnProperties.getSortDirectionSwt(); + + if (sortColumn < 0) { + return 0; + } + + String sortColumnName = (String) data.keySet().toArray()[sortColumn]; + Object left; + Object right; + switch (sortColumnDirection) { + case SWT.UP: + left = this.data.get(sortColumnName).originalValue; + right = o.data.get(sortColumnName).originalValue; + break; + + case SWT.DOWN: + left = o.data.get(sortColumnName).originalValue; + right = this.data.get(sortColumnName).originalValue; + break; + + case SWT.NONE: + default: + return 0; + } + + int compareResult = 0; + try { + switch (this.data.get(sortColumnName).type) { + case INT: + case SECONDS_INT: + case INT_GROUP: + case DECIMAL_3_CHAR: + // compareResult = Integer.compare((int) left, (int) right); + if (left instanceof Integer) { + compareResult = Integer.compare((int) left, (int) right); + } else if (left instanceof Long) { + compareResult = Long.compare((long) left, (long) right); + } + + break; + + case SECONDS_LONG: + case LONG_GROUP: + compareResult = Long.compare((long) left, (long) right); + break; + + case DECIMAL_6_CHAR: + compareResult = Double.compare((double) left, (double) right); + break; + + case DATE: + case TEXT: + default: + compareResult = + Collator.getInstance(Locale.getDefault()) + .compare(String.valueOf(left), String.valueOf(right)); + } + } catch (NumberFormatException excp) { + compareResult = + Collator.getInstance(Locale.getDefault()) + .compare(String.valueOf(left), String.valueOf(right)); + } + + return compareResult; + } + + protected TableItem createTableItem(Table table, int index, Date startDateItem) { + TableItem item = null; + if (index == -1) { + item = new TableItem(table, SWT.NONE); + } else { + item = new TableItem(table, SWT.NONE, index); + } + + item.setText(getExtendedInfo()); + item.setData(ViewerArea.EXTENDED_INFO, this); + item.setImage(currentIcon); + item.setChecked(false); + + highlightNewItem(item, startDateItem); + + return item; + } + + /** + * Устанавливает подсветку нового эелемента при включенной настройке. + * + * @param item - строка таблицы + * @param startDateItem - дата старта + */ + private void highlightNewItem(TableItem item, Date startDateItem) { + if (startDateItem == null) { + return; + } + + Config commonConfig = Config.currentConfig; + if (commonConfig.isHighlightNewItems() + && (new Date().getTime() - startDateItem.getTime() + < commonConfig.getHighlightNewItemsDuration() * 1000)) { + item.setForeground(newItemColor); + } + } + + protected abstract void computeExtendedInfoData(); + + protected void putData(String title, Object value, CELL_VALUE_TYPE dataType) { + + CellValue column = new CellValue(title, title, value, dataType); + data.put(title, column); + } + + /** Инициализация имен колонок всех подклассов. */ + public static void init() { + + SessionInfoExtended.initColumnsName(); + ConnectionInfoExtended.initColumnsName(); + LockInfoExtended.initColumnsName(); + WorkingProcessInfoExtended.initColumnsName(); + WorkingServerInfoExtended.initColumnsName(); + } + + /** + * Обновление заголовка вкладки с количеством элементов. + * + * @param clazz - класс-наследник BaseInfoExtended + * @param count - количество элементов + */ + public static void updateTabText(Class clazz, int count) { + resetTabsTextCount(); + + if (clazz == SessionInfoExtended.class) { + SessionInfoExtended.updateTabText(count); + } else if (clazz == ConnectionInfoExtended.class) { + ConnectionInfoExtended.updateTabText(count); + } else if (clazz == LockInfoExtended.class) { + LockInfoExtended.updateTabText(count); + } else if (clazz == WorkingProcessInfoExtended.class) { + WorkingProcessInfoExtended.updateTabText(count); + } else if (clazz == WorkingServerInfoExtended.class) { + WorkingServerInfoExtended.updateTabText(count); + } + } + + /** Сброс заголовков вкладок на неизвестное количество элементов. */ + public static void resetTabsTextCount() { + SessionInfoExtended.resetTabTextCount(); + ConnectionInfoExtended.resetTabTextCount(); + LockInfoExtended.resetTabTextCount(); + WorkingProcessInfoExtended.resetTabTextCount(); + WorkingServerInfoExtended.resetTabTextCount(); + } + + /** + * Установка связи таблицы-списка со вкладкой. + * + * @param clazz - класс-наследник BaseInfoExtended + * @param tabitem - вкладка, на которой находится таблица + */ + public static void linkTabItem(Class clazz, TabItem tabitem) { + if (clazz == SessionInfoExtended.class) { + SessionInfoExtended.linkTabItem(tabitem); + } else if (clazz == ConnectionInfoExtended.class) { + ConnectionInfoExtended.linkTabItem(tabitem); + } else if (clazz == LockInfoExtended.class) { + LockInfoExtended.linkTabItem(tabitem); + } else if (clazz == WorkingProcessInfoExtended.class) { + WorkingProcessInfoExtended.linkTabItem(tabitem); + } else if (clazz == WorkingServerInfoExtended.class) { + WorkingServerInfoExtended.linkTabItem(tabitem); + } + } +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/CellValue.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/CellValue.java new file mode 100644 index 0000000..6ab9d76 --- /dev/null +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/CellValue.java @@ -0,0 +1,176 @@ +package ru.yanygin.clusterAdminLibrary; + +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** Value of cell from lists. */ +public class CellValue { + + public enum CELL_VALUE_TYPE { + TEXT, + INT, + BOOLEAN, + DATE, + SECONDS_INT, + SECONDS_LONG, + INT_GROUP, + LONG_GROUP, + DECIMAL_3_CHAR, + DECIMAL_6_CHAR + } + + public String name; + public String descr; + public String value; + public Object originalValue; + public CELL_VALUE_TYPE type; + + DecimalFormat decimalFormatDouble3 = new DecimalFormat("###,##0.000"); //$NON-NLS-1$ + DecimalFormat decimalFormatDouble6 = new DecimalFormat("#,##0.000000"); //$NON-NLS-1$ + DecimalFormat decimalFormatLong = new DecimalFormat("###,###"); //$NON-NLS-1$ + + // NumberFormat fmt = NumberFormat.getInstance(); + // fmt.setGroupingUsed(false); + // fmt.setMaximumIntegerDigits(999); + // fmt.setMaximumFractionDigits(999); + + /** + * Create cell value class. + * + * @param name - Name of column + * @param descr - Description of column + * @param value - Value of cell + * @param type - Type value of cell + */ + public CellValue(String name, String descr, Object value, CELL_VALUE_TYPE type) { + this.name = name; + this.descr = descr; + this.originalValue = value; + this.type = type; + + switch (type) { + case INT: + this.value = Integer.toString((int) value); + break; + + case BOOLEAN: + this.value = Boolean.toString((boolean) value); + break; + + case DATE: + this.value = dateToString((Date) value); + break; + + case SECONDS_INT: + this.value = double3ToString((int) value); + // double d = Double.valueOf((int) value); + // this.value = millisecondToString((int) value); + break; + + case SECONDS_LONG: + this.value = double3ToString((long) value); + // this.value = millisecondToString((long) value); + break; + + case INT_GROUP: + this.value = longToStringGroup((int) value); + break; + + case LONG_GROUP: + this.value = longToStringGroup((long) value); + break; + + case DECIMAL_3_CHAR: + if (value instanceof Integer) { + this.value = double3ToString((int) value); + } else if (value instanceof Long) { + this.value = double3ToString((long) value); + } + break; + + case DECIMAL_6_CHAR: + this.value = double6ToString((double) value); + break; + + case TEXT: + default: + this.value = (String) value; + } + } + + /** + * Cast date to string. + * + * @param date - date + * @return date format to string + */ + private String dateToString(Date date) { + + DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); //$NON-NLS-1$ + Date emptyDate = new Date(0); + + return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ + } + + /** + * Cast double value to string. + * + * @param value - double value + * @return double value to string + */ + private String double3ToString(double value) { + return decimalFormatDouble3.format(value / 1000); + } + + /** + * Cast double value to string. + * + * @param value - double value + * @return double value to string + */ + private String double6ToString(double value) { + return decimalFormatDouble6.format(value); + } + + /** + * Cast long value to string. + * + * @param value - long value + * @return long value to string + */ + private String longToStringGroup(long value) { + return decimalFormatLong.format(value); + } + + /** + * Cast millisecond to string. + * + * @param value - millisecond + * @return millisecond to string + */ + private String millisecondToString(int value) { + return Double.toString(((double) value) / 1000); + } + + /** + * Cast millisecond to string. + * + * @param value - millisecond + * @return millisecond to string + */ + private String millisecondToString(long value) { + return Double.toString(((double) value) / 1000); + } + + /** + * Cast double value to string. + * + * @param value - double value + * @return double value to string + */ + private String doubleToString1(double value) { + return String.format("%.9f", value); + } +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java index e05bef8..e5d19d8 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ClusterProvider.java @@ -1,27 +1,8 @@ package ru.yanygin.clusterAdminLibrary; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonIOException; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Locale; -import java.util.Map; -import org.eclipse.swt.dnd.Clipboard; -import org.eclipse.swt.dnd.TextTransfer; -import org.eclipse.swt.widgets.Display; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,143 +11,151 @@ public class ClusterProvider { File configFile; static Config commonConfig; private static final String DEFAULT_CONFIG_PATH = "config.json"; //$NON-NLS-1$ + private static final String TEMP_CONFIG_PATH = "config_temp.json"; //$NON-NLS-1$ private static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ public ClusterProvider() {} - public static Config getCommonConfig() { - return commonConfig; - } - - public void readConfig() { - readConfig(DEFAULT_CONFIG_PATH); - } - - public void readConfig(String configPath) { - LOGGER.info("Start read config from file <{}>", configPath); //$NON-NLS-1$ - - if (configPath.isBlank()) { - LOGGER.debug("Config path is empty, create new config in root folder"); //$NON-NLS-1$ - commonConfig = new Config(); - return; - } - - configFile = new File(configPath); - if (!configFile.exists()) { - LOGGER.debug("Config file not exists, create new"); //$NON-NLS-1$ - commonConfig = new Config(); - return; - } - - JsonReader jsonReader = null; - - try { - jsonReader = - new JsonReader( - new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); - } catch (FileNotFoundException excp) { - LOGGER.debug("Config file read error:", excp); //$NON-NLS-1$ - LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ - configFile = new File(DEFAULT_CONFIG_PATH); - commonConfig = new Config(); - return; - } - Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); - - try { - commonConfig = gson.fromJson(jsonReader, Config.class); - } catch (Exception excp) { - LOGGER.debug("error convert config from json"); //$NON-NLS-1$ - LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ - configFile = new File(DEFAULT_CONFIG_PATH); - commonConfig = new Config(); - return; - } - - if (commonConfig == null) { - LOGGER.debug("config is null, after read json"); //$NON-NLS-1$ - LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ - configFile = new File(DEFAULT_CONFIG_PATH); - commonConfig = new Config(); - } else { - - commonConfig.init(); - - if (commonConfig.getLocale() != null) { - LOGGER.debug("Set locale is <{}>", commonConfig.getLocale()); //$NON-NLS-1$ - Locale locale = Locale.forLanguageTag(commonConfig.getLocale()); - java.util.Locale.setDefault(locale); - Messages.reloadBundle(locale); - } - } - LOGGER.info("Config file read successfully"); //$NON-NLS-1$ - } - - public void saveConfig() { - - LOGGER.info("Start save config to file <{}>", configFile.getAbsolutePath()); //$NON-NLS-1$ - - // configFile = new File(configPath); - - JsonWriter jsonWriter; - try { - jsonWriter = - new JsonWriter( - new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8)); - } catch (FileNotFoundException excp) { - LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ - return; - } - Gson gson = - new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); - try { - gson.toJson(getCommonConfig(), getCommonConfig().getClass(), jsonWriter); - } catch (JsonIOException excp) { - LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ - } - - try { - jsonWriter.close(); - } catch (IOException excp) { - LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ - } - LOGGER.info("Config file write successfully"); //$NON-NLS-1$ - } - - public Server createNewServer() { - Server newServer = null; - - if (commonConfig.isReadClipboard()) { - Clipboard clipboard = new Clipboard(Display.getDefault()); - String clip = (String) clipboard.getContents(TextTransfer.getInstance()); - clipboard.dispose(); - - if (clip != null && clip.startsWith("Srvr=")) { //$NON-NLS-1$ - String[] srvrPart = clip.split(";"); //$NON-NLS-1$ - String srvr = srvrPart[0].substring(6, srvrPart[0].length() - 1); - newServer = new Server(srvr); - } - } else { - newServer = new Server("Server:1541"); //$NON-NLS-1$ - } - - return newServer; - } - - public void addNewServer(Server server) { - commonConfig.getServers().put(server.getServerKey(), server); - saveConfig(); - } - - public void removeServer(Server server) { - getCommonConfig().getServers().remove(server.getServerKey(), server); - saveConfig(); - } - - public Map getServers() { - return getCommonConfig().getServers(); - } + // public static Config getCommonConfig() { + // return commonConfig; + // } + + /** Читает конфиг из файла по-умолчанию. */ + // public void readConfig() { + // readConfig(DEFAULT_CONFIG_PATH); + // } + + /** + * Читает конфиг из определенного файла. + * + * @param configPath - имя конфиг файла + */ + // public void readConfig(String configPath) { + // LOGGER.info("Start read config from file <{}>", configPath); //$NON-NLS-1$ + // + // if (configPath.isBlank()) { + // LOGGER.debug("Config path is empty, create new config in root folder"); //$NON-NLS-1$ + // commonConfig = new Config(); + // return; + // } + // + // configFile = new File(configPath); + // if (!configFile.exists()) { + // LOGGER.debug("Config file not exists, create new"); //$NON-NLS-1$ + // commonConfig = new Config(); + // return; + // } + // + // JsonReader jsonReader = null; + // + // try { + // jsonReader = + // new JsonReader( + // new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); + // } catch (FileNotFoundException excp) { + // LOGGER.debug("Config file read error:", excp); //$NON-NLS-1$ + // LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ + // configFile = new File(TEMP_CONFIG_PATH); + // commonConfig = new Config(); + // return; + // } + // Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + // + // try { + // commonConfig = gson.fromJson(jsonReader, Config.class); + // commonConfig.migrateProps(); + // } catch (Exception excp) { + // LOGGER.debug("error convert config from json:", excp); //$NON-NLS-1$ + // LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ + // configFile = new File(TEMP_CONFIG_PATH); + // commonConfig = new Config(); + // return; + // } + // + // if (commonConfig == null) { + // LOGGER.debug("config is null, after read json"); //$NON-NLS-1$ + // LOGGER.debug("Create new config in root folder"); //$NON-NLS-1$ + // configFile = new File(TEMP_CONFIG_PATH); + // commonConfig = new Config(); + // } else { + // + // commonConfig.init(); + // if (commonConfig.getLocale() != null) { + // LOGGER.debug("Set locale is <{}>", commonConfig.getLocale()); //$NON-NLS-1$ + // Locale locale = Locale.forLanguageTag(commonConfig.getLocale()); + // java.util.Locale.setDefault(locale); + // Messages.reloadBundle(locale); // TODO не совсем понятно как работает + // } + // } + // LOGGER.info("Config file read successfully"); //$NON-NLS-1$ + // } + // + // public void saveConfig() { + // + // LOGGER.info("Start save config to file <{}>", configFile.getAbsolutePath()); //$NON-NLS-1$ + // + // // configFile = new File(configPath); + // + // JsonWriter jsonWriter; + // try { + // jsonWriter = + // new JsonWriter( + // new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.UTF_8)); + // } catch (FileNotFoundException excp) { + // LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + // return; + // } + // Gson gson = + // new GsonBuilder() + // .excludeFieldsWithoutExposeAnnotation() + // .setPrettyPrinting() + // .create(); + // try { + // gson.toJson(getCommonConfig(), getCommonConfig().getClass(), jsonWriter); + // } catch (JsonIOException excp) { + // LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + // } + // + // try { + // jsonWriter.close(); + // } catch (IOException excp) { + // LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + // } + // LOGGER.info("Config file write successfully"); //$NON-NLS-1$ + // } + + // public Server createNewServer() { + // Server newServer = null; + // + // if (commonConfig.isReadClipboard()) { + // Clipboard clipboard = new Clipboard(Display.getDefault()); + // String clip = (String) clipboard.getContents(TextTransfer.getInstance()); + // clipboard.dispose(); + // + // if (clip != null && clip.startsWith("Srvr=")) { //$NON-NLS-1$ + // String[] srvrPart = clip.split(";"); //$NON-NLS-1$ + // String srvr = srvrPart[0].substring(6, srvrPart[0].length() - 1); + // return new Server(srvr); + // } + // } + // + // return new Server("Server:1541"); //$NON-NLS-1$ + // } + + // public void addNewServer(Server server) { + // commonConfig.getServers().put(server.getServerKey(), server); + // saveConfig(); + // } + // + // public void removeServer(Server server) { + // getCommonConfig().getServers().remove(server.getServerKey(), server); + // saveConfig(); + // } + // + // public Map getServers() { + // return getCommonConfig().getServers(); + // } public List findNewServers() { @@ -175,97 +164,100 @@ public List findNewServers() { return addedServers; } - public void connectToServers() { - - getCommonConfig().connectAllServers(); - } - - public List getConnectedServers() { - - List connectedServers = new ArrayList<>(); - - getCommonConfig() - .getServers() - .forEach( - (server, config) -> { - if (config.isConnected()) { - connectedServers.add(config.getServerKey()); - } - }); - - return connectedServers; - } - - public void checkConnectToServers() { - - getCommonConfig().checkConnectionAllServers(); - } - - public void close() { - - saveConfig(); - - getServers() - .forEach( - (server, config) -> { - if (config.isConnected()) { - config.disconnectFromAgent(); - } - }); - } - - public static Map getInstalledV8Versions() { - LOGGER.debug("Get installed v8 platform versions"); //$NON-NLS-1$ - - Map versions = new HashMap<>(); - - if (!commonConfig.isWindows()) { - return versions; - } - - File v8x64CommonPath = new File("C:\\Program Files\\1cv8"); //$NON-NLS-1$ - File v8x86CommonPath = new File("C:\\Program Files (x86)\\1cv8"); //$NON-NLS-1$ - - FilenameFilter filter = - new FilenameFilter() { - @Override - public boolean accept(File f, String name) { - return name.matches("8.3.\\d\\d.\\d{4}"); //$NON-NLS-1$ - } - }; - - try { - if (v8x64CommonPath.exists()) { - File[] v8x64dirs = v8x64CommonPath.listFiles(filter); - for (File dir : v8x64dirs) { - if (dir.isDirectory()) { - File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ - if (ras.exists() && ras.isFile()) { - versions.put(dir.getName().concat(" (x86_64)"), ras.getAbsolutePath()); //$NON-NLS-1$ - } - } - } - } - } catch (Exception excp) { - LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ - } - - try { - if (v8x86CommonPath.exists()) { - File[] v8x86dirs = v8x86CommonPath.listFiles(filter); - for (File dir : v8x86dirs) { - if (dir.isDirectory()) { - File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ - if (ras.exists() && ras.isFile()) { - versions.put(dir.getName(), ras.getAbsolutePath()); //$NON-NLS-1$ - } - } - } - } - } catch (Exception excp) { - LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ - } - - return versions; - } + // public void connectToServers() { + // + // getCommonConfig().connectAllServers(); + // } + + // public List getConnectedServers() { + // + // List connectedServers = new ArrayList<>(); + // + // getCommonConfig() + // .getServers() + // .forEach( + // (server, config) -> { + // if (config.isConnected()) { + // connectedServers.add(config.getServerKey()); + // } + // }); + // + // return connectedServers; + // } + + // public void checkConnectToServers() { + // + // getCommonConfig().checkConnectionAllServers(); + // } + + // public void close() { + // + // saveConfig(); + // + // getServers() + // .forEach( + // (server, config) -> { + // if (config.isConnected()) { + // config.disconnectFromAgent(); + // } + // }); + // } + // + // public static Map getInstalledV8Versions() { + // LOGGER.debug("Get installed v8 platform versions"); //$NON-NLS-1$ + // + // Map versions = new HashMap<>(); + // + // if (!commonConfig.isWindows()) { + // return versions; + // } + // + // File v8x64CommonPath = new File("C:\\Program Files\\1cv8"); //$NON-NLS-1$ + // File v8x86CommonPath = new File("C:\\Program Files (x86)\\1cv8"); //$NON-NLS-1$ + // + // FilenameFilter filter = + // new FilenameFilter() { + // @Override + // public boolean accept(File f, String name) { + // return name.matches("8.3.\\d\\d.\\d{4}"); //$NON-NLS-1$ + // } + // }; + // + // try { + // if (v8x64CommonPath.exists()) { + // File[] v8x64dirs = v8x64CommonPath.listFiles(filter); + // for (File dir : v8x64dirs) { + // if (dir.isDirectory()) { + // File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ + // if (ras.exists() && ras.isFile()) { + // versions.put(dir.getName().concat(" (x86_64)"), ras.getAbsolutePath()); + // //$NON-NLS-1$ + // } + // } + // } + // } + // } catch (Exception excp) { + // LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); + // //$NON-NLS-1$ + // } + // + // try { + // if (v8x86CommonPath.exists()) { + // File[] v8x86dirs = v8x86CommonPath.listFiles(filter); + // for (File dir : v8x86dirs) { + // if (dir.isDirectory()) { + // File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ + // if (ras.exists() && ras.isFile()) { + // versions.put(dir.getName(), ras.getAbsolutePath()); //$NON-NLS-1$ + // } + // } + // } + // } + // } catch (Exception excp) { + // LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); + // //$NON-NLS-1$ + // } + // + // return versions; + // } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java index 223c137..6557989 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ColumnProperties.java @@ -2,8 +2,11 @@ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; +import java.util.LinkedHashMap; +import java.util.Map; +import org.eclipse.swt.SWT; -/** Column properties. */ +/** Свойства столбцов. */ public class ColumnProperties { @SerializedName("Order") @@ -18,64 +21,278 @@ public class ColumnProperties { @Expose private boolean[] visible = null; + @SerializedName("SortColumn") + @Expose + private int sortColumn = -1; // -1 = отсутствие сортировки + + @SerializedName("RowSortDirection") + @Expose + private RowSortDirection rowSortDirection = RowSortDirection.DISABLE; + + private Map columnsMap = new LinkedHashMap<>(); + + /** Направление сортировки строк. */ + public enum RowSortDirection { + /** Выключено/Как у предыдущего столбца. */ + DISABLE, + /** По возрастанию. */ + ASC, + /** По убыванию. */ + DESC + } + + /** Конструктор по-умолчанию. */ + public ColumnProperties() { + // нужен для инициализации полей не найденных в конфиге при десериализации + } + + /** Инициализация параметров после десериализации. */ + public void init() { + // TODO deprecated? + // При чтении конфиг-файла отсутствующие поля, инициализируются значением null + if (this.rowSortDirection == null) { + this.rowSortDirection = RowSortDirection.DISABLE; + } + } + /** - * Get column order. + * Получить порядок столбцов. * - * @return column order + * @return порядок столбцов */ public int[] getOrder() { return order; } /** - * Set column order. + * Установить порядок столбцов. * - * @param order - new column order + * @param order - новый порядок столбцов */ public void setOrder(int[] order) { this.order = order; } /** - * Get column width. + * Получить ширину столбцов. * - * @return column width + * @return ширина столбцов */ public int[] getWidth() { return width; } /** - * Set column width. + * Установить ширину столбца. * - * @param width - new column width + * @param index - номер столбца + * @param width - новая ширина столбца */ public void setWidth(int index, int width) { this.width[index] = width; } /** - * Get column visible. + * Получить видимость столбцов. * - * @return column visible + * @return видимость столбцов */ public boolean[] getVisible() { return visible; } /** - * Set column visible. + * Установить видимость столбца. * - * @param visible - new column visible + * @param visible - новое значение видимости столбца */ public void setVisible(boolean[] visible) { this.visible = visible; } /** - * Column properties. + * Получить порядок столбцов. + * + * @return орядок столбцов + */ + public int getSortColumn() { + return sortColumn; + } + + /** + * Выполнить сортировку столбца. + * + * @param sortColumn - номер столбца + */ + public void setSortColumn(int sortColumn) { + + RowSortDirection defSortDir = Config.currentConfig.getRowSortDirection(); + + if (this.sortColumn == sortColumn) { // колонка не меняется - переключаем направление + + switch (this.rowSortDirection) { + case ASC: + this.rowSortDirection = RowSortDirection.DESC; + break; + case DESC: + this.rowSortDirection = RowSortDirection.ASC; + break; + + default: + this.rowSortDirection = + (defSortDir == RowSortDirection.DISABLE) ? RowSortDirection.DESC : defSortDir; + break; + } + + } else { // колонка меняется - ставим направление из настроек + + if (defSortDir == RowSortDirection.ASC || defSortDir == RowSortDirection.DESC) { + this.rowSortDirection = defSortDir; + } else if (defSortDir == RowSortDirection.DISABLE + && this.rowSortDirection == RowSortDirection.DISABLE) { + this.rowSortDirection = RowSortDirection.DESC; + } + + // TODO (нужен еще коммент или уже сделал?) + // если по-умолчанию = как предыдущее - то менять не нужно + // (но надо учесть, что предыдущее может быть не ASC и не DESC), тогда ставим DESC + // если по-умолчанию = ASC или DESC - то ставим его принудительно + + } + + this.sortColumn = sortColumn; + } + + /** + * Получить направление сортировки строк. + * + * @return направление сортировки + */ + public RowSortDirection getSortDirection() { + return this.rowSortDirection; + } + + /** + * Получить направление сортировки строк в SWT значениях. + * + * @return направление сортировки + */ + public int getSortDirectionSwt() { + int sortDirectionSwt = 0; + switch (this.rowSortDirection) { + case ASC: + sortDirectionSwt = SWT.UP; + break; + + case DESC: + sortDirectionSwt = SWT.DOWN; + break; + + case DISABLE: + default: + sortDirectionSwt = SWT.NONE; + break; + } + + return sortDirectionSwt; + } + + /** + * Установить направление сортировки строк. + * + * @param sortDirectionSwt направление сортировки строк в SWT значениях + */ + public void setSortDirection(int sortDirectionSwt) { + + switch (sortDirectionSwt) { + case SWT.UP: + this.rowSortDirection = RowSortDirection.ASC; + break; + + case SWT.DOWN: + this.rowSortDirection = RowSortDirection.DESC; + break; + + case SWT.NONE: + default: + this.rowSortDirection = RowSortDirection.DISABLE; + break; + } + + } + + /** + * Get Columns Map. + * + * @return ColumnsMap + */ + // public Map getColumnsMap() { + // return columnsMap; + // } + + /** + * Add column. + * + * @param columnName - column name + */ + // public void addColumnInMap(String columnName) { + // if (columnsMap == null) { + // columnsMap = new LinkedHashMap<>(); + // } + // columnsMap.put(columnName, ""); //$NON-NLS-1$ + // } + + /** + * Добавить столбцы. + * + * @param columnsName - имена столбцов + */ + public void addColumnsInMap(String... columnsName) { + for (int i = 0; i < columnsName.length; i++) { + columnsMap.put(columnsName[i], ""); //$NON-NLS-1$ + } + updateColumnProperties(columnsName.length); + } + + /** + * Подготовка map перед заполнением значениями (устанавливает порядок столбцов). + * + * @param data - будущая map со значениями строк + */ + public void prepareDataMap(Map data) { + columnsMap.forEach((k, v) -> data.put(k, null)); + } + + /** + * Получение имен столбцов. + * + * @return String[] массив имен столбцов + */ + public String[] getColumnsName() { + return columnsMap.keySet().toArray(new String[0]); + } + + /** + * Получение имен столбцов для пользователей. + * + * @return String[] массив имен столбцов + */ + public String[] getColumnsDescription() { + + String[] str = columnsMap.keySet().toArray(new String[0]); + + String[] names = new String[str.length]; + for (int i = 0; i < str.length; i++) { + names[i] = Messages.getString(str[i]); + } + + return names; + } + + /** + * Конструктор, инициализирует свойства столбцов. * - * @param size - column count + * @param size - количество колонок */ public ColumnProperties(int size) { @@ -96,9 +313,9 @@ public ColumnProperties(int size) { } /** - * Update column count by the current count. + * Обновление текущего количества столбцов. * - * @param arraySize - current colimn count + * @param arraySize - текущее количество столбцов */ public void updateColumnProperties(int arraySize) { diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java index aad7d88..c514914 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java @@ -1,20 +1,54 @@ package ru.yanygin.clusterAdminLibrary; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonIOException; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.awt.Desktop; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.lang.module.ModuleDescriptor.Version; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import org.apache.http.client.fluent.Request; +import org.eclipse.swt.SWT; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Shell; +import org.json.JSONArray; +import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import ru.yanygin.clusterAdminLibrary.ColumnProperties.RowSortDirection; +import ru.yanygin.clusterAdminLibrary.InfoBaseInfoShortExt.InfobasesSortDirection; -/** Main config for applacation. */ +/** Класс с конфигурацией приложения. */ public class Config { - @SerializedName("Servers") + + @SerializedName("ConfigVersion") @Expose - private Map servers = new HashMap<>(); + private String configVersion; + + @SerializedName("CheckingUpdate") + @Expose + private boolean checkingUpdate = false; @SerializedName("ExpandServers") @Expose @@ -62,48 +96,69 @@ public class Config { @SerializedName("Locale") @Expose - private String locale; + private String locale = null; // null = как в системе - @SerializedName("SessionColumnProperties") + @SerializedName("ShadeSleepingSessions") @Expose - private ColumnProperties sessionColumnProperties; + private boolean shadeSleepingSessions; - @SerializedName("ConnectionColumnProperties") + @SerializedName("HighlightNewItems") @Expose - private ColumnProperties connectionColumnProperties; + private boolean highlightNewItems; - @SerializedName("LockColumnProperties") + @SerializedName("HighlightNewItemsDuration") @Expose - private ColumnProperties lockColumnProperties; + private int highlightNewItemsDuration; - @SerializedName("WPColumnProperties") + @SerializedName("ReadClipboard") @Expose - private ColumnProperties wpColumnProperties; + private boolean readClipboard; - @SerializedName("WSColumnProperties") + @SerializedName("RowSortDirection") @Expose - private ColumnProperties wsColumnProperties; + private RowSortDirection rowSortDirection = RowSortDirection.DISABLE; - @SerializedName("ShadowSleepSessions") + @SerializedName("InfobasesSortDirection") @Expose - private boolean shadowSleepSessions; + private InfobasesSortDirection infobasesSortDirection = InfobasesSortDirection.DISABLE; - @SerializedName("HighlightNewItems") + @SerializedName("Servers") @Expose - private boolean highlightNewItems; + private Map servers = new HashMap<>(); - @SerializedName("HighlightNewItemsDuration") + @SerializedName("SessionColumnProperties") @Expose - private int highlightNewItemsDuration; + private ColumnProperties sessionColumnProperties = new ColumnProperties(0); - @SerializedName("ReadClipboard") + @SerializedName("ConnectionColumnProperties") @Expose - private boolean readClipboard; + private ColumnProperties connectionColumnProperties = new ColumnProperties(0); + + @SerializedName("LockColumnProperties") + @Expose + private ColumnProperties lockColumnProperties = new ColumnProperties(0); + + @SerializedName("WPColumnProperties") + @Expose + private ColumnProperties wpColumnProperties = new ColumnProperties(0); + + @SerializedName("WSColumnProperties") + @Expose + private ColumnProperties wsColumnProperties = new ColumnProperties(0); private static final Logger LOGGER = LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ + private static final String DEFAULT_CONFIG_PATH = "config.json"; //$NON-NLS-1$ + private static final String TEMP_CONFIG_PATH = "config_temp.json"; //$NON-NLS-1$ + + public static Config currentConfig; - private OsType currrentOs; + private OsType currentOs = getOperatingSystemType(); + private Version currentVersion = readCurrentVersion(); + private Version latestVersion; + private String latestVersionUrl; + // private File configFile; + private String configPath; private enum OsType { WINDOWS, @@ -112,608 +167,897 @@ private enum OsType { OTHER } + /** Constructor for main config. */ + public Config() { + // this.init(); + this.configPath = DEFAULT_CONFIG_PATH; + currentConfig = this; + } + + /** + * Constructor for config. + * + * @param configPath - путь к файлу конфига + */ + public Config(String configPath) { + this.configPath = configPath; + currentConfig = this; + } + + /** + * Constructor for main config. + * + * @param initFields - init fields + */ + // public Config(boolean initFields) { + // if (initFields) { + // this.init(); + // } + // } + + /** Init config. */ + public void init() { + runReadUpstreamVersion(); + } + + /** Миграция настроек из конфига предыдущей версии. */ + public void migrateProps() { + + if (configVersion == null) { + configVersion = "0.2.0"; + servers.forEach((key, server) -> server.migrateProps(configVersion)); + configVersion = currentVersion.toString(); + } + } + + private OsType getOperatingSystemType() { + OsType os = null; + String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); + LOGGER.debug("Current OS is <{}>", osName); //$NON-NLS-1$ + + if ((osName.indexOf("mac") >= 0) || (osName.indexOf("darwin") >= 0)) { + os = OsType.MACOS; + } else if (osName.indexOf("win") >= 0) { + os = OsType.WINDOWS; + } else if (osName.indexOf("nux") >= 0) { + os = OsType.LINUX; + } else { + os = OsType.OTHER; + } + return os; + } + + private Version readCurrentVersion() { + + // MavenXpp3Reader reader = new MavenXpp3Reader(); + // Model model; + // + // if ((new File("pom.xml")).exists()) { + // try { + // model = reader.read(new FileReader("pom.xml")); + // // model = + // reader.read(getClass().getResourceAsStream("/META-INF/maven/".concat("pom.xml"))); + // return Version.parse(model.getVersion()); + // + // } catch (IOException | XmlPullParserException e) { + // LOGGER.debug("Error parse current version"); //$NON-NLS-1$ + // } + // } else { + // LOGGER.debug("Pom-file not exist"); //$NON-NLS-1$ + // String v = ClusterAdminLibraryMain.class.getPackage().getImplementationVersion(); + // LOGGER.debug("PackageImplementationVersion {}", v); //$NON-NLS-1$ + // return Version.parse(v); + // } + + return Version.parse("0.3.0"); + } + + private void runReadUpstreamVersion() { + + if (!checkingUpdate) { + return; + } + + Display.getDefault() + .asyncExec( + new Runnable() { + + @Override + public void run() { + readUpstreamVersion(); + } + }); + } + + /** Узнать последнюю версию из релизов GitHub. */ + public void readUpstreamVersion() { + + // final URL url = new URL("https://api.github.com/repos/YanSergey/OneS_ClusterAdmin/tags"); + URL url; + HttpURLConnection conn; + try { + url = new URL("https://api.github.com/repos/YanSergey/OneS_ClusterAdmin/releases/latest"); + conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + } catch (IOException e) { + LOGGER.debug("Error getting a upstream version", e); //$NON-NLS-1$ + checkingUpdate = false; + return; + } + + final int connectionTimeout = 10000; + + conn.setRequestProperty("Content-Type", "application/json"); + conn.setConnectTimeout(connectionTimeout); + conn.setReadTimeout(connectionTimeout); + + StringBuilder result = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { + for (String line; (line = reader.readLine()) != null; ) { + result.append(line); + } + } catch (IOException e) { + LOGGER.debug("Error read github response", e); //$NON-NLS-1$ + checkingUpdate = false; + return; + } + + String versionsJsonString = result.toString(); + + // Считываем json + JSONObject jo = new JSONObject(versionsJsonString); + String lastTagName = jo.getString("tag_name"); + JSONArray assets = jo.getJSONArray("assets"); + + String currentOsString = ""; + switch (currentOs) { + case WINDOWS: + currentOsString = "windows"; + break; + case LINUX: + currentOsString = "linux"; + break; + case MACOS: + currentOsString = "macos"; + break; + default: + LOGGER.debug("Error get current OS"); //$NON-NLS-1$ + checkingUpdate = false; + return; + } + + String downloadUrl; + for (Object object : assets) { + downloadUrl = ((JSONObject) object).getString("browser_download_url"); + if (downloadUrl.contains(currentOsString)) { + latestVersionUrl = downloadUrl; + break; + } + } + // currentVersion.compareTo(Version.parse(lastTagName)) = 1 + // return Version.parse(lastTagName); + latestVersion = Version.parse("0.4.0"); // TODO del + } + + /** + * Запуск скачивания нового релиза. + * + * @param parentShell - parent shell + */ + public void runDownloadRelease(Shell parentShell) { + Display.getDefault() + .asyncExec( + new Runnable() { + + @Override + public void run() { + String fname = selectFileToSave(parentShell); + if (fname == null) { + return; + } + + if (downloadReleaseToFile(fname)) { + showDownloadedFile(fname); + } + } + }); + } + + private String selectFileToSave(Shell parentShell) { + + String[] filterNames = {"Исполняемые файлы Java (*.jar)"}; + String[] filterExt = {"*.jar"}; + + FileDialog dialog = new FileDialog(parentShell, SWT.SAVE); + dialog.setFileName(new File(latestVersionUrl).getName()); + dialog.setText("Укажите расположение и имя файла"); + dialog.setFilterNames(filterNames); + dialog.setFilterExtensions(filterExt); + + return dialog.open(); + } + + private boolean downloadReleaseToFile(String fname) { + // String link = downloadLatestVersionUrl; + String link = "https://speedtest.selectel.ru/10MB"; // TODO это для теста, удалить! + + try { + Request.Get(link).execute().saveContent(new File(fname)); + } catch (IOException e) { + e.printStackTrace(); + return false; + } + + return true; + } + + private void showDownloadedFile(String fname) { + if (Config.currentConfig.isWindows()) { + + final String command = "explorer.exe /select,\"" + new File(fname).getAbsolutePath() + "\""; + try { + Runtime.getRuntime().exec(command); + } catch (IOException e) { + e.printStackTrace(); + } + + } else { + + Desktop desktop = Desktop.getDesktop(); + desktop.browseFileDirectory(new File(fname)); + } + } + + /** + * Создание нового сервера. + * + * @return новый сервер + */ + public Server createNewServer() { + Server newServer = null; + + if (isReadClipboard()) { + Clipboard clipboard = new Clipboard(Display.getDefault()); + String clip = (String) clipboard.getContents(TextTransfer.getInstance()); + clipboard.dispose(); + + if (clip != null && clip.startsWith("Srvr=")) { //$NON-NLS-1$ + String[] srvrPart = clip.split(";"); //$NON-NLS-1$ + String srvr = srvrPart[0].substring(6, srvrPart[0].length() - 1); + newServer = new Server(srvr); + } else { + newServer = new Server("Server:1541"); //$NON-NLS-1$ + } + } else { + newServer = new Server("Server:1541"); //$NON-NLS-1$ + } + // servers.put(newServer.getServerKey(), newServer); + // TODO по идее еще рано добавлять в список серверов эту заготовку + return newServer; + } + + public void addNewServer(Server server) { + servers.put(server.getServerKey(), server); + saveConfig(); + } + + public void removeServer(Server server) { + servers.remove(server.getServerKey(), server); + saveConfig(); + } + + public void close() { + + saveConfig(); + + servers.forEach( + (serverKey, server) -> { + if (server.isConnected()) { + server.disconnectFromAgent(); + } + }); + } + + /** + * Добавление новых серверов в конфиг. + * + * @param newServers - список новых серверов + * @return список серверов, которые были реально добавлены + */ + public List addNewServers(List newServers) { + // Пакетное добавление серверов в список, предполагается для механизма импорта из списка + // информационных баз + + List addedServers = new ArrayList<>(); + + // Имя сервера, которое приходит сюда не равно Представлению сервера, выводимому в списке + // Имя сервера. оно же Key в map и json, строка вида Server:1541, с обязательным указанием порта + // менеджера, к которому подключаемся + // если порт менеджера не задан - ставим стандартный 1541 + // переделать + for (String serverName : newServers) { + if (!servers.containsKey(serverName)) { + Server serverConfig = new Server(serverName); + servers.put(serverName, serverConfig); + + addedServers.add(serverName); + } + } + + return addedServers; + } + + /** Подключиться ко всем серверам в тихом режиме. */ + public void connectAllServers() { + servers.forEach((serverKey, server) -> server.connectToServer(false, true)); + } + + /** Проверить доступность всех серверов в тихом режиме. */ + public void checkConnectionAllServers() { + servers.forEach((serverKey, server) -> server.connectToServer(true, true)); + } + /** - * Get servers. + * Проверять обновление при запуске. * - * @return the servers + * @return текущее значение + */ + public boolean checkingUpdate() { + return checkingUpdate; + } + + /** + * Установка проверки обновления при запуске. + * + * @param checkingUpdate - новое значение + */ + public void setCheckingUpdate(boolean checkingUpdate) { + this.checkingUpdate = checkingUpdate; + } + + /** + * Получает список зарегистрированных серверов. + * + * @return список серверов */ public Map getServers() { return servers; } /** - * Expand servers in tree. + * При подключении разворачивать узел сервера в дереве. * - * @return the expandServersTree + * @return значение разворачивать/не разворачивать */ public boolean isExpandServersTree() { return expandServersTree; } /** - * Set expand servers in tree. + * Установить разворачивание узла сервера в дереве при подключении. * - * @param expandServersTree the expandServersTree to set + * @param expand - true=разворачивать, false=не разворачивать */ - public void setExpandServersTree(boolean expandServersTree) { - this.expandServersTree = expandServersTree; + public void setExpandServersTree(boolean expand) { + this.expandServersTree = expand; } /** - * Expand clusters in tree. + * При подключении разворачивать узел кластера в дереве. * - * @return the expandClustersTree + * @return значение разворачивать/не разворачивать */ public boolean isExpandClustersTree() { return expandClustersTree; } /** - * Set expand clusters in tree. + * Установить разворачивание узла кластеров в дереве при подключении сервера. * - * @param expandClustersTree the expandClustersTree to set + * @param expand - true=разворачивать, false=не разворачивать */ - public void setExpandClustersTree(boolean expandClustersTree) { - this.expandClustersTree = expandClustersTree; + public void setExpandClustersTree(boolean expand) { + this.expandClustersTree = expand; } /** - * Expand infobases in tree. + * При подключении разворачивать узел инфобаз в дереве. * - * @return the expandInfobasesTree + * @return значение разворачивать/не разворачивать */ public boolean isExpandInfobasesTree() { return expandInfobasesTree; } /** - * Set expand infobases in tree. + * Установить разворачивание узла инфобаз в дереве при подключении сервера. * - * @param expandInfobasesTree the expandInfobasesTree to set + * @param expand - true=разворачивать, false=не разворачивать */ - public void setExpandInfobasesTree(boolean expandInfobasesTree) { - this.expandInfobasesTree = expandInfobasesTree; + public void setExpandInfobasesTree(boolean expand) { + this.expandInfobasesTree = expand; } /** - * Show working servers in tree. + * Показывать узел рабочих серверов в дереве. * - * @return the showWorkingServersTree + * @return значение */ public boolean isShowWorkingServersTree() { return showWorkingServersTree; } /** - * Set show working servers in tree. + * Установить показ узла рабочих серверов в дереве. * - * @param showWorkingServersTree the showWorkingServersTree to set + * @param show - значение показывать/не показывать */ - public void setShowWorkingServersTree(boolean showWorkingServersTree) { - this.showWorkingServersTree = showWorkingServersTree; + public void setShowWorkingServersTree(boolean show) { + this.showWorkingServersTree = show; } /** - * Expand working servers in tree. + * При подключении разворачивать узел рабочих серверов в дереве. * - * @return the expandWorkingServersTree + * @return значение разворачивать/не разворачивать */ public boolean isExpandWorkingServersTree() { return expandWorkingServersTree; } /** - * Set expand working servers in tree. + * Установить разворачивание узла рабочих серверов в дереве при подключении сервера. * - * @param expandWorkingServersTree the expandWorkingServersTree to set + * @param expand - true=разворачивать, false=не разворачивать */ - public void setExpandWorkingServersTree(boolean expandWorkingServersTree) { - this.expandWorkingServersTree = expandWorkingServersTree; + public void setExpandWorkingServersTree(boolean expand) { + this.expandWorkingServersTree = expand; } /** - * Show working processes in tree. + * Показывать узел рабочих процессов в дереве. * - * @return the showWorkingProcessesTree + * @return значение */ public boolean isShowWorkingProcessesTree() { return showWorkingProcessesTree; } /** - * Set show working processes in tree. + * Установить показ узла рабочих процессов в дереве. * - * @param showWorkingProcessesTree the showWorkingProcessesTree to set + * @param show - значение показывать/не показывать */ - public void setShowWorkingProcessesTree(boolean showWorkingProcessesTree) { - this.showWorkingProcessesTree = showWorkingProcessesTree; + public void setShowWorkingProcessesTree(boolean show) { + this.showWorkingProcessesTree = show; } /** - * Expand working processes in tree. + * При подключении разворачивать узел рабочих процессов в дереве. * - * @return the expandWorkingProcessesTree + * @return the значение разворачивать/не разворачивать */ public boolean isExpandWorkingProcessesTree() { return expandWorkingProcessesTree; } /** - * Set expand working processes in tree. + * Установить разворачивание узла рабочих процессов в дереве при подключении сервера. * - * @param expandWorkingProcessesTree the expandWorkingProcessesTree to set + * @param expand - true=разворачивать, false=не разворачивать */ - public void setExpandWorkingProcessesTree(boolean expandWorkingProcessesTree) { - this.expandWorkingProcessesTree = expandWorkingProcessesTree; + public void setExpandWorkingProcessesTree(boolean expand) { + this.expandWorkingProcessesTree = expand; } /** - * Show server description in tree. + * Показывать описание сервера в дереве. * - * @return the showServerDescription + * @return значение */ public boolean isShowServerDescription() { return showServerDescription; } /** - * Set show server description in tree. + * Установить показ описания сервера в дереве. * - * @param showServerDescription the showServerDescription to set + * @param show значение */ - public void setShowServerDescription(boolean showServerDescription) { - this.showServerDescription = showServerDescription; + public void setShowServerDescription(boolean show) { + this.showServerDescription = show; } /** - * Show server version in tree. + * Показывать версию сервера в дереве. * - * @return the showServerVersion + * @return значение */ public boolean isShowServerVersion() { return showServerVersion; } /** - * Set show server version in tree. + * Установить показ версии сервера в дереве. * - * @param showServerVersion the showServerVersion to set + * @param show значение */ - public void setShowServerVersion(boolean showServerVersion) { - this.showServerVersion = showServerVersion; + public void setShowServerVersion(boolean show) { + this.showServerVersion = show; } /** - * Show infobase description in tree. + * Показывать описание инфобазы в дереве. * - * @return the showInfobaseDescription + * @return значение */ public boolean isShowInfobaseDescription() { return showInfobaseDescription; } /** - * Set show infobase description in tree. + * Установить показ описания инфобазы в дереве. * - * @param showInfobaseDescription the showInfobaseDescription to set + * @param show значение */ - public void setShowInfobaseDescription(boolean showInfobaseDescription) { - this.showInfobaseDescription = showInfobaseDescription; + public void setShowInfobaseDescription(boolean show) { + this.showInfobaseDescription = show; } /** - * Show local-RAS connection info in tree. + * Показывать информацию в дереве, что сервер подключен через local-RAS. * - * @return the showLocalRasConnectInfo + * @return значение */ public boolean isShowLocalRasConnectInfo() { return showLocalRasConnectInfo; } /** - * Set show local-RAS connection info in tree. + * Установить показ информации в дереве, что сервер подключен через local-RAS. * - * @param showLocalRasConnectInfo the showLocalRasConnectInfo to set + * @param show значение */ - public void setShowLocalRasConnectInfo(boolean showLocalRasConnectInfo) { - this.showLocalRasConnectInfo = showLocalRasConnectInfo; + public void setShowLocalRasConnectInfo(boolean show) { + this.showLocalRasConnectInfo = show; } /** - * Get locale. + * Получить текущий язык приложения. * - * @return the locale + * @return текущий язык приложения */ public String getLocale() { return locale; } /** - * Set locale. + * Установить текущий язык приложения. * - * @param locale the locale to set + * @param locale - новый язык приложения */ public void setLocale(String locale) { this.locale = locale; } /** - * Get session column properties. + * Затенять спящие сеансы. * - * @return the sessionColumnProperties + * @return значение настройки */ - public ColumnProperties getSessionColumnProperties() { - return sessionColumnProperties; + public boolean isShadeSleepingSessions() { + return shadeSleepingSessions; } /** - * Get connection column properties. + * Устанавливает настройку "Затенять спящие сеансы". * - * @return the connectionColumnProperties + * @param shade - новое значение настройки */ - public ColumnProperties getConnectionColumnProperties() { - return connectionColumnProperties; + public void setShadowSleepSessions(boolean shade) { + this.shadeSleepingSessions = shade; } /** - * Get lock column properties. + * Подсвечивать новые строки в списках. * - * @return the lockColumnProperties + * @return значение настройки */ - public ColumnProperties getLockColumnProperties() { - return lockColumnProperties; + public boolean isHighlightNewItems() { + return highlightNewItems; } /** - * Get working processes column properties. + * Устанавливает настройку "Подсвечивать новые строки в списках". * - * @return the wpColumnProperties + * @param highlight - новое значение настройки */ - public ColumnProperties getWpColumnProperties() { - return wpColumnProperties; + public void setHighlightNewItems(boolean highlight) { + this.highlightNewItems = highlight; } /** - * Get working servers column properties. + * Получает длительность подсвечивания новых строк в списках. * - * @return the wsColumnProperties + * @return длительность подсветки */ - public ColumnProperties getWsColumnProperties() { - return wsColumnProperties; + public int getHighlightNewItemsDuration() { + return highlightNewItemsDuration; } /** - * Shadow sleep sessions. + * Устанавливает длительность подсвечивания новых строк в списках. * - * @return the shadowSleepSessions + * @param duration - новая длительность подсветки */ - public boolean isShadowSleepSessions() { - return shadowSleepSessions; + public void setHighlightNewItemsDuration(int duration) { + this.highlightNewItemsDuration = duration; } /** - * Set shadow sleep sessions. + * Читать бефер обмена. * - * @param shadowSleepSessions the shadowSleepSessions to set + * @return значение настройки */ - public void setShadowSleepSessions(boolean shadowSleepSessions) { - this.shadowSleepSessions = shadowSleepSessions; + public boolean isReadClipboard() { + return readClipboard; } /** - * Highlight new items in lists. + * Установка настройки "Читать бефер обмена". * - * @return the highlightNewItems + * @param read - новое значение настройки */ - public boolean isHighlightNewItems() { - return highlightNewItems; + public void setReadClipboard(boolean read) { + this.readClipboard = read; } /** - * Set highlight new items in lists. + * Получает настройку "Направление сортировки строк по-умолчанию". * - * @param highlightNewItems the highlightNewItems to set + * @return значение настройки */ - public void setHighlightNewItems(boolean highlightNewItems) { - this.highlightNewItems = highlightNewItems; + public RowSortDirection getRowSortDirection() { + return rowSortDirection; } /** - * Highlight new items duration. + * Устанавливает настройку "Направление сортировки строк по-умолчанию". * - * @return the highlightNewItemsDuration + * @param sortDirection - новое значение настройки */ - public int getHighlightNewItemsDuration() { - return highlightNewItemsDuration; + public void setRowSortDirection(RowSortDirection sortDirection) { + this.rowSortDirection = sortDirection; } /** - * Set highlight new items duration. + * Получает настройку "Направление сортировки инфобаз". * - * @param highlightNewItemsDuration the highlightNewItemsDuration to set + * @return значение настройки */ - public void setHighlightNewItemsDuration(int highlightNewItemsDuration) { - this.highlightNewItemsDuration = highlightNewItemsDuration; + public InfobasesSortDirection getInfobasesSortDirection() { + return infobasesSortDirection; } /** - * Read clipboard. + * Устанавливает настройку "Направление сортировки инфобаз". * - * @return the readClipboard + * @param sortDirection - новое значение настройки */ - public boolean isReadClipboard() { - return readClipboard; + public void setInfobasesSortDirection(InfobasesSortDirection sortDirection) { + this.infobasesSortDirection = sortDirection; } /** - * Set read clipboard. + * Получение свойства колонок списков. * - * @param readClipboard the readClipboard to set + * @param clazz - имя класса, идентифицирующее список-кладелец колонок + * @return ColumnProperties - свойства колонок списка */ - public void setReadClipboard(boolean readClipboard) { - this.readClipboard = readClipboard; - } - - /** Constructor for main config. */ - public Config() { - this.init(); - } - - /** Init config. */ - public void init() { - getOperatingSystemType(); - - this.servers.forEach( - (key, server) -> { - server.init(); - }); - } - - private void getOperatingSystemType() { - if (currrentOs == null) { - String osName = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); - LOGGER.debug("Current OS is <{}>", osName); //$NON-NLS-1$ - - if ((osName.indexOf("mac") >= 0) || (osName.indexOf("darwin") >= 0)) { - currrentOs = OsType.MACOS; - } else if (osName.indexOf("win") >= 0) { - currrentOs = OsType.WINDOWS; - } else if (osName.indexOf("nux") >= 0) { - currrentOs = OsType.LINUX; - } else { - currrentOs = OsType.OTHER; - } + public ColumnProperties getColumnsProperties(Class clazz) { + if (clazz == SessionInfoExtended.class) { + return sessionColumnProperties; + } else if (clazz == ConnectionInfoExtended.class) { + return connectionColumnProperties; + } else if (clazz == LockInfoExtended.class) { + return lockColumnProperties; + } else if (clazz == WorkingProcessInfoExtended.class) { + return wpColumnProperties; + } else if (clazz == WorkingServerInfoExtended.class) { + return wsColumnProperties; + } else { + return null; } } /** - * Add new servers in main config. + * Установка порядка колонок списков по имени класса. * - * @param servers - list of servers - * @return list of servers + * @param clazz - имя класса, идентифицирующее список-кладелец колонок + * @param columnOrder - новый порядок колонок */ - public List addNewServers(List servers) { - // Пакетное добавление серверов в список, предполагается для механизма импорта из списка - // информационных баз - - List addedServers = new ArrayList<>(); - - // Имя сервера, которое приходит сюда не равно Представлению сервера, выводимому в списке - // Имя сервера. оно же Key в map и json, строка вида Server:1541, с обязательным указанием порта - // менеджера, к которому подключаемся - // если порт менеджера не задан - ставим стандартный 1541 - // переделать - for (String serverName : servers) { - if (!this.servers.containsKey(serverName)) { - Server serverConfig = new Server(serverName); - this.servers.put(serverName, serverConfig); - - addedServers.add(serverName); - } - } - - return addedServers; + public void setColumnsOrder(Class clazz, int[] columnOrder) { + getColumnsProperties(clazz).setOrder(columnOrder); } - /** Connect to all servers in silent mode. */ - public void connectAllServers() { - servers.forEach((serverKey, server) -> server.connectToServer(false, true)); - } - - /** Check connection to all servers in silent mode. */ - public void checkConnectionAllServers() { - servers.forEach((serverKey, server) -> server.connectToServer(true, true)); + /** + * Установка ширины колонок списков по имени класса. + * + * @param clazz - имя класса, идентифицирующее список-кладелец колонок + * @param index - индекс колонки + * @param width - ширина колонки + */ + public void setColumnsWidth(Class clazz, int index, int width) { + getColumnsProperties(clazz).setWidth(index, width); } /** - * Is Windows. + * Это ОС Windows. * - * @return true is Windows + * @return true если Windows */ public boolean isWindows() { - return currrentOs == OsType.WINDOWS; + return currentOs == OsType.WINDOWS; } /** - * Is Linux. + * Это ОС Linux. * - * @return true is Linux + * @return true если Linux */ public boolean isLinux() { - return currrentOs == OsType.LINUX; + return currentOs == OsType.LINUX; } /** - * Is MacOs. + * Это ОС MacOs. * - * @return true is MacOs + * @return true если MacOs */ public boolean isMacOs() { - return currrentOs == OsType.MACOS; + return currentOs == OsType.MACOS; } /** - * Set sessions column order. + * Возвращает текущую версию приложения. * - * @param columnOrder - new column order + * @return Version */ - public void setSessionsColumnOrder(int[] columnOrder) { - sessionColumnProperties.setOrder(columnOrder); + public Version getCurrentVersion() { + return currentVersion; } /** - * Set connection column order. + * Возвращает последнюю версию приложения с релизов GitHub. * - * @param columnOrder - new column order + * @return Version или null, если запрос не выполнялся или завершился ошибкой */ - public void setConnectionsColumnOrder(int[] columnOrder) { - connectionColumnProperties.setOrder(columnOrder); + public Version getLatestVersion() { + return latestVersion; } /** - * Set lock column order. + * Возвращает путь к файлу конфига. * - * @param columnOrder - new column order + * @return строка с путем к файлу конфига */ - public void setLocksColumnOrder(int[] columnOrder) { - lockColumnProperties.setOrder(columnOrder); + public String getConfigPath() { + return configPath; } /** - * Set working processes column order. + * Устанавливает путь к файлу конфига. * - * @param columnOrder - new column order + * @param configPath - строка с путем к файлу конфига */ - public void setWorkingProcessesColumnOrder(int[] columnOrder) { - wpColumnProperties.setOrder(columnOrder); + public void setConfigPath(String configPath) { + this.configPath = configPath; } /** - * Set working servers column order. + * Читает конфиг из файла по-умолчанию. * - * @param columnOrder - new column order + * @return ссылка на прочитанный конфиг */ - public void setWorkingServersColumnOrder(int[] columnOrder) { - wsColumnProperties.setOrder(columnOrder); + public static Config readConfig() { + return readConfig(DEFAULT_CONFIG_PATH); } /** - * Init sessions column count. + * Читает конфиг из определенного файла. * - * @param columnCount - new column count + * @param configPath - имя конфиг файла + * @return объект конфига */ - public void initSessionsColumnCount(int columnCount) { - - if (sessionColumnProperties == null) { - sessionColumnProperties = new ColumnProperties(columnCount); - } else { - sessionColumnProperties.updateColumnProperties(columnCount); + public static Config readConfig(String configPath) { + if (configPath == null || configPath.isBlank()) { + LOGGER.debug("Config path is empty, set config path in root folder"); //$NON-NLS-1$ + configPath = DEFAULT_CONFIG_PATH; } - } + LOGGER.info("Start read config from file <{}>", configPath); //$NON-NLS-1$ - /** - * Init connection column count. - * - * @param columnCount - new column count - */ - public void initConnectionsColumnCount(int columnCount) { - - if (connectionColumnProperties == null) { - connectionColumnProperties = new ColumnProperties(columnCount); - } else { - connectionColumnProperties.updateColumnProperties(columnCount); + File configFile = new File(configPath); + if (!configFile.exists()) { + LOGGER.debug( + "Config file not exists, create new config in folder <{}>", configPath); //$NON-NLS-1$ + return new Config(configPath); } - } - /** - * Init lock column count. - * - * @param columnCount - new column count - */ - public void initLocksColumnCount(int columnCount) { - - if (lockColumnProperties == null) { - lockColumnProperties = new ColumnProperties(columnCount); - } else { - lockColumnProperties.updateColumnProperties(columnCount); + JsonReader jsonReader = null; + + try { + jsonReader = + new JsonReader( + new InputStreamReader(new FileInputStream(configFile), StandardCharsets.UTF_8)); + } catch (FileNotFoundException excp) { + LOGGER.debug("Config file read error:", excp); //$NON-NLS-1$ + LOGGER.debug("Create temp config in root folder"); //$NON-NLS-1$ + // configFile = new File(TEMP_CONFIG_PATH); + return new Config(TEMP_CONFIG_PATH); } - } - - /** - * Init working processes column count. - * - * @param columnCount - new column count - */ - public void initWorkingProcessesColumnCount(int columnCount) { - - if (wpColumnProperties == null) { - wpColumnProperties = new ColumnProperties(columnCount); - } else { - wpColumnProperties.updateColumnProperties(columnCount); + Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); + + Config config = null; + try { + config = gson.fromJson(jsonReader, Config.class); + } catch (Exception excp) { + LOGGER.debug("error convert config from json:", excp); //$NON-NLS-1$ + LOGGER.debug("Create temp config in root folder"); //$NON-NLS-1$ + // configFile = new File(TEMP_CONFIG_PATH); + return new Config(TEMP_CONFIG_PATH); } - } - - /** - * Init working servers column count. - * - * @param columnCount - new column count - */ - public void initWorkingServersColumnCount(int columnCount) { - if (wsColumnProperties == null) { - wsColumnProperties = new ColumnProperties(columnCount); + if (config == null) { + LOGGER.debug("the config is null after reading the json"); //$NON-NLS-1$ + LOGGER.debug("Create temp config in root folder"); //$NON-NLS-1$ + // configFile = new File(TEMP_CONFIG_PATH); + config = new Config(TEMP_CONFIG_PATH); } else { - wsColumnProperties.updateColumnProperties(columnCount); + + config.setConfigPath(configPath); + config.migrateProps(); + config.init(); + if (config.getLocale() != null) { + LOGGER.debug("Set locale is <{}>", config.getLocale()); //$NON-NLS-1$ + Locale locale = Locale.forLanguageTag(config.getLocale()); + java.util.Locale.setDefault(locale); + Messages.reloadBundle(locale); // TODO не совсем понятно как работает + } } + LOGGER.info("Config file read successfully"); //$NON-NLS-1$ + return config; } - /** - * Set sessions column width. - * - * @param index - index of column - * @param width - column width - */ - public void setSessionsColumnWidth(int index, int width) { - sessionColumnProperties.setWidth(index, width); - } + /** Сохранение конфига в файл. */ + public void saveConfig() { - /** - * Set connection column width. - * - * @param index - index of column - * @param width - column width - */ - public void setConnectionsColumnWidth(int index, int width) { - connectionColumnProperties.setWidth(index, width); - } + LOGGER.info("Start save config to file <{}>", configPath); //$NON-NLS-1$ - /** - * Set lock column width. - * - * @param index - index of column - * @param width - column width - */ - public void setLocksColumnWidth(int index, int width) { - lockColumnProperties.setWidth(index, width); - } + // configFile = new File(configPath); - /** - * Set working processes column width. - * - * @param index - index of column - * @param width - column width - */ - public void setWorkingProcessesColumnWidth(int index, int width) { - wpColumnProperties.setWidth(index, width); - } + JsonWriter jsonWriter; + try { + jsonWriter = + new JsonWriter( + new OutputStreamWriter(new FileOutputStream(configPath), StandardCharsets.UTF_8)); + } catch (FileNotFoundException excp) { + LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + return; + } + Gson gson = + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); + try { + gson.toJson(this, this.getClass(), jsonWriter); + } catch (JsonIOException excp) { + LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + } - /** - * Set working servers column width. - * - * @param index - index of column - * @param width - column width - */ - public void setWorkingServersColumnWidth(int index, int width) { - wsColumnProperties.setWidth(index, width); + try { + jsonWriter.close(); + } catch (IOException excp) { + LOGGER.error("Config file save error:", excp); //$NON-NLS-1$ + } + LOGGER.info("Config file write successfully"); //$NON-NLS-1$ } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java index cbff728..7ceaa54 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/ConnectionInfoExtended.java @@ -2,125 +2,143 @@ import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; import com._1c.v8.ibis.admin.IWorkingProcessInfo; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import java.util.UUID; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import ru.yanygin.clusterAdminLibrary.CellValue.CELL_VALUE_TYPE; -/** Extend info for connection. */ -public class ConnectionInfoExtended implements IInfoExtended { - - private static final String TITLE_INFOBASE = - Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ - private static final String TITLE_CONNECTION = - Messages.getString("ConnectionInfo.Connection"); //$NON-NLS-1$ - private static final String TITLE_SESSION = - Messages.getString("ConnectionInfo.Session"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = - Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_APPLICATION = - Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ - private static final String TITLE_SERVER = - Messages.getString("SessionInfo.Server"); //$NON-NLS-1$ - private static final String TITLE_RP_HOST_PORT = - Messages.getString("ConnectionInfo.RpHostPort"); //$NON-NLS-1$ - private static final String TITLE_CONNECTED_AT = - Messages.getString("ConnectionInfo.ConnectedAt"); //$NON-NLS-1$ - // private static final String TITLE_INFOBASE_CONNECTION_ID = - // Messages.getString("ConnectionInfo.InfobaseConnectionID"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - UUID infobaseId; - IInfoBaseConnectionShort connectionInfo; - List workingProcesses; - - Map columnsMap = new LinkedHashMap<>(); +/** Расширенная информация для соединения. */ +public class ConnectionInfoExtended extends BaseInfoExtended { + + private static final String TITLE_INFOBASE = "SessionInfo.Infobase"; //$NON-NLS-1$ + private static final String TITLE_CONNECTION = "ConnectionInfo.Connection"; //$NON-NLS-1$ + private static final String TITLE_SESSION = "ConnectionInfo.Session"; //$NON-NLS-1$ + private static final String TITLE_COMPUTER = "SessionInfo.Computer"; //$NON-NLS-1$ + private static final String TITLE_APPLICATION = "SessionInfo.Application"; //$NON-NLS-1$ + private static final String TITLE_SERVER = "SessionInfo.Server"; //$NON-NLS-1$ + private static final String TITLE_RP_HOST_PORT = "ConnectionInfo.RpHostPort"; //$NON-NLS-1$ + private static final String TITLE_CONNECTED_AT = "ConnectionInfo.ConnectedAt"; //$NON-NLS-1$ + + private static Config commonConfig = Config.currentConfig; + private static ColumnProperties columnProperties = + commonConfig.getColumnsProperties(ConnectionInfoExtended.class); + + private static final String DEFAULT_ICON_FILENAME = "connection.png"; + private static Image defaultIcon; + + private static final String TAB_TEXT_TEMPLATE = + Messages.getString("TabText.ConnectionsCount"); //$NON-NLS-1$ + + private static TabItem currentTab; + private static int itemCount; + + private IInfoBaseConnectionShort connectionInfo; /** - * Create extended info for working server. + * Создание расширенной информации для соединения. * * @param server - server * @param clusterId - cluster ID - * @param infobaseId - infobase ID * @param connectionInfo - connection info - * @param workingProcesses - working process info - * @param columnsMap - columns map */ public ConnectionInfoExtended( - Server server, - UUID clusterId, - UUID infobaseId, - IInfoBaseConnectionShort connectionInfo, - List workingProcesses, - Map columnsMap) { + Server server, UUID clusterId, IInfoBaseConnectionShort connectionInfo) { this.server = server; this.clusterId = clusterId; - this.infobaseId = infobaseId; this.connectionInfo = connectionInfo; - this.workingProcesses = workingProcesses; - this.columnsMap = columnsMap; + this.currentIcon = defaultIcon; + + computeExtendedInfoData(); + } + + protected void computeExtendedInfoData() { + + String infobaseName = ""; //$NON-NLS-1$ + String wpHostName = ""; //$NON-NLS-1$ + String wpPort = ""; //$NON-NLS-1$ + + if (!connectionInfo.getInfoBaseId().equals(Helper.EMPTY_UUID)) { + infobaseName = server.getInfoBaseName(clusterId, connectionInfo.getInfoBaseId()); + } + + IWorkingProcessInfo workingProcess = + server.getWorkingProcessInfo(clusterId, connectionInfo.getWorkingProcessId()); + + if (workingProcess != null) { + wpHostName = workingProcess.getHostName(); + wpPort = Integer.toString(workingProcess.getMainPort()); + } + + columnProperties.prepareDataMap(data); + + putData(TITLE_INFOBASE, infobaseName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_CONNECTION, connectionInfo.getConnId(), CELL_VALUE_TYPE.INT); + putData(TITLE_SESSION, connectionInfo.getSessionNumber(), CELL_VALUE_TYPE.INT); + putData(TITLE_COMPUTER, connectionInfo.getHost(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_APPLICATION, getApplicationName(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_SERVER, wpHostName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_RP_HOST_PORT, wpPort, CELL_VALUE_TYPE.TEXT); + putData(TITLE_CONNECTED_AT, connectionInfo.getConnectedAt(), CELL_VALUE_TYPE.DATE); + + } + + @Override + public void addToTable(Table table, int index) { + createTableItem(table, index, connectionInfo.getConnectedAt()); } /** - * Init columns name. + * Получение ConnectionInfo. * - * @param columnsMap - sample map with columns name + * @return the ConnectionInfo */ - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SESSION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SERVER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_RP_HOST_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTED_AT, ""); //$NON-NLS-1$ - // connectionColumnsMap.put(TITLE_INFOBASE_CONNECTION_ID, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initConnectionsColumnCount(columnsMap.size()); + public IInfoBaseConnectionShort getConnectionInfo() { + return connectionInfo; } - @Override - public String[] getExtendedInfo() { - - String infobaseName = ""; //$NON-NLS-1$ - if (infobaseId == null && !connectionInfo.getInfoBaseId().equals(emptyUuid)) { - infobaseId = connectionInfo.getInfoBaseId(); - infobaseName = server.getInfoBaseName(clusterId, infobaseId); - } + private String getApplicationName() { + return server.getApplicationName(connectionInfo.getApplication()); + } - String[] currentWorkingProcessInfo = - getWorkingProcessInfo(connectionInfo.getWorkingProcessId()); + /** Инициализация имен колонок. */ + protected static void initColumnsName() { - Map session = new LinkedHashMap<>(); - session.putAll(columnsMap); + columnProperties.addColumnsInMap( + TITLE_INFOBASE, + TITLE_CONNECTION, + TITLE_SESSION, + TITLE_COMPUTER, + TITLE_APPLICATION, + TITLE_SERVER, + TITLE_RP_HOST_PORT, + TITLE_CONNECTED_AT); - session.put(TITLE_INFOBASE, infobaseName); - session.put(TITLE_CONNECTION, Integer.toString(connectionInfo.getConnId())); - session.put(TITLE_SESSION, Integer.toString(connectionInfo.getSessionNumber())); - session.put(TITLE_COMPUTER, connectionInfo.getHost()); - session.put(TITLE_APPLICATION, server.getApplicationName(connectionInfo.getApplication())); - session.put(TITLE_SERVER, currentWorkingProcessInfo[0]); //$NON-NLS-1$ - session.put(TITLE_RP_HOST_PORT, currentWorkingProcessInfo[1]); - session.put(TITLE_CONNECTED_AT, dateToString(connectionInfo.getConnectedAt())); - // session.put(TITLE_INFOBASE_CONNECTION_ID, - // convertUuidToString(connectionInfo.getInfoBaseConnectionId())); + defaultIcon = Helper.getImage(DEFAULT_ICON_FILENAME); + } - return session.values().toArray(new String[0]); + /** + * Обновление заголовка вкладки. + * + * @param count - количество элементов + */ + protected static void updateTabText(int count) { + itemCount = count; + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount)); } - private String[] getWorkingProcessInfo(UUID workingProcessId) { + /** Сброс заголовка вкладки на неизвестное количество элементов. */ + protected static void resetTabTextCount() { + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount + "*")); + } - for (IWorkingProcessInfo workingProcess : workingProcesses) { - if (workingProcess.getWorkingProcessId().equals(workingProcessId)) { - return new String[] { - workingProcess.getHostName(), Integer.toString(workingProcess.getMainPort()) - }; - } - } - return new String[] {"", ""}; + /** + * Установка связи с вкладкой TabItem. + * + * @param tabitem вкладка Tabitem + */ + protected static void linkTabItem(TabItem tabitem) { + currentTab = tabitem; } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Helper.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Helper.java new file mode 100644 index 0000000..50223a8 --- /dev/null +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Helper.java @@ -0,0 +1,206 @@ +package ru.yanygin.clusterAdminLibrary; + +import java.io.File; +import java.io.FilenameFilter; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.MessageBox; +import org.eclipse.wb.swt.SWTResourceManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Helper class. */ +public class Helper { + + private static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ + + /** Пустой UUID. */ + public static final UUID EMPTY_UUID = + UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ + + private Helper() {} + + /** + * Получает картинку из ресурсов. + * + * @param name - имя картинки + * @return Image + */ + public static Image getImage(String name) { + return new Image( + Display.getCurrent(), + Helper.class.getResourceAsStream("/icons/".concat(name))); //$NON-NLS-1$ + } + + /** + * Показывает окно с сообщение пользователю. + * + * @param message - текст сообщения + */ + public static void showMessageBox(String message) { + MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(message); + messageBox.open(); + } + + /** + * Показывает диалог с вопросом и вариантами ответа ДА | НЕТ. + * + * @param question - текст вопроса + * @return выбранный ответ + */ + public static int showQuestionBox(String question) { + var messageBox = + new MessageBox(Display.getDefault().getActiveShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); + messageBox.setMessage(question); + + return messageBox.open(); + } + + /** + * Возвращает список установленных версий платформы V8. + * + * @param config - конфиг программы + * @return список установленных версий платформы V8 + */ + public static Map getInstalledV8Versions() { + LOGGER.debug("Get installed v8 platform versions"); //$NON-NLS-1$ + + Map versions = new HashMap<>(); + + if (!Config.currentConfig.isWindows()) { + return versions; + } + + File v8x64CommonPath = new File("C:\\Program Files\\1cv8"); //$NON-NLS-1$ + File v8x86CommonPath = new File("C:\\Program Files (x86)\\1cv8"); //$NON-NLS-1$ + + FilenameFilter filter = + new FilenameFilter() { + @Override + public boolean accept(File f, String name) { + return name.matches("8.3.\\d\\d.\\d{4}"); //$NON-NLS-1$ + } + }; + + try { + if (v8x64CommonPath.exists()) { + File[] v8x64dirs = v8x64CommonPath.listFiles(filter); + for (File dir : v8x64dirs) { + if (dir.isDirectory()) { + File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ + if (ras.exists() && ras.isFile()) { + versions.put(dir.getName().concat(" (x86_64)"), ras.getAbsolutePath()); //$NON-NLS-1$ + } + } + } + } + } catch (Exception excp) { + LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ + } + + try { + if (v8x86CommonPath.exists()) { + File[] v8x86dirs = v8x86CommonPath.listFiles(filter); + for (File dir : v8x86dirs) { + if (dir.isDirectory()) { + File ras = new File(dir.getAbsolutePath().concat("\\bin\\ras.exe")); //$NON-NLS-1$ + if (ras.exists() && ras.isFile()) { + versions.put(dir.getName(), ras.getAbsolutePath()); //$NON-NLS-1$ + } + } + } + } + } catch (Exception excp) { + LOGGER.error("Error read dir <{}>", v8x64CommonPath.getAbsolutePath(), excp); //$NON-NLS-1$ + } + + return versions; + } + + /** + * Получает белый цвет. + * + * @return Color(255, 255, 255) + */ + public static Color getWhiteColor() { + return SWTResourceManager.getColor(255, 255, 255); + } + + /** + * Получает розовый цвет. + * + * @return Color(255, 204, 204) + */ + public static Color getPinkColor() { + return SWTResourceManager.getColor(255, 204, 204); + } + + /** + * Получает светло-зеленый цвет. + * + * @return Color(128, 255, 128) + */ + public static Color getLightGreenColor() { + return SWTResourceManager.getColor(128, 255, 128); + } + + /** + * Получает красный цвет. + * + * @return Color(255, 0, 0) + */ + public static Color getRedColor() { + return SWTResourceManager.getColor(255, 0, 0); + } + + /** + * Получает красный цвет. + * + * @return Color(190, 0, 30) + */ + public static Color getDarkRedColor() { + return SWTResourceManager.getColor(190, 0, 30); + } + + /** + * Получает черный цвет. + * + * @return Color(0, 0, 0) + */ + public static Color getBlackColor() { + return new Color(0, 0, 0); + } + + /** + * Получает синий цвет. + * + * @return Color(0, 0, 255) + */ + public static Color getBlueColor() { + return new Color(0, 0, 255); + } + + /** + * Получает синий цвет. + * + * @return Color(255, 128, 64) + */ + public static Color getOrangeColor() { + return new Color(255, 128, 64); + } + + /** + * Получает синий цвет. + * + * @return Color(0, 128, 128) + */ + public static Color getTurquoiseColor() { + return new Color(0, 128, 128); + } +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java deleted file mode 100644 index e0b3a79..0000000 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/IInfoExtended.java +++ /dev/null @@ -1,134 +0,0 @@ -package ru.yanygin.clusterAdminLibrary; - -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.UUID; - -/** Extend info. */ -public interface IInfoExtended { - - UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ - DecimalFormat dFLong = new DecimalFormat("###,###"); //$NON-NLS-1$ - DecimalFormat dFDouble6 = new DecimalFormat("#,##0.000000"); //$NON-NLS-1$ - DecimalFormat dFDouble3 = new DecimalFormat("###,##0.000"); //$NON-NLS-1$ - - // NumberFormat fmt = NumberFormat.getInstance(); - // fmt.setGroupingUsed(false); - // fmt.setMaximumIntegerDigits(999); - // fmt.setMaximumFractionDigits(999); - - /** - * Init columns name. - * - * @param columnsMap - sample map with columns name - */ - public static void initColumnsName(Map columnsMap) {} - - /** - * Check highlight for new item in list. - * - * @param startDateItem - date of start - * @return true if need highlight - */ - public static boolean highlightItem(Date startDateItem) { - - Config commonConfig = ClusterProvider.getCommonConfig(); - return commonConfig.isHighlightNewItems() - && (new Date().getTime() - startDateItem.getTime() - < commonConfig.getHighlightNewItemsDuration() * 1000); - } - - /** - * Get extended info. - * - * @return extended info - */ - public String[] getExtendedInfo(); - - /** - * Convert UUID to string. - * - * @param uuid - UUID - * @return string - */ - default String convertUuidToString(UUID uuid) { - return uuid.equals(emptyUuid) ? "" : uuid.toString(); //$NON-NLS-1$ - } - - /** - * Cast date to string. - * - * @param date - date - * @return date format to string - */ - default String dateToString(Date date) { - - DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); //$NON-NLS-1$ - Date emptyDate = new Date(0); - - return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ - } - - /** - * Cast millisecond to string. - * - * @param value - millisecond - * @return millisecond to string - */ - default String millisecondToString(int value) { - return Double.toString(((double) value) / 1000); - } - - /** - * Cast millisecond to string. - * - * @param value - millisecond - * @return millisecond to string - */ - default String millisecondToString(long value) { - return Double.toString(((double) value) / 1000); - } - - /** - * Cast long value to string. - * - * @param value - long value - * @return long value to string - */ - default String longToStringGroup(long value) { - return dFLong.format(value); - } - - /** - * Cast double value to string. - * - * @param value - double value - * @return double value to string - */ - default String double6ToString(double value) { - return dFDouble6.format(value); - } - - /** - * Cast double value to string. - * - * @param value - double value - * @return double value to string - */ - default String double3ToString(double value) { - return dFDouble3.format((double) value / 1000); - } - - /** - * Cast double value to string. - * - * @param value - double value - * @return double value to string - */ - default String doubleToString1(double value) { - return String.format("%.9f", value); - } -} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/InfoBaseInfoShortExt.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/InfoBaseInfoShortExt.java new file mode 100644 index 0000000..ac6aa15 --- /dev/null +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/InfoBaseInfoShortExt.java @@ -0,0 +1,141 @@ +package ru.yanygin.clusterAdminLibrary; + +import com._1c.v8.ibis.admin.IInfoBaseInfoShort; +import com._1c.v8.ibis.admin.InfoBaseInfoShort; +import java.text.Collator; +import java.util.Locale; +import org.eclipse.swt.graphics.Image; + +/** Класс расширяет возможности InfoBaseInfoShort. */ +public class InfoBaseInfoShortExt extends InfoBaseInfoShort + implements Comparable { + + private static final String DEFAULT_ICON_FILENAME = "infobase.png"; //$NON-NLS-1$ + private static final String FAVORITE_ICON_FILENAME = "infobase_favorite.png"; //$NON-NLS-1$ + private static Image defaultIcon = Helper.getImage(DEFAULT_ICON_FILENAME); + private static Image favoriteIcon = Helper.getImage(FAVORITE_ICON_FILENAME); + + static final String INFOBASE_ID = "InfobaseId"; //$NON-NLS-1$ + static final String INFOBASE_INFO_SHORT_EXT = "InfobaseInfoShortExt"; //$NON-NLS-1$ + + int index = 0; + boolean isFavorite = false; + Image currentIcon; // protected + + /** + * Возвращает порядковый номер инфобазы из кластера. + * + * @return the index + */ + public int getIndex() { + return index; + } + + /** + * Устанавливает порядковый номер инфобазы из кластера. + * + * @param index - индекс + */ + public void setIndex(int index) { + this.index = index; + } + + /** + * Возвращает находится ли инфобаза в списке избранных. + * + * @return the isFavorite + */ + public boolean isFavorite() { + return isFavorite; + } + + /** + * Возвращает иконку инфобазы. + * + * @return Image currentIcon + */ + public Image getIcon() { + return currentIcon; + } + + /** + * Устанавливает признак избранной инфобазы. + * + * @param isFavorite - текущее состояние + */ + public void setFavoriteState(boolean isFavorite) { + this.isFavorite = isFavorite; + this.currentIcon = isFavorite ? favoriteIcon : defaultIcon; + } + + /** + * Создает класс краткое (расширенное) описание инфобазыю. + * + * @param ib - краткое описание инфобазы + * @param index - порядковый номер инфобазы из кластера + * @param isFavorite - инфобаза в избранном + */ + public InfoBaseInfoShortExt(IInfoBaseInfoShort ib, int index, boolean isFavorite) { + super(ib.getInfoBaseId()); + this.setDescr(ib.getDescr()); + this.setName(ib.getName()); + this.index = index; + this.isFavorite = isFavorite; + this.currentIcon = isFavorite ? favoriteIcon : defaultIcon; + } + + /** Направление сортировки инфобаз. */ + public enum InfobasesSortDirection { + /** Выключено. */ + DISABLE, + /** По имени. */ + BY_NAME, + /** По избранноми и имени. */ + BY_FAVORITES_AND_NAME + } + + @Override + public int compareTo(InfoBaseInfoShortExt o) { + + InfobasesSortDirection sortDirection = Config.currentConfig.getInfobasesSortDirection(); + Collator collator = Collator.getInstance(Locale.getDefault()); + + int compareResult = 0; + switch (sortDirection) { + case BY_NAME: + compareResult = collator.compare(getName(), o.getName()); + break; + case BY_FAVORITES_AND_NAME: + compareResult = Boolean.compare(o.isFavorite, isFavorite()); + if (compareResult == 0) { + compareResult = collator.compare(getName(), o.getName()); + } + break; + + case DISABLE: + compareResult = Integer.compare(index, o.index); + break; + + default: + return 0; + } + + return compareResult; + } + + /** + * Получение названия инфобазы для дерева. + * + * @return названия инфобазы для дерева + */ + public String getInfobaseDescription() { + String infobaseTitle; + if (Config.currentConfig.isShowInfobaseDescription() && !getDescr().isBlank()) { + infobaseTitle = String.format("%s (%s)", getName(), getDescr()); //$NON-NLS-1$ + } else { + infobaseTitle = String.format("%s", getName()); //$NON-NLS-1$ + } + return infobaseTitle; + } + +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java index 3465a45..7e09b4c 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/LockInfoExtended.java @@ -4,92 +4,63 @@ import com._1c.v8.ibis.admin.IObjectLockInfo; import com._1c.v8.ibis.admin.ISessionInfo; import com._1c.v8.ibis.admin.IWorkingProcessInfo; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.UUID; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import ru.yanygin.clusterAdminLibrary.CellValue.CELL_VALUE_TYPE; -/** Extend info for lock. */ -public class LockInfoExtended implements IInfoExtended { - - private static final String TITLE_DESCRIPTION = - Messages.getString("InfoTables.Description"); //$NON-NLS-1$ - private static final String TITLE_INFOBASE = - Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ - private static final String TITLE_CONNECTION = - Messages.getString("ConnectionInfo.Connection"); //$NON-NLS-1$ - private static final String TITLE_SESSION = - Messages.getString("ConnectionInfo.Session"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = - Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_APPLICATION = - Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ - private static final String TITLE_HOSTNAME = - Messages.getString("ConnectionInfo.Hostname"); //$NON-NLS-1$ - private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ - private static final String TITLE_LOCKED_AT = - Messages.getString("LockInfo.LockedAt"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - UUID infobaseId; - IObjectLockInfo lockInfo; - List sessionsInfo; - List connections; - - Map columnsMap = new LinkedHashMap<>(); +/** Расширенная информация для блокировки. */ +public class LockInfoExtended extends BaseInfoExtended { + + private static final String TITLE_DESCRIPTION = "InfoTables.Description"; //$NON-NLS-1$ + private static final String TITLE_INFOBASE = "SessionInfo.Infobase"; //$NON-NLS-1$ + private static final String TITLE_CONNECTION = "ConnectionInfo.Connection"; //$NON-NLS-1$ + private static final String TITLE_SESSION = "ConnectionInfo.Session"; //$NON-NLS-1$ + private static final String TITLE_COMPUTER = "SessionInfo.Computer"; //$NON-NLS-1$ + private static final String TITLE_APPLICATION = "SessionInfo.Application"; //$NON-NLS-1$ + private static final String TITLE_HOSTNAME = "ConnectionInfo.Hostname"; //$NON-NLS-1$ + private static final String TITLE_PORT = "SessionInfo.Port"; //$NON-NLS-1$ + private static final String TITLE_LOCKED_AT = "LockInfo.LockedAt"; //$NON-NLS-1$ + + private static Config commonConfig = Config.currentConfig; + private static ColumnProperties columnProperties = + commonConfig.getColumnsProperties(LockInfoExtended.class); + + private static final String DEFAULT_ICON_FILENAME = "lock_16.png"; + private static Image defaultIcon; + + private static final String TAB_TEXT_TEMPLATE = + Messages.getString("TabText.LocksCount"); //$NON-NLS-1$ + + private static TabItem currentTab; + private static int itemCount; + + private IObjectLockInfo lockInfo; + private List sessionsInfo; + private List connections; /** - * Create extended info for working server. + * Создание расширенной информации для блокировки. * * @param server - server * @param clusterId - cluster ID - * @param infobaseId - infobase ID * @param lockInfo - lock info - * @param sessionsInfo - sessions info - * @param connections - list of connections - * @param columnsMap - columns map */ - public LockInfoExtended( - Server server, - UUID clusterId, - UUID infobaseId, - IObjectLockInfo lockInfo, - List sessionsInfo, - List connections, - Map columnsMap) { + public LockInfoExtended(Server server, UUID clusterId, IObjectLockInfo lockInfo) { this.server = server; this.clusterId = clusterId; - this.infobaseId = infobaseId; + this.lockInfo = lockInfo; - this.sessionsInfo = sessionsInfo; - this.connections = connections; - this.columnsMap = columnsMap; - } + this.sessionsInfo = server.getSessions(clusterId); + this.currentIcon = defaultIcon; - /** - * Init columns name. - * - * @param columnsMap - sample map with columns name - */ - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_DESCRIPTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SESSION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_HOSTNAME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LOCKED_AT, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initLocksColumnCount(columnsMap.size()); + computeExtendedInfoData(); } - @Override - public String[] getExtendedInfo() { + protected void computeExtendedInfoData() { var connectionNumber = ""; //$NON-NLS-1$ var sessionNumber = ""; //$NON-NLS-1$ @@ -99,26 +70,26 @@ public String[] getExtendedInfo() { var hostPort = ""; //$NON-NLS-1$ var infobaseName = ""; //$NON-NLS-1$ - if (!lockInfo.getSid().equals(emptyUuid)) { + if (!lockInfo.getSid().equals(Helper.EMPTY_UUID)) { ISessionInfo session = getSessionInfoFromLockConnectionId(lockInfo, sessionsInfo); if (session != null) { sessionNumber = Integer.toString(session.getSessionId()); - appName = session.getAppId(); computerName = session.getHost(); + appName = session.getAppId(); infobaseName = server.getInfoBaseName(clusterId, session.getInfoBaseId()); } - } else if (!lockInfo.getConnectionId().equals(emptyUuid)) { + } else if (!lockInfo.getConnectionId().equals(Helper.EMPTY_UUID)) { IInfoBaseConnectionShort connection = getConnectionInfoFromLockConnectionId(lockInfo, connections); if (connection != null) { connectionNumber = Integer.toString(connection.getConnId()); - appName = connection.getApplication(); computerName = connection.getHost(); + appName = connection.getApplication(); infobaseName = server.getInfoBaseName(clusterId, connection.getInfoBaseId()); - UUID wpId = connection.getWorkingProcessId(); + UUID wpId = connection.getWorkingProcessId(); IWorkingProcessInfo wpInfo = server.getWorkingProcessInfo(clusterId, wpId); if (wpInfo != null) { hostName = wpInfo.getHostName(); @@ -127,20 +98,31 @@ public String[] getExtendedInfo() { } } - Map lock = new LinkedHashMap<>(); - lock.putAll(columnsMap); + columnProperties.prepareDataMap(data); + + putData(TITLE_DESCRIPTION, lockInfo.getLockDescr(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_INFOBASE, infobaseName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_CONNECTION, connectionNumber, CELL_VALUE_TYPE.TEXT); + putData(TITLE_SESSION, sessionNumber, CELL_VALUE_TYPE.TEXT); + putData(TITLE_COMPUTER, computerName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_APPLICATION, server.getApplicationName(appName), CELL_VALUE_TYPE.TEXT); + putData(TITLE_HOSTNAME, hostName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_PORT, hostPort, CELL_VALUE_TYPE.TEXT); + putData(TITLE_LOCKED_AT, lockInfo.getLockedAt(), CELL_VALUE_TYPE.DATE); + } - lock.put(TITLE_DESCRIPTION, lockInfo.getLockDescr()); - lock.put(TITLE_INFOBASE, infobaseName); - lock.put(TITLE_CONNECTION, connectionNumber); - lock.put(TITLE_SESSION, sessionNumber); - lock.put(TITLE_COMPUTER, computerName); - lock.put(TITLE_APPLICATION, server.getApplicationName(appName)); - lock.put(TITLE_HOSTNAME, hostName); - lock.put(TITLE_PORT, hostPort); - lock.put(TITLE_LOCKED_AT, dateToString(lockInfo.getLockedAt())); + @Override + public void addToTable(Table table, int index) { + createTableItem(table, index, lockInfo.getLockedAt()); + } - return lock.values().toArray(new String[0]); + /** + * Get LockInfo. + * + * @return the lockInfo + */ + public IObjectLockInfo getLockInfo() { + return lockInfo; } private ISessionInfo getSessionInfoFromLockConnectionId( @@ -157,11 +139,47 @@ private ISessionInfo getSessionInfoFromLockConnectionId( private IInfoBaseConnectionShort getConnectionInfoFromLockConnectionId( IObjectLockInfo lockInfo, List connections) { - for (IInfoBaseConnectionShort connection : connections) { - if (connection.getInfoBaseConnectionId().equals(lockInfo.getConnectionId())) { - return connection; - } - } - return null; + return server.getConnectionInfoShort(clusterId, lockInfo.getConnectionId()); + } + + /** Инициализация имен колонок. */ + protected static void initColumnsName() { + + columnProperties.addColumnsInMap( + TITLE_DESCRIPTION, + TITLE_INFOBASE, + TITLE_CONNECTION, + TITLE_SESSION, + TITLE_COMPUTER, + TITLE_APPLICATION, + TITLE_HOSTNAME, + TITLE_PORT, + TITLE_LOCKED_AT); + + defaultIcon = Helper.getImage(DEFAULT_ICON_FILENAME); + } + + /** + * Обновление заголовка вкладки. + * + * @param count - количество элементов + */ + protected static void updateTabText(int count) { + itemCount = count; + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount)); + } + + /** Сброс заголовка вкладки на неизвестное количество элементов. */ + protected static void resetTabTextCount() { + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount + "*")); + } + + /** + * Установка связи с вкладкой TabItem. + * + * @param tabitem вкладка Tabitem + */ + protected static void linkTabItem(TabItem tabitem) { + currentTab = tabitem; } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java index f8c26c2..160c948 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Server.java @@ -30,99 +30,133 @@ import com._1c.v8.ibis.admin.client.IAgentAdminConnectorFactory; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; +import java.text.Collator; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.MessageBox; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.yanygin.clusterAdminLibraryUI.AuthenticateDialog; +import ru.yanygin.clusterAdminLibraryUI.ViewerArea.TreeItemType; -/** Server 1C Enterprise parameters. */ -public class Server { +/** Параметры подключения к серверу 1С Предприятие. */ +public class Server implements Comparable { @SerializedName("Description") @Expose - private String description; + private String description = ""; //$NON-NLS-1$ @SerializedName("AgentHost") @Expose - private String agentHost; + private String agentHost = ""; //$NON-NLS-1$ @SerializedName("AgentPort") @Expose - private int agentPort; + private int agentPort = 0; @SerializedName("RasHost") @Expose - private String rasHost; + private String rasHost = ""; //$NON-NLS-1$ @SerializedName("RasPort") @Expose - private int rasPort; + private int rasPort = 0; @SerializedName("UseLocalRas") @Expose - private boolean useLocalRas; + private boolean useLocalRas = false; @SerializedName("LocalRasPort") @Expose - private int localRasPort; + private int localRasPort = 0; @SerializedName("LocalRasV8version") @Expose - private String localRasV8version; + private String localRasV8version = ""; //$NON-NLS-1$ @SerializedName("Autoconnect") @Expose - private boolean autoconnect; + private boolean autoconnect = false; + @Deprecated(since = "0.3.0", forRemoval = true) @SerializedName("SaveCredentials") + @Expose(serialize = false, deserialize = true) // TODO верно ли написал + private boolean saveCredentials = false; + + @SerializedName("SaveCredentialsVariant") @Expose - private boolean saveCredentials; + private SaveCredentialsVariant saveCredentialsVariant = SaveCredentialsVariant.DISABLE; + @Deprecated(since = "0.3.0", forRemoval = true) @SerializedName("AgentUser") - @Expose - private String agentUserName; + @Expose(serialize = false, deserialize = true) // TODO верно ли написал + private String agentUserName = ""; //$NON-NLS-1$ + @Deprecated(since = "0.3.0", forRemoval = true) @SerializedName("AgentPassword") + @Expose(serialize = false, deserialize = true) // TODO верно ли написал + private String agentPassword = ""; //$NON-NLS-1$ + + @SerializedName("AgentCredential") @Expose - private String agentPassword; + private UserPassPair agentCredential = new UserPassPair(); + @Deprecated(since = "0.3.0", forRemoval = true) @SerializedName("ClustersCredentials") + @Expose(serialize = false, deserialize = true) // TODO верно ли написал + private Map clustersCredentialsOld = new HashMap<>(); + + @SerializedName("ClustersCredentialsV3") @Expose - private Map - credentialsClustersCashe; // TODO Креды инфобаз хранить тут же или в отдельном списке? + private Map clustersCredentialsV03 = new HashMap<>(); + + @SerializedName("InfobasesCredentials") + @Expose + private List infobasesCredentials = new ArrayList<>(); + + @SerializedName("FavoriteInfobases") + @Expose + private List favoriteInfobases = new ArrayList<>(); - public Map credentialsInfobasesCashe; private boolean available; private Process localRasProcess; - private String connectionError; - private String agentVersion = ""; //$NON-NLS-1$ + private String connectionError = ""; //$NON-NLS-1$; + // private String agentVersion = ""; //$NON-NLS-1$ + private String agentVersion = Messages.getString("Server.NotConnect"); //$NON-NLS-1$ private IAgentAdminConnector agentConnector; private IAgentAdminConnection agentConnection; private static final Logger LOGGER = LoggerFactory.getLogger("clusterAdminLibrary"); //$NON-NLS-1$ - private static UUID emptyUuid = - UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ public static final String THIN_CLIENT = "1CV8C"; //$NON-NLS-1$ public static final String THICK_CLIENT = "1CV8"; //$NON-NLS-1$ + public static final String WEB_CLIENT = "WebClient"; //$NON-NLS-1$ public static final String DESIGNER = "Designer"; //$NON-NLS-1$ public static final String SERVER_CONSOLE = "SrvrConsole"; //$NON-NLS-1$ public static final String RAS_CONSOLE = "RAS"; //$NON-NLS-1$ public static final String JOBSCHEDULER = "JobScheduler"; //$NON-NLS-1$ + public static final String BACKGROUND_JOB = "BackgroundJob"; //$NON-NLS-1$ + + private static final String TREE_TITLE_PATTERN = "%s (%s)"; //$NON-NLS-1$ + + public enum SaveCredentialsVariant { + DISABLE, + NAME, + NAMEPASS + } - interface IRunAuthenticate { - void performAutenticate(String userName, String password, boolean saveNewUserpass); + interface AuthenticateAction { + void performAutenticate(UserPassPair userPass, boolean saveNewUserpass); } interface IGetInfobaseInfo { @@ -130,35 +164,38 @@ interface IGetInfobaseInfo { } /** - * Get the server description. + * Получение описания сервера. * - * @return server description + * @return описание сервера */ public String getDescription() { return description; } /** - * Set new server description. + * Установка описания сервера. * - * @param description - new server description + * @param description - новое описания сервера */ public void setDescription(String description) { this.description = description; } /** - * Get the application name. + * Получение имени приложения по Application ID. * * @param appId - application ID - * @return application name + * @return имя приложения */ public String getApplicationName(String appId) { + // TODO переделать на map switch (appId) { case THIN_CLIENT: return Messages.getString("Server.ThinClient"); //$NON-NLS-1$ case THICK_CLIENT: return Messages.getString("Server.ThickClient"); //$NON-NLS-1$ + case WEB_CLIENT: + return Messages.getString("Server.WebClient"); //$NON-NLS-1$ case DESIGNER: return Messages.getString("Server.Designer"); //$NON-NLS-1$ case SERVER_CONSOLE: @@ -167,6 +204,8 @@ public String getApplicationName(String appId) { return Messages.getString("Server.AdministrationServer"); //$NON-NLS-1$ case JOBSCHEDULER: return Messages.getString("Server.JobScheduler"); //$NON-NLS-1$ + case BACKGROUND_JOB: + return Messages.getString("Server.BackgroundJob"); //$NON-NLS-1$ case "": //$NON-NLS-1$ return ""; //$NON-NLS-1$ default: @@ -175,166 +214,166 @@ public String getApplicationName(String appId) { } /** - * Get the agent host name. + * Получение имени хоста агента сервера. * - * @return agent host name + * @return имя хоста агента сервера */ public String getAgentHost() { return agentHost; } /** - * Set new agent host. + * Установка имени хоста агента сервера. * - * @param agentHost - agent new host + * @param agentHost - новое имя хоста агента сервера */ public void setAgentHost(String agentHost) { this.agentHost = agentHost; } /** - * Get agent port as string. + * Получение порта агента сервера строкой. * - * @return agent port cast to string + * @return порт агента сервера строкой */ public String getAgentPortAsString() { return Integer.toString(agentPort); } /** - * Set agent port. + * Установка порта агента сервера. * - * @param agentPort - agent port + * @param agentPort - порт агента сервера */ public void setAgentPort(int agentPort) { this.agentPort = agentPort; } /** - * Get RAS host. + * Получение имени хоста RAS. * - * @return RAS host + * @return имя хоста RAS */ public String getRasHost() { return rasHost; } /** - * Set RAS host. + * Установка имени хоста RAS. * - * @param rasHost - RAS host + * @param rasHost - имя хоста RAS */ public void setRasHost(String rasHost) { this.rasHost = rasHost; } /** - * Get RAS port as string. + * Получение имени хоста RAS строкой. * - * @return RAS port cast to string + * @return имя хоста RAS строкой */ public String getRasPortAsString() { return Integer.toString(rasPort); } /** - * Set RAS port. + * Установка порта RAS. * - * @param rasPort - RAS port + * @param rasPort - порт RAS */ public void setRasPort(int rasPort) { this.rasPort = rasPort; } /** - * Get using local RAS. + * Получение использования локального RAS. * - * @return use local RAS + * @return использование локального RAS */ public boolean getUseLocalRas() { return useLocalRas; } /** - * Set using local RAS. + * Установка использования локального RAS. * - * @param useLocalRas - use local RAS + * @param useLocalRas - использовать локальный RAS */ public void setUseLocalRas(boolean useLocalRas) { this.useLocalRas = useLocalRas; } /** - * Get local RAS port as string. + * Получение порта локального RAS строкой. * - * @return local RAS port cast to string + * @return порт локального RAS строкой */ public String getLocalRasPortAsString() { return Integer.toString(localRasPort); } /** - * Set local RAS port. + * Установка порта локального RAS. * - * @param localRasPort - local RAS port + * @param localRasPort - порт локального RAS */ public void setLocalRasPort(int localRasPort) { this.localRasPort = localRasPort; } /** - * Get local RAS v8 version. + * Получение версии v8 локального RAS. * - * @return local RAS v8 version + * @return версия v8 локального RAS */ public String getLocalRasV8version() { return localRasV8version; } /** - * Set local RAS v8 version. + * Установка версии v8 локального RAS. * - * @param localRasV8version - local RAS v8 version + * @param localRasV8version - версия v8 локального RAS */ public void setLocalRasV8version(String localRasV8version) { this.localRasV8version = localRasV8version; } /** - * Get version of agent. + * Получение версии агента сервера. * - * @return version + * @return версия агента сервера */ public String getAgentVersion() { return agentVersion; } /** - * Get connection error string. + * Получение строки с ошибкой подключения к серверу. * - * @return connection error + * @return ошибка подключения */ public String getConnectionError() { return connectionError; } /** - * Returns the server key of the form "Server:1541". + * Получение ключа сервера в виде "Server:1541". * - * @return server key + * @return ключ сервера */ public String getServerKey() { return agentHost.concat(":").concat(Integer.toString(agentPort)); //$NON-NLS-1$ } /** - * Get description of the server. + * Получение названия сервера для дерева. * - * @return description + * @return Название сервера */ - public String getTreeDescription() { + public String getTreeTitle() { - var commonConfig = ClusterProvider.getCommonConfig(); + var commonConfig = Config.currentConfig; var localRasPatternPart = useLocalRas && commonConfig.isShowLocalRasConnectInfo() @@ -359,142 +398,287 @@ public String getTreeDescription() { } /** - * Get the autoconnect parameters. + * Получение названия кластера для дерева. + * + * @param clusterInfo - информация о кластере + * @return Название сервера + */ + public String getClusterTreeTitle(IClusterInfo clusterInfo) { + + return String.format(TREE_TITLE_PATTERN, clusterInfo.getName(), clusterInfo.getMainPort()); + } + + /** + * Получение названия рабочего процесса для дерева. + * + * @param wpInfo - информация о рабочем процессе + * @return Название сервера + */ + public String getWorkingProcessTreeTitle(IWorkingProcessInfo wpInfo) { + + return String.format(TREE_TITLE_PATTERN, wpInfo.getHostName(), wpInfo.getMainPort()); + } + + /** + * Получение названия рабочего сервера для дерева. + * + * @param wsInfo - информация о рабочем сервере + * @return Название сервера + */ + public String getWorkingServerTreeTitle(IWorkingServerInfo wsInfo) { + + return String.format(TREE_TITLE_PATTERN, wsInfo.getHostName(), wsInfo.getMainPort()); + } + + /** + * Получение значения настройки "Автоподключение при старте программы". * - * @return autoconnect + * @return значение настройки "Автоподключение при старте программы". */ public boolean getAutoconnect() { return autoconnect; } /** - * Set the server to connect automatically when the program starts. + * Установка значения настройки "Автоподключение при старте программы". * - * @param autoconnect - connect automatically to server + * @param autoconnect - новое значение настройки "Автоподключение при старте программы". */ public void setAutoconnect(boolean autoconnect) { this.autoconnect = autoconnect; } /** - * Get the flag to save the server credentials. + * Получение текущего варианта сохранения credentials. + * + * @return текущий вариант сохранения credentials + */ + public SaveCredentialsVariant getSaveCredentialsVariant() { + return saveCredentialsVariant; + } + + /** + * Установка варианта сохранения credentials. + * + * @param saveCredentialsVariant - вариант сохранения credentials + */ + public void setSaveCredentialsVariant(SaveCredentialsVariant saveCredentialsVariant) { + this.saveCredentialsVariant = saveCredentialsVariant; + } + + /** + * Получение логина и пароля агента сервера. + * + * @return логин и пароль агента сервера + */ + public UserPassPair getAgentCredential() { + return agentCredential; + } + + /** + * Установка логина и пароля агента сервера. + * + * @param agentUserPass - логин и пароль агента сервера + */ + public void setAgentCredential(UserPassPair agentUserPass) { + this.agentCredential = agentUserPass; + this.agentCredential.clear(saveCredentialsVariant); + } + + /** + * Добавление новых данных доступа к кластерам. + * + * @param clusterId - ID кластера + * @param userPassPair - логин/пароль для добавления + */ + public void addClusterCredentials(UUID clusterId, UserPassPair userPassPair) { + clustersCredentialsV03.put(clusterId, userPassPair); + } + + /** + * Получение данных доступа к кластерам. * - * @return save the server credentials + * @param clusterId - ID кластера + * @return массив с логин/паролями */ - public boolean getSaveCredentials() { - return saveCredentials; + public UserPassPair getClusterCredentials(UUID clusterId) { + return clustersCredentialsV03.getOrDefault(clusterId, new UserPassPair()); } /** - * Set the flag to save the server credentials. + * Получение данных доступа к кластерам. * - * @param saveCredentials - save the server credentials + * @return данные доступа */ - public void setSaveCredentials(boolean saveCredentials) { - this.saveCredentials = saveCredentials; + public Map getAllClustersCredentials() { + return clustersCredentialsV03; } /** - * Get agent user name. + * Установка данных доступа к кластерам. * - * @return agent user name + * @param credentials - новые данные доступа */ - public String getAgentUserName() { - return agentUserName; + public void setAllClustersCredentials(Map credentials) { + this.clustersCredentialsV03 = credentials; } /** - * Set the agent username. + * Сохранение в конфиге новых данных доступа к инфобазам кластера. * - * @param agentUser - agent username + * @param userPassPair - логин/пароль для добавления */ - public void setAgentUserName(String agentUser) { - this.agentUserName = agentUser; + public void saveInfobaseCredentials(UserPassPair userPassPair) { + infobasesCredentials.add(userPassPair); } /** - * Get agent user password. + * Получение данных доступа к инфобазам. * - * @return agent user password + * @return данные доступа */ - public String getAgentPassword() { - return agentPassword; + public List getInfobasesCredentials() { + return infobasesCredentials; } /** - * Set the agent password. + * Установка данных доступа к инфобазам. * - * @param agentPassword - agent password + * @param credentials - новые данные доступа */ - public void setAgentPassword(String agentPassword) { - this.agentPassword = agentPassword; + public void setAllInfobasesCredentials(List credentials) { + this.infobasesCredentials = credentials; } /** - * Get credentials. + * Проверяет нахождение инфобазы в списке Избранного. * - * @return credentials + * @param ib - инфобаза + * @return Истина - если инфобаза в Избранном, иначе ложь */ - public Map getCredentials() { - return credentialsClustersCashe; + public boolean infobaseIsFavorite(InfoBaseInfoShortExt ib) { + return favoriteInfobases.contains(ib.getName()); } /** - * Set new server credentials. + * Проверяет нахождение инфобазы в списке Избранного. * - * @param credentials - new credentials for the server + * @param infobaseName - имя инфобазы + * @return Истина - если инфобаза в Избранном, иначе ложь */ - public void setCredentials(Map credentials) { - this.credentialsClustersCashe = credentials; + public boolean infobaseIsFavorite(String infobaseName) { + return favoriteInfobases.contains(infobaseName); } /** - * Initialize new server instance. + * Добавление/удаление информационной базы в избранное. * - * @param serverName - server name of the form "Server:1541". + * @param ib - Экземпляр расширенной информации о инфобазе + */ + public void changeInfobaseFavoriteState(InfoBaseInfoShortExt ib) { + String infobaseName = ib.getName(); + if (favoriteInfobases.contains(infobaseName)) { + favoriteInfobases.remove(infobaseName); + } else { + favoriteInfobases.add(infobaseName); + } + + ib.setFavoriteState(favoriteInfobases.contains(infobaseName)); + } + + /** Конструктор, вызываемый при десериализации. */ + public Server() { + } + + /** + * Создание нового экземпляра. + * + * @param serverName - имя сервера в виде "Server" или с указанием порта менеджера "Server:2541". */ public Server(String serverName) { - calculateServerParams(serverName); + computeServerParams(serverName); - this.useLocalRas = false; - this.localRasPort = 0; - this.localRasV8version = ""; //$NON-NLS-1$ - this.autoconnect = false; - this.available = false; - this.saveCredentials = false; - this.agentVersion = ""; //$NON-NLS-1$ + // this.useLocalRas = false; + // this.localRasPort = 0; + // this.localRasV8version = ""; //$NON-NLS-1$ + // this.autoconnect = false; + // this.available = false; + // this.saveCredentials = false; + // this.agentVersion = ""; //$NON-NLS-1$ - init(); + // init(); } /** Initializes some server parameters. */ - public void init() { + // public void init() { + // + // // При чтении конфиг-файла отсутствующие поля, инициализируются значением null + // if (agentUserName == null) { + // agentUserName = ""; //$NON-NLS-1$ + // } + // if (agentPassword == null) { + // agentPassword = ""; //$NON-NLS-1$ + // } + // if (description == null) { + // description = ""; //$NON-NLS-1$ + // } + // if (localRasV8version == null) { + // localRasV8version = ""; //$NON-NLS-1$ + // } + // if (agentVersion == null) { + // agentVersion = Messages.getString("Server.NotConnect"); //$NON-NLS-1$ + // } + // + // if (credentialsClustersCashe == null) { + // credentialsClustersCashe = new HashMap<>(); + // } + // + // this.connectionError = ""; //$NON-NLS-1$ + // + // LOGGER.info("Server <{}> init done", getServerKey()); //$NON-NLS-1$ + // } + + /** + * Перенос настроек при чтении конфиг-файла старой версии. + * + * @param configVersion - версия конфига, с которого осуществляется переход + */ + public void migrateProps(String configVersion) { + + if (configVersion.equals("0.2.0")) { - // При чтении конфиг-файла отсутствующие поля, инициализируются значением null - if (agentUserName == null) { - agentUserName = ""; //$NON-NLS-1$ - } - if (agentPassword == null) { - agentPassword = ""; //$NON-NLS-1$ - } - if (description == null) { - description = ""; //$NON-NLS-1$ - } - if (localRasV8version == null) { - localRasV8version = ""; //$NON-NLS-1$ - } - if (agentVersion == null) { - agentVersion = Messages.getString("Server.NotConnect"); //$NON-NLS-1$ - } + if (saveCredentials) { + saveCredentialsVariant = SaveCredentialsVariant.NAMEPASS; + saveCredentials = false; + } - if (credentialsClustersCashe == null) { - credentialsClustersCashe = new HashMap<>(); + if (!agentUserName.isBlank() && saveCredentialsVariant == SaveCredentialsVariant.NAMEPASS) { + agentCredential = new UserPassPair(agentUserName, agentPassword); + agentUserName = ""; + agentPassword = ""; + } + + clustersCredentialsOld.forEach( + (uuid, array) -> + clustersCredentialsV03.put(uuid, new UserPassPair(array[0], array[1], array[2]))); + clustersCredentialsOld.clear(); + + LOGGER.info("Server <{}> migrate props from version 0.2.0", getServerKey()); //$NON-NLS-1$ } - this.connectionError = ""; //$NON-NLS-1$ + } + + @Override + public int compareTo(Server o) { + + Collator collator = Collator.getInstance(Locale.getDefault()); + + // Сортировка по алфавиту (по возрастанию) + String firstString = o.getServerKey(); + String secondString = getServerKey(); - LOGGER.info("Server <{}> init done", getServerKey()); //$NON-NLS-1$ + return collator.compare(secondString, firstString); } private void readAgentVersion() { @@ -526,9 +710,9 @@ private String getLocalisedMessage(Throwable excp) { } /** - * Return true if v8 version 8.3.15 or more. + * Возвращает истину, если версия платформы v8 8.3.15 или выше. * - * @return {@code true} if v8 version 8.3.15 or more + * @return {@code true} если v8 версия 8.3.15 или выше */ public boolean isFifteenOrMoreAgentVersion() { return agentVersion.compareTo("8.3.15") >= 0; //$NON-NLS-1$ @@ -540,7 +724,7 @@ public boolean isFifteenOrMoreAgentVersion() { * @param serverAddress - Имя сервера из списка баз. Может содержать номер порта менеджера * кластера (Если не указан, то по-умолчанию 1541). Примеры: Server1c, Server1c:2541 */ - private void calculateServerParams(String serverAddress) { + private void computeServerParams(String serverAddress) { String host; int newAgentPort; @@ -568,13 +752,13 @@ private void calculateServerParams(String serverAddress) { this.agentPort = newAgentPort; this.rasPort = newRasPort; - LOGGER.info("Calculate params for Server <{}> ", this.getServerKey()); //$NON-NLS-1$ + LOGGER.info("Compute params for Server <{}> ", this.getServerKey()); //$NON-NLS-1$ } /** - * Checks whether connection to the administration server is established. + * Проверяет, установлено ли соединение с сервером администрирования. * - * @return {@code true} if connected, {@code false} overwise + * @return {@code true} установлено, {@code false} не установлено */ public boolean isConnected() { boolean isConnected = (agentConnection != null); @@ -589,11 +773,11 @@ public boolean isConnected() { } /** - * Connects to the server. + * Выполняет подключение к серверу. * - * @param disconnectAfter - disconnect after successful connection - * @param silentMode - do not output an error to the user interactively - * @return {@code true} if connect is succesful + * @param disconnectAfter - отключиться сразу после успешного подключения + * @param silentMode - не выводить сообщение об ошибке пользователю в интерактивном режиме + * @return {@code true} если соединение прошло успешно */ public boolean connectToServer(boolean disconnectAfter, boolean silentMode) { LOGGER.debug("<{}> start connection", this.getServerKey()); //$NON-NLS-1$ @@ -627,9 +811,7 @@ public boolean connectToServer(boolean disconnectAfter, boolean silentMode) { LOGGER.error(connectionError); if (!silentMode) { - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(connectionError); - messageBox.open(); + Helper.showMessageBox(connectionError); } return false; } @@ -644,7 +826,7 @@ public boolean connectToServer(boolean disconnectAfter, boolean silentMode) { */ private boolean checkAndRunLocalRas() { - if (!ClusterProvider.getCommonConfig().isWindows()) { + if (!Config.currentConfig.isWindows()) { return true; } @@ -658,10 +840,7 @@ private boolean checkAndRunLocalRas() { Messages.getString("Server.LocalRasParamsIsEmpty"), //$NON-NLS-1$ this.getServerKey()); LOGGER.error(message); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(message); - messageBox.open(); + Helper.showMessageBox(message); return false; } @@ -669,16 +848,13 @@ private boolean checkAndRunLocalRas() { ///////////////////////////// пока только Windows var processBuilder = new ProcessBuilder(); var processOutput = ""; //$NON-NLS-1$ - var localRasPath = ClusterProvider.getInstalledV8Versions().get(localRasV8version); + var localRasPath = Helper.getInstalledV8Versions().get(localRasV8version); if (localRasPath == null) { var message = String.format( Messages.getString("Server.LocalRasNotFound"), this.getServerKey()); //$NON-NLS-1$ LOGGER.error(message); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(message); - messageBox.open(); + Helper.showMessageBox(message); return false; } @@ -705,10 +881,8 @@ private boolean checkAndRunLocalRas() { } catch (Exception excp) { LOGGER.error("Error launch local RAS for server <{}>", this.getServerKey()); //$NON-NLS-1$ LOGGER.error("Error: <{}>", processOutput, excp); //$NON-NLS-1$ - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + Helper.showMessageBox(excp.getLocalizedMessage()); + return false; } @@ -722,32 +896,30 @@ private boolean checkAndRunLocalRas() { LOGGER.debug("Local RAS runnung = {}", localRasProcess.isAlive()); //$NON-NLS-1$ if (localRasProcess.isAlive()) { LOGGER.debug("Local RAS parent CMD pid = {}", localRasProcess.pid()); //$NON-NLS-1$ - Stream ch = localRasProcess.children(); - ch.forEach( - ch1 -> { - LOGGER.debug( - "\tchildren -> {}, pid = {}", ch1.info().command().get(), ch1.pid()); //$NON-NLS-1$ - }); + Stream subprocesses = localRasProcess.children(); + subprocesses.forEach( + subprocess -> + LOGGER.debug( + "\tsubprocess -> {}, pid = {}", //$NON-NLS-1$ + subprocess.info().command().get(), + subprocess.pid())); return true; } else { connectionError = String.format("Local RAS <%s> is shutdown", this.getServerKey()); //$NON-NLS-1$ LOGGER.error(connectionError); - - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(connectionError); - messageBox.open(); + Helper.showMessageBox(connectionError); return false; } } /** - * Проверяет действительна ли еще авторизация на центральном сервере и если нет - запускает - * процесс авторизации. + * Проверяет действительна ли еще аутентификация на центральном сервере и если нет - запускает + * процесс аутентификации. * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return boolean истекла/не истекла */ private boolean checkAutenticateAgent() { @@ -785,14 +957,14 @@ private boolean checkAutenticateAgent() { } /** - * Establishes connection with the administration server of 1C:Enterprise server cluster. + * Устанавливает соединение с сервером администрирования. * - * @param address - server address - * @param port - IP port - * @param timeout - connection timeout (in milliseconds) - * @throws AgentAdminException in the case of errors. + * @param address - адрес сервера RAS + * @param port - IP порт сервера RAS + * @param timeout - таймаут соединения (в миллисекундах) + * @throws AgentAdminException в случае ошибок. */ - public void connectToAgent(String address, int port, long timeout) { + private void connectToAgent(String address, int port, long timeout) { if (isConnected()) { LOGGER.debug( "The connection to server <{}> is already established", //$NON-NLS-1$ @@ -819,9 +991,9 @@ public void connectToAgent(String address, int port, long timeout) { } /** - * Terminates connection to the administration server. + * Отключение от сервера администрирования. * - * @throws AgentAdminException in the case of errors. + * @throws AgentAdminException в случае ошибок. */ public void disconnectFromAgent() { if (!isConnected()) { @@ -849,7 +1021,7 @@ public void disconnectFromAgent() { private void disconnectLocalRas() { if (useLocalRas && localRasProcess.isAlive()) { Stream ch = localRasProcess.children(); - ch.forEach(ch1 -> ch1.destroy()); + ch.forEach(ProcessHandle::destroy); localRasProcess.destroy(); LOGGER.info( "Local RAS of Server <{}> is shutdown now", //$NON-NLS-1$ @@ -858,11 +1030,11 @@ private void disconnectLocalRas() { } /** - * Authethicates a central server administrator agent. + * Выполняет аутентификацию администратора центрального сервера. * - *

        Need call before of regCluster, getAgentAdmins, regAgentAdmin, unregAgentAdmin + *

        Необходимо вызывать перед regCluster, getAgentAdmins, regAgentAdmin, unregAgentAdmin * - * @return {@code true} if authenticated, {@code false} overwise + * @return {@code true} успешно, {@code false} не успешно */ public boolean authenticateAgent() { @@ -870,41 +1042,47 @@ public boolean authenticateAgent() { return false; } - IRunAuthenticate authMethod = - (String userName, String password, boolean saveNewUserpass) -> { + AuthenticateAction authAction = + (UserPassPair userPass, boolean saveNewUserpass) -> { LOGGER.debug( "Try to autenticate the agent server <{}>", //$NON-NLS-1$ - this.getServerKey()); - this.agentConnection.authenticateAgent(userName, password); + getServerKey()); + agentConnection.authenticateAgent(userPass.getUsername(), userPass.getPassword()); LOGGER.debug( "Authentication to the agent server <{}> was successful", //$NON-NLS-1$ - this.getServerKey()); + getServerKey()); // сохраняем новые user/pass после успешной авторизации - if (saveNewUserpass) { - this.agentUserName = userName; - this.agentPassword = password; + // (если сохранение включено в настройках) + if (saveNewUserpass && saveCredentialsVariant != SaveCredentialsVariant.DISABLE) { + agentCredential = userPass; + agentCredential.clear(saveCredentialsVariant); + // agentUserName = userPass.getUsername(); + // agentPassword = + // saveCredentialsVariant == SaveCredentialsVariant.NAMEPASS + // ? userPass.getPassword() + // : ""; LOGGER.debug( "New credentials for the agent server <{}> are saved", //$NON-NLS-1$ - this.getServerKey()); + getServerKey()); } }; - String authDescription = + String authTitle = String.format( Messages.getString("Server.AuthenticationOfCentralServerAdministrator"), //$NON-NLS-1$ agentHost, agentPort); return runAuthProcessWithRequestToUser( - authDescription, agentUserName, agentPassword, authMethod); + agentCredential, new ArrayList<>(), authTitle, authAction); } /** - * Checks whether authentication is still valid on the cluster and if not, starts the - * authentication process. + * Проверяет, действительна ли аутентификация в кластере, и, если нет, запускает процесс + * аутентификации. * - * @param clusterId - cluster ID - * @return boolean valid/not valid + * @param clusterId - ID кластера + * @return {@code true} аутентифицирован, {@code false} не аутентифицирован */ private boolean checkAutenticateCluster(UUID clusterId) { @@ -940,12 +1118,12 @@ private boolean checkAutenticateCluster(UUID clusterId) { } /** - * Checks whether the authentication in the infobase is still valid and if not, starts the - * authentication process. + * Проверяет, действительна ли аутентификация в инфобазе, и, если нет, запускает процесс + * аутентификации. * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID - * @return boolean valid/not valid + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы + * @return {@code true} аутентифицирован, {@code false} не аутентифицирован */ private boolean checkAutenticateInfobase(UUID clusterId, UUID infobaseId) { @@ -953,10 +1131,10 @@ private boolean checkAutenticateInfobase(UUID clusterId, UUID infobaseId) { } /** - * Authethicates a server cluster administrator. + * Аутентификация на кластере. * - * @param clusterId - cluster ID - * @return boolean is authentication successful + * @param clusterId - ID кластера + * @return {@code true} при успешной аутентификации */ public boolean authenticateCluster(UUID clusterId) { @@ -964,58 +1142,76 @@ public boolean authenticateCluster(UUID clusterId) { return false; } - IRunAuthenticate authMethod = - (String userName, String password, boolean saveNewUserpass) -> { - String clusterName = getClusterInfo(clusterId).getName(); + AuthenticateAction authAction = + (UserPassPair userPass, boolean saveNewUserpass) -> { + IClusterInfo clusterInfo = getClusterInfo(clusterId); + var clusterName = + String.format( + "%s (%s)", clusterInfo.getName(), clusterInfo.getMainPort()); //$NON-NLS-1$ LOGGER.debug( "Try to autenticate to the cluster <{}> of server <{}>", //$NON-NLS-1$ clusterName, - this.getServerKey()); - agentConnection.authenticate(clusterId, userName, password); + getServerKey()); + agentConnection.authenticate(clusterId, userPass.getUsername(), userPass.getPassword()); LOGGER.debug( "Authentication to the cluster <{}> of server <{}> was successful", //$NON-NLS-1$ clusterName, - this.getServerKey()); + getServerKey()); + + userPass.setDescription(clusterName); // сохраняем новые user/pass после успешной авторизации - if (this.saveCredentials && saveNewUserpass) { - this.credentialsClustersCashe.put( - clusterId, new String[] {userName, password, clusterName}); + // (если сохранение включено в настройках) + if (saveNewUserpass && saveCredentialsVariant != SaveCredentialsVariant.DISABLE) { + + // TODO по идее достаточно очистить пароль, если в настройках указано, что не хранить + // но этого креда могло еще не быть в хранилище, а значит его туда надо все же вставить + + if (saveCredentialsVariant == SaveCredentialsVariant.NAME) { + userPass.setPassword(""); + } + clustersCredentialsV03.put(clusterId, userPass); + // TODO clusterProvider.saveConfig(); + LOGGER.debug( "New credentials for the cluster <{}> of server <{}> are saved", //$NON-NLS-1$ clusterName, - this.getServerKey()); + getServerKey()); } }; - String[] userAndPassword = - credentialsClustersCashe.getOrDefault( - clusterId, new String[] {"", ""}); //$NON-NLS-1$ //$NON-NLS-2$ - String authDescription = + UserPassPair userPass = getClusterCredentials(clusterId); + List userPasses = + getAllClustersCredentials().values().stream().collect(Collectors.toList()); + String authTitle = String.format( Messages.getString("Server.AuthenticationOfClusterAdminnistrator"), //$NON-NLS-1$ getServerKey(), getClusterInfo(clusterId).getName()); - return runAuthProcessWithRequestToUser( - authDescription, userAndPassword[0], userAndPassword[1], authMethod); + return runAuthProcessWithRequestToUser(userPass, userPasses, authTitle, authAction); } private boolean runAuthProcessWithRequestToUser( - String authDescription, String userName, String password, IRunAuthenticate authMethod) { + UserPassPair userPass, + List userPassesList, + String authTitle, + AuthenticateAction authAction) { + + // TODO требуется рефакторинг метода try { // Сперва пытаемся авторизоваться под сохраненной учеткой // (она может быть инициализирована пустыми строками) - authMethod.performAutenticate(userName, password, false); + authAction.performAutenticate(userPass, false); } catch (Exception excp) { + String authExcpMessage = excp.getLocalizedMessage(); LOGGER.debug( "Autenticate to server <{}> error: <{}>", //$NON-NLS-1$ - this.getServerKey(), - excp.getLocalizedMessage()); + getServerKey(), + authExcpMessage); AuthenticateDialog authenticateDialog; - String authExcpMessage = excp.getLocalizedMessage(); int dialogResult; // крутимся, пока не подойдет пароль, или пользователь не нажмет Отмена @@ -1024,40 +1220,39 @@ private boolean runAuthProcessWithRequestToUser( try { LOGGER.debug( "Requesting new user credentials for the server <{}>", //$NON-NLS-1$ - this.getServerKey()); + getServerKey()); authenticateDialog = new AuthenticateDialog( Display.getDefault().getActiveShell(), - userName, - authDescription, - authExcpMessage); + userPass, + authTitle, + authExcpMessage, + userPassesList); dialogResult = authenticateDialog.open(); } catch (Exception exc) { + String excpMessage = exc.getLocalizedMessage(); LOGGER.debug( - "Request new user credentials for the server <{}> failed", //$NON-NLS-1$ - this.getServerKey()); - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(exc.getLocalizedMessage()); - messageBox.open(); + "Request new user credentials for the server <{}> failed: <{}>", //$NON-NLS-1$ + getServerKey(), + excpMessage); + Helper.showMessageBox(excpMessage); return false; } if (dialogResult == 0) { LOGGER.debug( "The user has provided new credentials for the server <{}>", //$NON-NLS-1$ - this.getServerKey()); - userName = authenticateDialog.getUsername(); - password = authenticateDialog.getPassword(); + getServerKey()); + userPass = authenticateDialog.getUserPass(); try { - authMethod.performAutenticate(userName, password, true); + authAction.performAutenticate(userPass, true); break; } catch (Exception exc) { + authExcpMessage = exc.getLocalizedMessage(); LOGGER.debug( "Autenticate to server <{}> error: <{}>", //$NON-NLS-1$ - this.getServerKey(), - excp.getLocalizedMessage()); - authExcpMessage = exc.getLocalizedMessage(); - continue; + getServerKey(), + authExcpMessage); } } else { return false; @@ -1068,19 +1263,39 @@ private boolean runAuthProcessWithRequestToUser( } /** - * Adds infobase authentication parameters to the context of the current administration server - * connection. + * Добавление всех сохраненных кредов инфобаз в кластер. + * + * @param clusterId - ID кластера + */ + public void provideSavedInfobasesCredentialsToCluster(UUID clusterId) { + if (!isConnected()) { + return; + } + + infobasesCredentials.forEach( + userpass -> + agentConnection.addAuthentication( + clusterId, userpass.getUsername(), userpass.getPassword())); + + LOGGER.debug( + "Provide infobase credentials for the cluster <{}> of server <{}>", //$NON-NLS-1$ + clusterId, + this.getServerKey()); + } + + /** + * Добавляет параметры аутентификации информационной базы в контекст текущего подключения к + * серверу администрирования. * - * @param clusterId - cluster ID - * @param userName - infobase administrator name - * @param password - infobase administrator password + * @param clusterId - ID кластера + * @param userPass - имя и пароль администратора инфобазы */ - public void addInfobaseCredentials(UUID clusterId, String userName, String password) { + public void addInfobaseCredentials(UUID clusterId, UserPassPair userPass) { if (!isConnected()) { return; } - agentConnection.addAuthentication(clusterId, userName, password); + agentConnection.addAuthentication(clusterId, userPass.getUsername(), userPass.getPassword()); LOGGER.debug( "Add new infobase credentials for the cluster <{}> of server <{}>", //$NON-NLS-1$ clusterId, @@ -1088,9 +1303,9 @@ public void addInfobaseCredentials(UUID clusterId, String userName, String passw } /** - * Gets the list of cluster descriptions registered on the central server. + * Получение списка кластеров зарегистрированных на центральном сервере. * - * @return list of cluster descriptions + * @return список кластеров */ public List getClusters() { if (!isConnected()) { @@ -1120,15 +1335,15 @@ public List getClusters() { cluster.getHostName(), cluster.getMainPort()); - // обновление имени кластера в кеше credentials - if (saveCredentials) { - String[] credentialClustersCashe = credentialsClustersCashe.get(cluster.getClusterId()); - if (credentialClustersCashe != null - && !credentialClustersCashe[2].equals(cluster.getName())) { - credentialClustersCashe[2] = cluster.getName(); - needSaveConfig = true; - } - } + // // обновление имени кластера в кеше credentials + // if (saveCredentials) { + // String[] credentialClustersCashe = clustersCredentials.get(cluster.getClusterId()); + // if (credentialClustersCashe != null + // && !credentialClustersCashe[2].equals(cluster.getName())) { + // credentialClustersCashe[2] = cluster.getName(); + // needSaveConfig = true; + // } + // } } if (needSaveConfig) { // TODO надо сохранить @@ -1138,10 +1353,10 @@ public List getClusters() { } /** - * Gets the cluster descriptions. + * Получение информации о кластере. * - * @param clusterId - cluster ID - * @return cluster - descriptions + * @param clusterId - ID кластера + * @return cluster - информация о кластере */ public IClusterInfo getClusterInfo(UUID clusterId) { if (!isConnected()) { @@ -1151,7 +1366,6 @@ public IClusterInfo getClusterInfo(UUID clusterId) { LOGGER.debug("Get the cluster <{}> descriptions", clusterId); //$NON-NLS-1$ IClusterInfo clusterInfo; - // TODO debug try { clusterInfo = agentConnection.getClusterInfo(clusterId); } catch (Exception excp) { @@ -1166,12 +1380,12 @@ public IClusterInfo getClusterInfo(UUID clusterId) { /** * Gets the list of cluster manager descriptions. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return cluster - list of cluster manager descriptions */ - public List getClusterManagers(UUID clusterId) { + private List getClusterManagers(UUID clusterId) { LOGGER.debug( "Gets the list of cluster manager descriptions in the cluster <{}>", //$NON-NLS-1$ clusterId); @@ -1185,7 +1399,7 @@ public List getClusterManagers(UUID clusterId) { } List clusterManagers; - // TODO debug + // TODO try { clusterManagers = agentConnection.getClusterManagers(clusterId); } catch (Exception excp) { @@ -1200,14 +1414,14 @@ public List getClusterManagers(UUID clusterId) { /** * Gets a cluster manager description. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId cluster ID + * @param clusterId ID кластера * @param managerId - manager ID * @return cluster manager description, or null if the manager with the specified ID does not * exist */ - public IClusterManagerInfo getClusterManagerInfo(UUID clusterId, UUID managerId) { + private IClusterManagerInfo getClusterManagerInfo(UUID clusterId, UUID managerId) { LOGGER.debug( "Get the cluster manager <{}> description of cluster <{}>", //$NON-NLS-1$ managerId, @@ -1222,7 +1436,7 @@ public IClusterManagerInfo getClusterManagerInfo(UUID clusterId, UUID managerId) } IClusterManagerInfo clusterManagerInfo; - // TODO debug + // TODO try { clusterManagerInfo = agentConnection.getClusterManagerInfo(clusterId, managerId); } catch (Exception excp) { @@ -1243,7 +1457,7 @@ public IClusterManagerInfo getClusterManagerInfo(UUID clusterId, UUID managerId) * @return {@code true} if cluster registration successful */ public boolean regCluster(IClusterInfo clusterInfo) { - if (clusterInfo.getClusterId().equals(emptyUuid)) { + if (clusterInfo.getClusterId().equals(Helper.EMPTY_UUID)) { LOGGER.debug( "Registration new cluster <{}>", //$NON-NLS-1$ clusterInfo.getName()); @@ -1274,7 +1488,7 @@ public boolean regCluster(IClusterInfo clusterInfo) { return false; } - if (clusterInfo.getClusterId().equals(emptyUuid)) { + if (clusterInfo.getClusterId().equals(Helper.EMPTY_UUID)) { LOGGER.debug( "Registration new cluster <{}> succesful", //$NON-NLS-1$ newClusterId); @@ -1287,12 +1501,12 @@ public boolean regCluster(IClusterInfo clusterInfo) { } /** - * Deletes a cluster. + * Удаление кластера с сервера. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @return delete a cluster successful + * @param clusterId - ID кластера + * @return {@code true} при успешном удалении кластера */ public boolean unregCluster(UUID clusterId) { LOGGER.debug("Delete a cluster <{}>", clusterId); //$NON-NLS-1$ @@ -1300,7 +1514,7 @@ public boolean unregCluster(UUID clusterId) { var unregSuccesful = false; String unregMessage = null; - if (!isConnected()) { // TODO + if (!isConnected()) { unregMessage = Messages.getString("Server.TheConnectionAClusterIsNotEstablished"); //$NON-NLS-1$ } @@ -1309,31 +1523,31 @@ public boolean unregCluster(UUID clusterId) { unregMessage = Messages.getString("Server.TheClusterAuthenticationError"); //$NON-NLS-1$ } - try { - agentConnection.unregCluster(clusterId); - unregSuccesful = true; - } catch (Exception excp) { - LOGGER.error("Error delete a cluster", excp); //$NON-NLS-1$ - unregMessage = excp.getLocalizedMessage(); + if (unregMessage == null) { + try { + agentConnection.unregCluster(clusterId); + unregSuccesful = true; + } catch (Exception excp) { + LOGGER.error("Error delete a cluster", excp); //$NON-NLS-1$ + unregMessage = excp.getLocalizedMessage(); + } } if (!unregSuccesful) { - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(unregMessage); - messageBox.open(); + Helper.showMessageBox(unregMessage); } return unregSuccesful; } /** - * Gets the list of cluster administrators. + * Получение списка администраторов кластера. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @return list of cluster administrators + * @param clusterId - ID кластера + * @return список администраторов кластера */ - public List getClusterAdmins(UUID clusterId) { + private List getClusterAdmins(UUID clusterId) { LOGGER.debug( "Gets the list of cluster administrators in the cluster <{}>", //$NON-NLS-1$ clusterId); @@ -1346,14 +1560,14 @@ public List getClusterAdmins(UUID clusterId) { } /** - * Deletes a cluster administrator. + * Удаление администратора кластера. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param name - administrator name + * @param clusterId - ID кластера + * @param name - имя администратора */ - public void unregClusterAdmin(UUID clusterId, String name) { + private void unregClusterAdmin(UUID clusterId, String name) { LOGGER.debug( "Deletes a cluster administrator in the cluster <{}>", //$NON-NLS-1$ clusterId); @@ -1366,14 +1580,14 @@ public void unregClusterAdmin(UUID clusterId, String name) { } /** - * Gets the list of short descriptions of infobases registered in the cluster. + * Получение списка краткого описания инфобаз кластера. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId -cluster ID - * @return list of short descriptions of cluster infobases + * @param clusterId -ID кластера + * @return список краткого описания инфобаз кластера */ - public List getInfoBasesShort(UUID clusterId) { + public List getInfoBasesShort(UUID clusterId) { LOGGER.debug( "Get the list of short descriptions of infobases registered in the cluster <{}>", //$NON-NLS-1$ clusterId); @@ -1394,23 +1608,34 @@ public List getInfoBasesShort(UUID clusterId) { return new ArrayList<>(); } + List clusterInfoBasesExt = new ArrayList<>(); clusterInfoBases.forEach( - ib -> - LOGGER.debug( - "\tInfobase: name=<{}>, desc=<{}>", ib.getName(), ib.getDescr())); //$NON-NLS-1$ + ib -> { + clusterInfoBasesExt.add( + new InfoBaseInfoShortExt( + ib, clusterInfoBasesExt.size(), favoriteInfobases.contains(ib.getName()))); + + LOGGER.debug( + "\tInfobase: name=<{}>, desc=<{}>", //$NON-NLS-1$ + ib.getName(), + ib.getDescr()); + }); LOGGER.debug("Get the list of short descriptions of infobases succesful"); //$NON-NLS-1$ - return clusterInfoBases; + + Collections.sort(clusterInfoBasesExt); + + return clusterInfoBasesExt; } /** * Gets the list of full descriptions of infobases registered in the cluster. * - *

        Cluster authentication is required For each infobase in the cluster, infobase authentication + *

        Требует аутентификации в кластере For each infobase in the cluster, infobase authentication * is required If infobase authentication is not performed, only fields that correspond to short * infobase description fields will be filled * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return list of full descriptions of cluster infobases */ public List getInfoBases(UUID clusterId) { @@ -1434,10 +1659,11 @@ public List getInfoBases(UUID clusterId) { } clusterInfoBases.forEach( - ib -> { - LOGGER.debug( - "\tInfobase: name=<{}>, desc=<{}>", ib.getName(), ib.getDescr()); //$NON-NLS-1$ - }); + ib -> + LOGGER.debug( + "\tInfobase: name=<{}>, desc=<{}>", //$NON-NLS-1$ + ib.getName(), + ib.getDescr())); LOGGER.debug("Get the list of descriptions of infobases succesful"); //$NON-NLS-1$ return clusterInfoBases; @@ -1446,10 +1672,10 @@ public List getInfoBases(UUID clusterId) { /** * Gets a short infobase description. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @return short infobase description */ public IInfoBaseInfoShort getInfoBaseShortInfo(UUID clusterId, UUID infobaseId) { @@ -1482,10 +1708,10 @@ public IInfoBaseInfoShort getInfoBaseShortInfo(UUID clusterId, UUID infobaseId) /** * Gets the full infobase description. * - *

        Cluster authentication is required. Infobase authentication is required. + *

        Требует аутентификации в кластере Infobase authentication is required. * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @return infobase full infobase description */ public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { @@ -1513,8 +1739,8 @@ public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { String authExcpMessage = excp.getLocalizedMessage(); int dialogResult; - var userName = ""; //$NON-NLS-1$ - var authDescription = Messages.getString("Server.AuthenticationOfInfobase"); //$NON-NLS-1$ + UserPassPair userPass = new UserPassPair(); + var authTitle = Messages.getString("Server.AuthenticationOfInfobase"); //$NON-NLS-1$ // пока не подойдет пароль, или пользователь не нажмет Отмена while (true) { @@ -1526,17 +1752,17 @@ public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { authenticateDialog = new AuthenticateDialog( Display.getDefault().getActiveShell(), - userName, - authDescription, - authExcpMessage); + userPass, + authTitle, + authExcpMessage, + infobasesCredentials); dialogResult = authenticateDialog.open(); } catch (Exception exc) { + String excpMessage = exc.getLocalizedMessage(); LOGGER.debug( "Request new user credentials for the infobase failed: <{}>", //$NON-NLS-1$ - exc.getLocalizedMessage()); - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(exc.getLocalizedMessage()); - messageBox.open(); + excpMessage); + Helper.showMessageBox(excpMessage); return null; } @@ -1544,11 +1770,11 @@ public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { LOGGER.debug( "The user has provided new credentials for the infobase <{}>", //$NON-NLS-1$ infobaseId); - userName = authenticateDialog.getUsername(); - String password = authenticateDialog.getPassword(); + userPass = authenticateDialog.getUserPass(); try { - addInfobaseCredentials(clusterId, userName, password); + addInfobaseCredentials(clusterId, userPass); infobaseInfo = agentConnection.getInfoBaseInfo(clusterId, infobaseId); + saveInfobaseCredentials(userPass); break; } catch (Exception exc) { authExcpMessage = exc.getLocalizedMessage(); @@ -1556,7 +1782,6 @@ public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { "Autenticate to infobase <{}> error: <{}>", //$NON-NLS-1$ this.getServerKey(), authExcpMessage); - continue; } } else { LOGGER.debug( @@ -1573,10 +1798,10 @@ public IInfoBaseInfo getInfoBaseInfo(UUID clusterId, UUID infobaseId) { /** * Gets the infobase name. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @return infobase full infobase description */ public String getInfoBaseName(UUID clusterId, UUID infobaseId) { @@ -1585,8 +1810,8 @@ public String getInfoBaseName(UUID clusterId, UUID infobaseId) { infobaseId, clusterId); - if (infobaseId.equals(emptyUuid)) { - LOGGER.debug("Infobase ID is empty"); //$NON-NLS-1$ + if (infobaseId.equals(Helper.EMPTY_UUID)) { + LOGGER.debug("ID инфобазы is empty"); //$NON-NLS-1$ return ""; //$NON-NLS-1$ } @@ -1597,13 +1822,13 @@ public String getInfoBaseName(UUID clusterId, UUID infobaseId) { /** * Creates an infobase in a cluster. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param info - infobase parameters + * @param clusterId - ID кластера + * @param info - параметры инфобазы * @param infobaseCreationMode - infobase creation mode: •0 - do not create a database •1 - create * a database - * @return ID of the created infobase + * @return ID созданной инфобазы или пустой UUID */ public UUID createInfoBase(UUID clusterId, IInfoBaseInfo info, int infobaseCreationMode) { LOGGER.debug( @@ -1612,10 +1837,10 @@ public UUID createInfoBase(UUID clusterId, IInfoBaseInfo info, int infobaseCreat clusterId); if (!isConnected()) { - return emptyUuid; + return Helper.EMPTY_UUID; } if (!checkAutenticateCluster(clusterId)) { - return emptyUuid; + return Helper.EMPTY_UUID; } UUID uuid; @@ -1623,7 +1848,8 @@ public UUID createInfoBase(UUID clusterId, IInfoBaseInfo info, int infobaseCreat uuid = agentConnection.createInfoBase(clusterId, info, infobaseCreationMode); } catch (Exception excp) { LOGGER.error("Error creates an infobase", excp); //$NON-NLS-1$ - throw excp; + Helper.showMessageBox(excp.getLocalizedMessage()); + return Helper.EMPTY_UUID; } LOGGER.debug("Creates an infobase succesful"); //$NON-NLS-1$ @@ -1631,14 +1857,14 @@ public UUID createInfoBase(UUID clusterId, IInfoBaseInfo info, int infobaseCreat } /** - * Changes short infobase description. + * Изменение краткого описания информационной базы. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере. * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param info - infobase parameters */ - public void updateInfoBaseShort(UUID clusterId, IInfoBaseInfoShort info) { + private void updateInfoBaseShort(UUID clusterId, IInfoBaseInfoShort info) { LOGGER.debug( "Changes short description infobase <{}> in the cluster <{}>", //$NON-NLS-1$ info.getInfoBaseId(), @@ -1651,7 +1877,7 @@ public void updateInfoBaseShort(UUID clusterId, IInfoBaseInfoShort info) { return; } - try { // TODO debug + try { // TODO agentConnection.updateInfoBaseShort(clusterId, info); } catch (Exception excp) { LOGGER.error("Error changes short description infobase", excp); //$NON-NLS-1$ @@ -1660,38 +1886,36 @@ public void updateInfoBaseShort(UUID clusterId, IInfoBaseInfoShort info) { } /** - * Changes infobase parameters. + * Изменение параметров информационной базы. * - *

        Infobase authentication is required (Здесь не нужно авторизоваться в базе, метод необходимо - * вызывать сразу после getInfoBaseInfo) + *

        Требует аутентификации в инфобазе (Здесь не нужно аутентифицироваться в базе, метод + * необходимо вызывать сразу после getInfoBaseInfo) * - * @param clusterId - cluster ID - * @param info - infobase parameters - * @return {@code true} if update succesful + * @param clusterId - ID кластера + * @param info - параметры инфобазы + * @return {@code true} при успешном изменении */ public boolean updateInfoBase(UUID clusterId, IInfoBaseInfo info) { - try { // TODO debug + try { agentConnection.updateInfoBase(clusterId, info); } catch (Exception excp) { LOGGER.error("Error changes description infobase", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + Helper.showMessageBox(excp.getLocalizedMessage()); return false; } return true; } /** - * Deletes an infobase. + * Удаление информационной базы. * - *

        Infobase authentication is required + *

        Требует аутентификации в инфобазе * - * @param clusterId - cluster ID - * @param infobaseId - infobase parameters - * @param dropMode - infobase drop mode: 0 - do not delete the database 1 - delete the database 2 - * - clear the database + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы + * @param dropMode - режим удаления инфобазы: 0 - не удалять базу данных в СУБД, 1 - удалять базу + * данных в СУБД, 2 - очистить базу от данных * @return {@code true} if drop succesful */ public boolean dropInfoBase(UUID clusterId, UUID infobaseId, int dropMode) { @@ -1700,102 +1924,117 @@ public boolean dropInfoBase(UUID clusterId, UUID infobaseId, int dropMode) { return false; } - try { // TODO debug + try { agentConnection.dropInfoBase(clusterId, infobaseId, dropMode); } catch (Exception excp) { LOGGER.error("Error deletes an infobase", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + Helper.showMessageBox(excp.getLocalizedMessage()); return false; } return true; } /** - * Gets the list of cluster session descriptions. + * Gets a session description. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @return List of session descriptions + * @param clusterId - ID кластера + * @param sid - session ID + * @return session description */ - public List getSessions(UUID clusterId) { + public ISessionInfo getSessionInfo(UUID clusterId, UUID sid) { LOGGER.debug( - "Gets the list of cluster session descriptions in the cluster <{}>", //$NON-NLS-1$ - clusterId); + "Gets a session <{}> description in the cluster <{}>", sid, clusterId); //$NON-NLS-1$ if (!isConnected()) { - return new ArrayList<>(); + return null; } - if (!checkAutenticateCluster(clusterId)) { - return new ArrayList<>(); + return null; } - List sessions; + ISessionInfo sessionInfo; try { - sessions = agentConnection.getSessions(clusterId); + sessionInfo = agentConnection.getSessionInfo(clusterId, sid); // TODO ошибка в библиотеке } catch (Exception excp) { - LOGGER.error("Error get the list of cluster session descriptions", excp); //$NON-NLS-1$ - return new ArrayList<>(); + LOGGER.error("Error get a session description", excp); //$NON-NLS-1$ + return null; } - sessions.forEach( - s -> { - LOGGER.debug( - "\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ - getApplicationName(s.getAppId()), - s.getSessionId()); - }); - - LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ - return sessions; + LOGGER.debug( + "\tappId={}, sid={}, connectionId={}, sessionId={}, userName={}", //$NON-NLS-1$ + sessionInfo.getAppId(), + sessionInfo.getSid(), + sessionInfo.getConnectionId(), + sessionInfo.getSessionId(), + sessionInfo.getUserName()); + + LOGGER.debug("Get the session description succesful"); //$NON-NLS-1$ + return sessionInfo; } /** - * Gets a session description. + * Получение списка сеансов кластера. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param sid - session ID - * @return session description + * @param clusterId - ID кластера + * @return список сеансов кластера */ - public ISessionInfo getSessionInfo(UUID clusterId, UUID sid) { + public List getSessions(UUID clusterId) { LOGGER.debug( - "Gets a session <{}> description in the cluster <{}>", sid, clusterId); //$NON-NLS-1$ + "Gets the list of cluster session descriptions in the cluster <{}>", //$NON-NLS-1$ + clusterId); if (!isConnected()) { - return null; + return new ArrayList<>(); } + if (!checkAutenticateCluster(clusterId)) { - return null; + return new ArrayList<>(); } - ISessionInfo sessionInfo; - try { // TODO debug - sessionInfo = agentConnection.getSessionInfo(clusterId, sid); + List sessions; + try { + sessions = agentConnection.getSessions(clusterId); } catch (Exception excp) { LOGGER.error("Error get the list of cluster session descriptions", excp); //$NON-NLS-1$ - return null; + return new ArrayList<>(); } - LOGGER.debug( - "\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ - getApplicationName(sessionInfo.getAppId()), - sessionInfo.getSessionId()); + + LOGGER.debug("Sessions:"); + sessions.forEach( + s -> + LOGGER.debug( + "\tappId={}, sid={}, connectionId={}, sessionId={}, userName={}", //$NON-NLS-1$ + s.getAppId(), + s.getSid(), + s.getConnectionId(), + s.getSessionId(), + s.getUserName())); LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ - return sessionInfo; + return sessions; } + // /** + // * Gets the extended list of cluster session descriptions. + // * + // * @param clusterId - ID кластера + // * @return Extended list of session descriptions + // */ + // public List getSessionsExtended(UUID clusterId) { + // return convertSessionsInfoToSessionsExtended(clusterId, getSessions(clusterId)); + // } + /** * Gets the list of infobase session descriptions. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @return Infobase sessions */ - public List getInfoBaseSessions(UUID clusterId, UUID infobaseId) { + private List getInfoBaseSessions(UUID clusterId, UUID infobaseId) { LOGGER.debug( "Gets the list of infobase <{}> session descriptions in the cluster <{}>", //$NON-NLS-1$ infobaseId, @@ -1815,41 +2054,121 @@ public List getInfoBaseSessions(UUID clusterId, UUID infobaseId) { LOGGER.error("Error get the list of infobase session descriptions", excp); //$NON-NLS-1$ return new ArrayList<>(); } + + LOGGER.debug("Sessions:"); sessions.forEach( - s -> { - LOGGER.debug( - "\tSession: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ - getApplicationName(s.getAppId()), - s.getSessionId()); - }); + s -> + LOGGER.debug( + "\tappId={}, sid={}, connectionId={}, sessionId={}, userName={}", //$NON-NLS-1$ + s.getAppId(), + s.getSid(), + s.getConnectionId(), + s.getSessionId(), + s.getUserName())); LOGGER.debug("Get the list of cluster session descriptions succesful"); //$NON-NLS-1$ return sessions; } + // /** + // * Gets the extended list of infobase session descriptions. + // * + // * @param clusterId - ID кластера + // * @param infobaseId - ID инфобазы + // * @return Extended list of session descriptions + // */ + // public List getInfoBaseSessionsExtended(UUID clusterId, UUID infobaseId) + // { + // return convertSessionsInfoToSessionsExtended( + // clusterId, getInfoBaseSessions(clusterId, infobaseId)); + // } + /** - * Gets the list of infobase session descriptions. + * Gets the list of working process session descriptions. * - *

        Cluster authentication is required + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param workingProcessId - Working process ID * @return Working process sessions */ - public List getWorkingProcessSessions(UUID clusterId, UUID workingProcessId) { + private List getWorkingProcessSessions(UUID clusterId, UUID workingProcessId) { return getSessions(clusterId).stream() .filter(s -> s.getWorkingProcessId().equals(workingProcessId)) .collect(Collectors.toList()); } + // /** + // * Gets the extended list of infobase session descriptions. + // * + // * @param clusterId - ID кластера + // * @param workingProcessId - working process ID + // * @return Extended list of session descriptions + // */ + // public List getWorkingProcessSessionsExtended( + // UUID clusterId, UUID workingProcessId) { + // return convertSessionsInfoToSessionsExtended( + // clusterId, getWorkingProcessSessions(clusterId, workingProcessId)); + // } + + /** + * Gets the extended list of cluster session descriptions. + * + * @param treeItemType - tree item type + * @param clusterId - ID кластера + * @param workingProcessId - working process ID + * @param infobaseId - ID инфобазы + * @return Extended list of session descriptions + */ + public List getSessionsExtendedInfo( + TreeItemType treeItemType, UUID clusterId, UUID workingProcessId, UUID infobaseId) { + + List sessions; + + switch (treeItemType) { + case SERVER: + return new ArrayList<>(); + + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + sessions = getSessions(clusterId); + break; + + case WORKINGPROCESS: + sessions = getWorkingProcessSessions(clusterId, workingProcessId); + break; + + case INFOBASE: + sessions = getInfoBaseSessions(clusterId, infobaseId); + break; + + default: + return new ArrayList<>(); + } + + return convertSessionsInfoToSessionsExtended(clusterId, sessions); + } + + private List convertSessionsInfoToSessionsExtended( + UUID clusterId, List sessions) { + + List sessionsExtended = new ArrayList<>(); + sessions.forEach( + session -> sessionsExtended.add(new SessionInfoExtended(this, clusterId, session))); + Collections.sort(sessionsExtended); + + return sessionsExtended; + } + /** * Terminates a session in the cluster with default message. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param sessionId - infobase ID + * @param clusterId - ID кластера + * @param sessionId - ID инфобазы * @return sucess terminate session */ public boolean terminateSession(UUID clusterId, UUID sessionId) { @@ -1860,10 +2179,10 @@ public boolean terminateSession(UUID clusterId, UUID sessionId) { /** * Terminates a session in the cluster. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param sessionId - infobase ID + * @param clusterId - ID кластера + * @param sessionId - ID инфобазы * @param message - error message for user * @return sucess terminate session */ @@ -1884,9 +2203,7 @@ public boolean terminateSession(UUID clusterId, UUID sessionId, String message) agentConnection.terminateSession(clusterId, sessionId, message); } catch (Exception excp) { LOGGER.error("Error terminate a session", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + Helper.showMessageBox(excp.getLocalizedMessage()); return false; } LOGGER.debug("Terminates a session succesful"); //$NON-NLS-1$ @@ -1896,7 +2213,7 @@ public boolean terminateSession(UUID clusterId, UUID sessionId, String message) /** * Terminates all sessions for all infobases in the cluster. * - * @param clusterId - cluster ID + * @param clusterId - ID кластера */ public void terminateAllSessions(UUID clusterId) { @@ -1906,8 +2223,8 @@ public void terminateAllSessions(UUID clusterId) { /** * Terminates all sessions for infobase in the cluster. * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @param onlyUsersSession - terminate only users sessions */ public void terminateAllSessionsOfInfobase( @@ -1929,89 +2246,185 @@ private boolean isUserSession(ISessionInfo session) { } /** - * Gets the list of short descriptions of cluster connections. + * Gets a short description of a connection. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @return list of short cluster connection descriptions + * @param clusterId - ID кластера + * @param connectionId - connection ID + * @return short connection description */ - public List getConnectionsShort(UUID clusterId) { - if (isConnected()) { - return agentConnection.getConnectionsShort(clusterId); + public IInfoBaseConnectionShort getConnectionInfoShort(UUID clusterId, UUID connectionId) { + LOGGER.debug( + "Gets a connection <{}> short description in the cluster <{}>", //$NON-NLS-1$ + connectionId, + clusterId); + if (!isConnected()) { + return null; } - // TODO - return new ArrayList<>(); + if (!checkAutenticateCluster(clusterId)) { + return null; + } + + IInfoBaseConnectionShort connectionInfo; + try { + connectionInfo = agentConnection.getConnectionInfoShort(clusterId, connectionId); + } catch (Exception excp) { + LOGGER.error("Error get a short description of a connection", excp); //$NON-NLS-1$ + return null; + } + // LOGGER.debug( + // "\tConnection: application name=<{}>, session ID=<{}>", //$NON-NLS-1$ + // getApplicationName(sessionInfo.getAppId()), + // sessionInfo.getSessionId()); + + LOGGER.debug("Get the short description of a connection succesful"); //$NON-NLS-1$ + return connectionInfo; } /** - * Gets a short description of a connection. + * Gets the list of short descriptions of cluster connections. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param connectionId - connection ID - * @return short connection description + * @param clusterId - ID кластера + * @return list of short cluster connection descriptions */ - public IInfoBaseConnectionShort getConnectionInfoShort(UUID clusterId, UUID connectionId) { - if (isConnected()) { - return agentConnection.getConnectionInfoShort(clusterId, connectionId); + private List getConnectionsShort(UUID clusterId) { + LOGGER.debug( + "Gets the list of short descriptions connections of cluster <{}>", //$NON-NLS-1$ + clusterId); + + if (!isConnected()) { + return new ArrayList<>(); } - // TODO - return null; + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List connections; + try { + connections = agentConnection.getConnectionsShort(clusterId); + } catch (Exception excp) { + LOGGER.error("Error get the list of short descriptions connections", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return connections; } + // /** + // * Gets the extended list of cluster connection descriptions. + // * + // * @param clusterId - ID кластера + // * @return Extended list of session descriptions + // */ + // public List getConnectionsExtended(UUID clusterId) { + // return convertConnectionsInfoToConnectionsExtended(clusterId, + // getConnectionsShort(clusterId)); + // } + /** * Gets the list of short descriptions of infobase connections. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @return list of short infobase connection descriptions */ - public List getInfoBaseConnectionsShort( + private List getInfoBaseConnectionsShort( UUID clusterId, UUID infobaseId) { - if (isConnected()) { - return agentConnection.getInfoBaseConnectionsShort(clusterId, infobaseId); + + LOGGER.debug( + "Gets the list of short descriptions connections of cluster <{}>, infobase <{}>", //$NON-NLS-1$ + clusterId, + infobaseId); + + if (!isConnected()) { + return new ArrayList<>(); } - // TODO - return new ArrayList<>(); + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List connections; + try { + connections = agentConnection.getInfoBaseConnectionsShort(clusterId, infobaseId); + } catch (Exception excp) { + LOGGER.error("Error get the list of short descriptions connections", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return connections; } + // /** + // * Gets the extended list of infobase connection descriptions. + // * + // * @param clusterId - ID кластера + // * @param infobaseId - ID инфобазы + // * @return Extended list of session descriptions + // */ + // public List getInfoBaseConnectionsExtended( + // UUID clusterId, UUID infobaseId) { + // return convertConnectionsInfoToConnectionsExtended( + // clusterId, getInfoBaseConnectionsShort(clusterId, infobaseId)); + // } + /** - * Gets the list of infobase connection descriptions for a working process. + * Возвращает список соединений информационной базы для рабочего процесса. * - *

        Cluster authentication is required. Infobase authentication is required. + *

        Требует аутентификации в кластере, Требует аутентификации в инфобазе. * - * @param clusterId - cluster ID - * @param workingProcessId - working process ID - * @param infobaseId - infobase ID - * @return list of infobase connection descriptions + * @param clusterId - ID кластера + * @param workingProcessId - ID рабочего процесса + * @param infobaseId - ID инфобазы + * @return список соединений к инфобазе */ - public List getInfoBaseConnections( + private List getInfoBaseConnections( UUID clusterId, UUID workingProcessId, UUID infobaseId) { - if (isConnected()) { - return agentConnection.getInfoBaseConnections(clusterId, workingProcessId, infobaseId); + + LOGGER.debug( + "Gets the list of descriptions connections of cluster <{}>, infobase <{}>", //$NON-NLS-1$ + clusterId, + infobaseId); + + if (!isConnected()) { + return new ArrayList<>(); } - // TODO - return new ArrayList<>(); + + if (!checkAutenticateCluster(clusterId)) { + return new ArrayList<>(); + } + + List connections; + try { // TODO + connections = agentConnection.getInfoBaseConnections(clusterId, workingProcessId, infobaseId); + } catch (Exception excp) { + LOGGER.error("Error get the list of descriptions connections", excp); //$NON-NLS-1$ + return new ArrayList<>(); + } + + return connections; } /** * Gets the list of connection descriptions for a working process. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param workingProcessId - working process ID * @return list of connection descriptions for a working process */ - public List getWorkingProcessConnectionsShort( + private List getWorkingProcessConnectionsShort( UUID clusterId, UUID workingProcessId) { if (isConnected()) { - return agentConnection.getConnectionsShort(clusterId).stream() + return getConnectionsShort(clusterId).stream() .filter(c -> c.getWorkingProcessId().equals(workingProcessId)) .collect(Collectors.toList()); } @@ -2019,15 +2432,79 @@ public List getWorkingProcessConnectionsShort( return new ArrayList<>(); } + // /** + // * Gets the extended list of working processId connection descriptions. + // * + // * @param clusterId - ID кластера + // * @param workingProcessId - workingProcess ID + // * @return Extended list of session descriptions + // */ + // public List getWorkingProcessConnectionsExtended( + // UUID clusterId, UUID workingProcessId) { + // return convertConnectionsInfoToConnectionsExtended( + // clusterId, getWorkingProcessConnectionsShort(clusterId, workingProcessId)); + // } + + /** + * Gets the extended list of cluster connections descriptions. + * + * @param treeItemType - tree item type + * @param clusterId - ID кластера + * @param workingProcessId - working process ID + * @param infobaseId - ID инфобазы + * @return Extended list of connection descriptions + */ + public List getConnectionsExtendedInfo( + TreeItemType treeItemType, UUID clusterId, UUID workingProcessId, UUID infobaseId) { + + List sessions; + + switch (treeItemType) { + case SERVER: + return new ArrayList<>(); + + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + sessions = getConnectionsShort(clusterId); + break; + + case WORKINGPROCESS: + sessions = getWorkingProcessConnectionsShort(clusterId, workingProcessId); + break; + + case INFOBASE: + sessions = getInfoBaseConnectionsShort(clusterId, infobaseId); + break; + + default: + return new ArrayList<>(); + } + + return convertConnectionsInfoToConnectionsExtended(clusterId, sessions); + } + + private List convertConnectionsInfoToConnectionsExtended( + UUID clusterId, List connections) { + + List connectionsExtended = new ArrayList<>(); + connections.forEach( + connection -> + connectionsExtended.add(new ConnectionInfoExtended(this, clusterId, connection))); + Collections.sort(connectionsExtended); + + return connectionsExtended; + } + /** * Closes an infobase connection. * - *

        Cluster authentication is required. Infobase authentication is required. + *

        Требует аутентификации в кластере Infobase authentication is required. * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param processId - working process ID * @param connectionId - connection ID - * @param infobaseId - infobase ID + * @param infobaseId - ID инфобазы * @return {@code true} if successful shutdown */ public boolean disconnectConnection( @@ -2052,9 +2529,7 @@ public boolean disconnectConnection( agentConnection.disconnect(clusterId, processId, connectionId); } catch (Exception excp) { LOGGER.error("Error close connection", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + Helper.showMessageBox(excp.getLocalizedMessage()); return false; } LOGGER.debug("Close connection succesful"); //$NON-NLS-1$ @@ -2064,9 +2539,9 @@ public boolean disconnectConnection( /** * Interrupt current server call. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param sid - session ID * @param message - interrupt message */ @@ -2080,12 +2555,12 @@ public void interruptCurrentServerCall(UUID clusterId, UUID sid, String message) /** * Gets the list of object locks. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return list of object lock descriptions */ - public List getLocks(UUID clusterId) { + private List getLocks(UUID clusterId) { LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ if (!isConnected()) { @@ -2097,7 +2572,7 @@ public List getLocks(UUID clusterId) { } List locks; - try { // TODO debug + try { locks = agentConnection.getLocks(clusterId); } catch (Exception excp) { LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ @@ -2107,16 +2582,26 @@ public List getLocks(UUID clusterId) { return locks; } + // /** + // * Gets the extended list of locks descriptions. + // * + // * @param clusterId - ID кластера + // * @return Extended list of session descriptions + // */ + // public List getLocksExtended(UUID clusterId) { + // return convertLocksInfoToLocksExtended(clusterId, getLocks(clusterId)); + // } + /** * Gets the list of infobase object locks. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @return list of object lock descriptions */ - public List getInfoBaseLocks(UUID clusterId, UUID infobaseId) { + private List getInfoBaseLocks(UUID clusterId, UUID infobaseId) { LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ if (!isConnected()) { @@ -2128,7 +2613,7 @@ public List getInfoBaseLocks(UUID clusterId, UUID infobaseId) { } List locks; - try { // TODO debug + try { locks = agentConnection.getInfoBaseLocks(clusterId, infobaseId); } catch (Exception excp) { LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ @@ -2138,16 +2623,27 @@ public List getInfoBaseLocks(UUID clusterId, UUID infobaseId) { return locks; } + // /** + // * Gets the extended list of infobase locks descriptions. + // * + // * @param clusterId - ID кластера + // * @param infobaseId - ID инфобазы + // * @return Extended list of session descriptions + // */ + // public List getInfoBaseLocksExtended(UUID clusterId, UUID infobaseId) { + // return convertLocksInfoToLocksExtended(clusterId, getInfoBaseLocks(clusterId, infobaseId)); + // } + /** * Gets the list of connection object locks. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param connectionId - connection ID * @return list of object lock descriptions */ - public List getConnectionLocks(UUID clusterId, UUID connectionId) { + private List getConnectionLocks(UUID clusterId, UUID connectionId) { LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ if (!isConnected()) { @@ -2159,7 +2655,7 @@ public List getConnectionLocks(UUID clusterId, UUID connectionI } List locks; - try { // TODO debug + try { // TODO locks = agentConnection.getConnectionLocks(clusterId, connectionId); } catch (Exception excp) { LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ @@ -2172,14 +2668,14 @@ public List getConnectionLocks(UUID clusterId, UUID connectionI /** * Gets the list of session object locks. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @param infobaseId - infobase ID + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы * @param sid - session ID * @return list of object lock descriptions */ - public List getSessionLocks(UUID clusterId, UUID infobaseId, UUID sid) { + private List getSessionLocks(UUID clusterId, UUID infobaseId, UUID sid) { LOGGER.debug("Gets the list of object locks in the cluster <{}>", clusterId); //$NON-NLS-1$ if (!isConnected()) { @@ -2191,7 +2687,7 @@ public List getSessionLocks(UUID clusterId, UUID infobaseId, UU } List locks; - try { // TODO debug + try { // TODO locks = agentConnection.getSessionLocks(clusterId, infobaseId, sid); } catch (Exception excp) { LOGGER.error("Error get the list of object locks", excp); //$NON-NLS-1$ @@ -2202,12 +2698,61 @@ public List getSessionLocks(UUID clusterId, UUID infobaseId, UU } /** - * Gets the list of descriptions of working processes registered in the cluster. + * Gets the extended list of cluster session descriptions. + * + * @param treeItemType - tree item type + * @param clusterId - ID кластера + * @param infobaseId - ID инфобазы + * @return Extended list of session descriptions + */ + public List getLocksExtendedInfo( + TreeItemType treeItemType, UUID clusterId, UUID infobaseId) { + + List locks; + + switch (treeItemType) { + case SERVER: + return new ArrayList<>(); + + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + locks = getLocks(clusterId); + break; + + case WORKINGPROCESS: + locks = new ArrayList<>(); + break; + + case INFOBASE: + locks = getInfoBaseLocks(clusterId, infobaseId); + break; + + default: + return new ArrayList<>(); + } + + return convertLocksInfoToLocksExtended(clusterId, locks); + } + + private List convertLocksInfoToLocksExtended( + UUID clusterId, List locks) { + + List locksExtended = new ArrayList<>(); + locks.forEach( + connection -> locksExtended.add(new LockInfoExtended(this, clusterId, connection))); + Collections.sort(locksExtended); + + return locksExtended; + } + + /** + * Получение списка рабочих процессов кластера. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @return list of working processes descriptions + * @param clusterId - ID кластера + * @return Список рабочих процессов кластера */ public List getWorkingProcesses(UUID clusterId) { if (!isConnected()) { @@ -2219,36 +2764,95 @@ public List getWorkingProcesses(UUID clusterId) { } List workingProcesses; - try { // TODO debug + try { LOGGER.debug( "Gets the list of descriptions of working processes in the cluster <{}>", //$NON-NLS-1$ clusterId); workingProcesses = agentConnection.getWorkingProcesses(clusterId); } catch (Exception excp) { - LOGGER.error( - "Error get the list of short descriptions of working processes", //$NON-NLS-1$ - excp); + LOGGER.error("Error get the list of descriptions of working processes", excp); //$NON-NLS-1$ + return new ArrayList<>(); } workingProcesses.forEach( - wp -> { - LOGGER.debug( - "\tWorking process: host name=<{}>, main port=<{}>", //$NON-NLS-1$ - wp.getHostName(), - wp.getMainPort()); - }); + wp -> + LOGGER.debug( + "\tWorking process: host name=<{}>, main port=<{}>", //$NON-NLS-1$ + wp.getHostName(), + wp.getMainPort())); - LOGGER.debug( - "Get the list of short descriptions of working processes succesful"); //$NON-NLS-1$ + LOGGER.debug("Get the list of descriptions of working processes succesful"); //$NON-NLS-1$ return workingProcesses; } + // /** + // * Gets the extended list of infobase connection descriptions. + // * + // * @param clusterId - ID кластера + // * @return Extended list of session descriptions + // */ + // public List getWorkingProcessesExtended(UUID clusterId) { + // return convertWorkingProcessInfoToWorkingProcessExtended( + // clusterId, getWorkingProcesses(clusterId)); + // } + + /** + * Получение списка расширенной информации о рабочих процессах. + * + * @param treeItemType - тип элемента дерева, для которого идет получение списка + * @param clusterId - ID кластера + * @param workingProcessId - working process ID + * @return Список расширенной информации о рабочих процессах + */ + public List getWorkingProcessesExtendedInfo( + TreeItemType treeItemType, UUID clusterId, UUID workingProcessId) { + + List workingProcesses; + + switch (treeItemType) { + case SERVER: + return new ArrayList<>(); + + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + workingProcesses = getWorkingProcesses(clusterId); + break; + + case WORKINGPROCESS: + workingProcesses = new ArrayList<>(); + workingProcesses.add(this.getWorkingProcessInfo(clusterId, workingProcessId)); + break; + + case INFOBASE: + // TODO отметить рп обслуживающий базу + workingProcesses = getWorkingProcesses(clusterId); + break; + + default: + return new ArrayList<>(); + } + + return convertWorkingProcessInfoToWorkingProcessExtended(clusterId, workingProcesses); + } + + private List convertWorkingProcessInfoToWorkingProcessExtended( + UUID clusterId, List workingProcesses) { + + List workingProcessesExtended = new ArrayList<>(); + workingProcesses.forEach( + wp -> workingProcessesExtended.add(new WorkingProcessInfoExtended(this, clusterId, wp))); + Collections.sort(workingProcessesExtended); + + return workingProcessesExtended; + } + /** * Gets a working process description. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param processId - working process ID * @return working process description, or null if the working process with the specified ID does * not exist @@ -2280,9 +2884,9 @@ public IWorkingProcessInfo getWorkingProcessInfo(UUID clusterId, UUID processId) /** * Gets the list of descriptions of working processes of a working server. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param serverId - working server ID * @return list of working process descriptions */ @@ -2295,12 +2899,12 @@ public List getServerWorkingProcesses(UUID clusterId, UUID } /** - * Gets the list of descriptions of working servers registered in the cluster. + * Получение списка рабочих серверов, зарегистрированных на кластере. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID - * @return list of working server descriptions + * @param clusterId - ID кластера + * @return Список рабочих серверов */ public List getWorkingServers(UUID clusterId) { if (!isConnected()) { @@ -2312,36 +2916,72 @@ public List getWorkingServers(UUID clusterId) { } List workingServers; - try { // TODO debug + try { LOGGER.debug( "Gets the list of descriptions of working servers in the cluster <{}>", //$NON-NLS-1$ clusterId); workingServers = agentConnection.getWorkingServers(clusterId); } catch (Exception excp) { LOGGER.error("Error get the list of descriptions of working servers", excp); //$NON-NLS-1$ - throw new IllegalStateException("Error get working servers"); //$NON-NLS-1$ + return new ArrayList<>(); } workingServers.forEach( - ws -> { - LOGGER.debug( - "\tWorking server: host name=<{}>, main port=<{}>", //$NON-NLS-1$ - ws.getHostName(), - ws.getMainPort()); - }); + ws -> + LOGGER.debug( + "\tWorking server: host name=<{}>, main port=<{}>", //$NON-NLS-1$ + ws.getHostName(), + ws.getMainPort())); LOGGER.debug("Get the list of descriptions of working servers succesful"); //$NON-NLS-1$ return workingServers; } /** - * Gets a description of a working server registered in the cluster. + * Получение списка расширенной информации о рабочих серверах, зарегистрированных на кластере. * - *

        Cluster authentication is required. + * @param treeItemType - тип элемента дерева, дял которого идет получение списка + * @param clusterId - ID кластера + * @return Список расширенной информации о рабочих серверах + */ + public List getWorkingServersExtendedInfo( + TreeItemType treeItemType, UUID clusterId) { + + switch (treeItemType) { + case SERVER: + return new ArrayList<>(); + + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + case WORKINGPROCESS: + case INFOBASE: + return convertWorkingServersInfoToWorkingServersExtended( + clusterId, getWorkingServers(clusterId)); + + default: + return new ArrayList<>(); + } + } + + private List convertWorkingServersInfoToWorkingServersExtended( + UUID clusterId, List workingServers) { + + List workingServersExtended = new ArrayList<>(); + workingServers.forEach( + ws -> workingServersExtended.add(new WorkingServerInfoExtended(this, clusterId, ws))); + Collections.sort(workingServersExtended); + + return workingServersExtended; + } + + /** + * Получение информации о рабочем сервере кластера. * - * @param clusterId - cluster ID - * @param serverId - server ID - * @return working server description, or null if the working server with the specified ID does - * not exist + *

        Требует аутентификации в кластере + * + * @param clusterId - ID кластера + * @param serverId - ID рабочего сервера + * @return информация о рабочем сервере, или null если рабочий сервер с указанным ID не существует */ public IWorkingServerInfo getWorkingServerInfo(UUID clusterId, UUID serverId) { if (!isConnected()) { @@ -2353,7 +2993,7 @@ public IWorkingServerInfo getWorkingServerInfo(UUID clusterId, UUID serverId) { } IWorkingServerInfo workingServerInfo; - try { // TODO debug + try { LOGGER.debug( "Gets the description of working server <{}> in the cluster <{}>", //$NON-NLS-1$ serverId, @@ -2361,7 +3001,8 @@ public IWorkingServerInfo getWorkingServerInfo(UUID clusterId, UUID serverId) { workingServerInfo = agentConnection.getWorkingServerInfo(clusterId, serverId); } catch (Exception excp) { LOGGER.error("Error get the list of descriptions of working server", excp); //$NON-NLS-1$ - throw new IllegalStateException("Error get working server"); //$NON-NLS-1$ + Helper.showMessageBox(excp.getLocalizedMessage()); + return null; } LOGGER.debug( @@ -2375,17 +3016,16 @@ public IWorkingServerInfo getWorkingServerInfo(UUID clusterId, UUID serverId) { } /** - * Creates a working server or changes the description of an existing one. + * Создание рабочего сервера или изменение существующего экземпляра. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере. * - * @param clusterId - cluster ID - * @param serverInfo - working server description - * @param createNew - if create new working server - * @return {@code true} if succes reg working server + * @param clusterId - ID кластера + * @param wsInfo - объект-описание рабочего сервера + * @param createNew - признак создания нового сервера + * @return {@code true} при успешном создании или изменении рабочего сервера */ - public boolean regWorkingServer( - UUID clusterId, IWorkingServerInfo serverInfo, boolean createNew) { + public boolean regWorkingServer(UUID clusterId, IWorkingServerInfo wsInfo, boolean createNew) { if (!isConnected()) { return false; } @@ -2398,35 +3038,36 @@ public boolean regWorkingServer( LOGGER.debug("Registration NEW working server"); //$NON-NLS-1$ } - try { // TODO debug + try { LOGGER.debug( "Registration working server <{}> registered in the cluster <{}>", //$NON-NLS-1$ - serverInfo.getName(), + wsInfo.getName(), clusterId); - agentConnection.regWorkingServer(clusterId, serverInfo); + agentConnection.regWorkingServer(clusterId, wsInfo); } catch (Exception excp) { LOGGER.error("Error registration working server", excp); //$NON-NLS-1$ + Helper.showMessageBox(excp.getLocalizedMessage()); return false; } LOGGER.debug( "\tRegistration working server: name=<{}>, host name=<{}>, main port=<{}>", //$NON-NLS-1$ - serverInfo.getName(), - serverInfo.getHostName(), - serverInfo.getMainPort()); + wsInfo.getName(), + wsInfo.getHostName(), + wsInfo.getMainPort()); LOGGER.debug("Registration working server succesful"); //$NON-NLS-1$ return true; } /** - * Deletes a working server and removes its cluster registration. + * Удаляет рабочий сервер и удаляет его регистрацию в кластере. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере. * - * @param clusterId - cluster ID - * @param serverId - server ID - * @return infobase full infobase description + * @param clusterId - ID кластера + * @param serverId - ID рабочего сервера + * @return {@code true} при успешном удалении рабочего сервера */ public boolean unregWorkingServer(UUID clusterId, UUID serverId) { if (!isConnected()) { @@ -2437,7 +3078,7 @@ public boolean unregWorkingServer(UUID clusterId, UUID serverId) { return false; } - try { // TODO debug + try { LOGGER.debug( "Deletes a working server <{}> from the cluster <{}>", //$NON-NLS-1$ serverId, @@ -2445,9 +3086,7 @@ public boolean unregWorkingServer(UUID clusterId, UUID serverId) { agentConnection.unregWorkingServer(clusterId, serverId); } catch (Exception excp) { LOGGER.error("Error registration working server", excp); //$NON-NLS-1$ - MessageBox messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + Helper.showMessageBox(excp.getLocalizedMessage()); return false; } @@ -2458,9 +3097,9 @@ public boolean unregWorkingServer(UUID clusterId, UUID serverId) { /** * Gets the list of cluster service descriptions. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return list of cluster service descriptions */ public List getClusterServices(UUID clusterId) { @@ -2471,9 +3110,9 @@ public List getClusterServices(UUID clusterId) { /** * Applies assignment rules. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param full - assigment rule application mode: 0 - partial 1 - full */ public void applyAssignmentRules(UUID clusterId, int full) { @@ -2484,9 +3123,9 @@ public void applyAssignmentRules(UUID clusterId, int full) { /** * Gets the list of descriptions of working server assignment rules. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param serverId - server ID * @return infobase full infobase description */ @@ -2499,9 +3138,9 @@ public List getAssignmentRules(UUID clusterId, UUID serverI * Creates an assignment rule, changes an existing one, or moves an existing rule to a new * position. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param serverId - server ID * @param info - assignment rule description * @param position - position in the rule list (starts from 0) @@ -2516,9 +3155,9 @@ public UUID regAssignmentRule( /** * Deletes an assignment rule from the list of working server rules. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param serverId - working server ID * @param ruleId - assignment rule ID */ @@ -2530,9 +3169,9 @@ public void unregAssignmentRule(UUID clusterId, UUID serverId, UUID ruleId) { /** * Gets an assignment rule description. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param serverId - server ID * @param ruleId - assignment rule ID * @return assignment rule description @@ -2545,9 +3184,9 @@ public IAssignmentRuleInfo getAssignmentRuleInfo(UUID clusterId, UUID serverId, /** * Gets the list of cluster security profiles. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return list of cluster security profiles */ public List getSecurityProfiles(UUID clusterId) { @@ -2558,9 +3197,9 @@ public List getSecurityProfiles(UUID clusterId) { /** * Creates or updates a cluster security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param profile -security profile */ public void createSecurityProfile(UUID clusterId, ISecurityProfile profile) { @@ -2571,9 +3210,9 @@ public void createSecurityProfile(UUID clusterId, ISecurityProfile profile) { /** * Deletes a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name */ public void dropSecurityProfile(UUID clusterId, String spName) { @@ -2584,9 +3223,9 @@ public void dropSecurityProfile(UUID clusterId, String spName) { /** * Gets the list of virtual directories of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @return list of virtual directories */ @@ -2599,9 +3238,9 @@ public List getSecurityProfileVirtualDirectori /** * Creates or updates a virtual directory of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param directory - virtual directory */ public void createSecurityProfileVirtualDirectory( @@ -2613,9 +3252,9 @@ public void createSecurityProfileVirtualDirectory( /** * Deletes a virtual directory of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @param alias - virtual directory alias */ @@ -2627,9 +3266,9 @@ public void dropSecurityProfileVirtualDirectory(UUID clusterId, String spName, S /** * Gets the list of allowed COM classes of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @return infobase full infobase description */ @@ -2642,9 +3281,9 @@ public List getSecurityProfileComClasses( /** * Creates or updates an allowed COM class of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param comClass - allowed COM class */ public void createSecurityProfileComClass(UUID clusterId, ISecurityProfileCOMClass comClass) { @@ -2655,9 +3294,9 @@ public void createSecurityProfileComClass(UUID clusterId, ISecurityProfileCOMCla /** * Deletes an allowed COM class of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @param name - COM class name */ @@ -2669,9 +3308,9 @@ public void dropSecurityProfileComClass(UUID clusterId, String spName, String na /** * Gets the list of allowed add-ins of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @return list of allowed add-ins */ @@ -2683,9 +3322,9 @@ public List getSecurityProfileAddIns(UUID clusterId, Stri /** * Creates or updates an allowed add-in of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param addIn - allowed add-in */ public void createSecurityProfileAddIn(UUID clusterId, ISecurityProfileAddIn addIn) { @@ -2696,9 +3335,9 @@ public void createSecurityProfileAddIn(UUID clusterId, ISecurityProfileAddIn add /** * Deletes an allowed add-in of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName -security profile name * @param name -add-in name */ @@ -2710,9 +3349,9 @@ public void dropSecurityProfileAddIn(UUID clusterId, String spName, String name) /** * Gets the list of allowed unsafe external modules of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @return list of allowed external modules */ @@ -2725,9 +3364,9 @@ public List getSecurityProfileUnsafeExternalModu /** * Creates or updates an allowed unsafe external module of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param module - allowed external module */ public void createSecurityProfileUnsafeExternalModule( @@ -2739,9 +3378,9 @@ public void createSecurityProfileUnsafeExternalModule( /** * Deletes an allowed unsafe external module of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @param name - external module name */ @@ -2753,9 +3392,9 @@ public void dropSecurityProfileUnsafeExternalModule(UUID clusterId, String spNam /** * Gets the list of allowed applications of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @return list of allowed applications */ @@ -2768,9 +3407,9 @@ public List getSecurityProfileApplications( /** * Creates or updates an allowed application of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param app - allowed application */ public void createSecurityProfileApplication(UUID clusterId, ISecurityProfileApplication app) { @@ -2781,9 +3420,9 @@ public void createSecurityProfileApplication(UUID clusterId, ISecurityProfileApp /** * Deletes an allowed application of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @param name - application name */ @@ -2795,9 +3434,9 @@ public void dropSecurityProfileApplication(UUID clusterId, String spName, String /** * Gets the list of Internet resources of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @return infobase full infobase description */ @@ -2810,9 +3449,9 @@ public List getSecurityProfileInternetResource /** * Creates or updates an Internet resource of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param resource - Internet resource */ public void createSecurityProfileInternetResource( @@ -2824,9 +3463,9 @@ public void createSecurityProfileInternetResource( /** * Deletes an Internet resource of a security profile. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param spName - security profile name * @param name - Internet resource name */ @@ -2838,9 +3477,9 @@ public void dropSecurityProfileInternetResource(UUID clusterId, String spName, S /** * Gets the list of resource counters. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return list of cluster resource counters */ public List getResourceConsumptionCounters(UUID clusterId) { @@ -2851,9 +3490,9 @@ public List getResourceConsumptionCounters(UUID clu /** * Gets resource counters description. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param counterName - resource counter name * @return cluster resource counter info */ @@ -2866,9 +3505,9 @@ public IResourceConsumptionCounter getResourceConsumptionCounterInfo( /** * Creates or updates a resource counter. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param counter - resource counter info */ public void regResourceConsumptionCounter(UUID clusterId, IResourceConsumptionCounter counter) { @@ -2879,9 +3518,9 @@ public void regResourceConsumptionCounter(UUID clusterId, IResourceConsumptionCo /** * Deletes a resource counter. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param counterName - resource counter name */ public void unregResourceConsumptionCounter(UUID clusterId, String counterName) { @@ -2892,9 +3531,9 @@ public void unregResourceConsumptionCounter(UUID clusterId, String counterName) /** * Gets the list of resource limits. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @return list of cluster resource limits */ public List getResourceConsumptionLimits(UUID clusterId) { @@ -2905,9 +3544,9 @@ public List getResourceConsumptionLimits(UUID cluster /** * Gets resource limits description. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param limitName - resource limit name * @return cluster resource counter info */ @@ -2920,9 +3559,9 @@ public IResourceConsumptionLimit getResourceConsumptionLimitInfo( /** * Creates or updates a resource limit. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param limit - cluster resource limit info */ public void regResourceConsumptionLimit(UUID clusterId, IResourceConsumptionLimit limit) { @@ -2933,9 +3572,9 @@ public void regResourceConsumptionLimit(UUID clusterId, IResourceConsumptionLimi /** * Deletes a resource limits. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param limitName - resource limit name */ public void unregResourceConsumptionLimit(UUID clusterId, String limitName) { @@ -2946,9 +3585,9 @@ public void unregResourceConsumptionLimit(UUID clusterId, String limitName) { /** * Gets the list of resource counter values. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param counterName - resource counter name * @param object - object name * @return list of resource counter values @@ -2962,9 +3601,9 @@ public List getResourceConsumptionCounterValue /** * Deletes a resource counter values. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param counterName - resource counter name * @param object - object name */ @@ -2978,9 +3617,9 @@ public void clearResourceConsumptionCounterAccumulatedValues( /** * Gets the list of resource counter accumulated values. * - *

        Cluster authentication is required. + *

        Требует аутентификации в кластере * - * @param clusterId - cluster ID + * @param clusterId - ID кластера * @param counterName - resource counter name * @param object - object name * @return ist of resource counter accumulated values diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java index 8caba40..3fe02d1 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/SessionInfoExtended.java @@ -3,325 +3,469 @@ import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; import com._1c.v8.ibis.admin.ISessionInfo; import com._1c.v8.ibis.admin.IWorkingProcessInfo; -import java.util.LinkedHashMap; +import java.util.ArrayList; import java.util.List; -import java.util.Map; +import java.util.Objects; import java.util.UUID; - -/** Extend info for session. */ -public class SessionInfoExtended implements IInfoExtended { - - private static final String TITLE_USERNAME = - Messages.getString("SessionInfo.Username"); //$NON-NLS-1$ - private static final String TITLE_INFOBASE = - Messages.getString("SessionInfo.Infobase"); //$NON-NLS-1$ - private static final String TITLE_SESSION_N = - Messages.getString("SessionInfo.SessionN"); //$NON-NLS-1$ - private static final String TITLE_CONNECTION_N = - Messages.getString("SessionInfo.ConnectionN"); //$NON-NLS-1$ - private static final String TITLE_STARTED_AT = - Messages.getString("SessionInfo.StartedAt"); //$NON-NLS-1$ - private static final String TITLE_LAST_ACTIVE_AT = - Messages.getString("SessionInfo.LastActiveAt"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = - Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_APPLICATION = - Messages.getString("SessionInfo.Application"); //$NON-NLS-1$ - private static final String TITLE_SERVER = - Messages.getString("SessionInfo.Server"); //$NON-NLS-1$ - private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ - private static final String TITLE_PID = Messages.getString("SessionInfo.PID"); //$NON-NLS-1$ - private static final String TITLE_DB_PROC_INFO = - Messages.getString("SessionInfo.DbProcInfo"); //$NON-NLS-1$ - private static final String TITLE_DB_PROC_TOOK = - Messages.getString("SessionInfo.DbProcTook"); //$NON-NLS-1$ - private static final String TITLE_DB_PROC_TOOK_AT = - Messages.getString("SessionInfo.DbProcTookAt"); //$NON-NLS-1$ - private static final String TITLE_BLOCKED_BY_DBMS = - Messages.getString("SessionInfo.BlockedByDbms"); //$NON-NLS-1$ - private static final String TITLE_BLOCKED_BY_LS = - Messages.getString("SessionInfo.BlockedByLs"); //$NON-NLS-1$ - private static final String TITLE_DURATION_CURRENT_DBMS = - Messages.getString("SessionInfo.DurationCurrentDbms"); //$NON-NLS-1$ - private static final String TITLE_DURATION_LAST_5_MIN_DBMS = - Messages.getString("SessionInfo.DurationLast5MinDbms"); //$NON-NLS-1$ - private static final String TITLE_DURATION_ALL_DBMS = - Messages.getString("SessionInfo.DurationAllDbms"); //$NON-NLS-1$ - private static final String TITLE_DBMS_BYTES_LAST_5_MIN = - Messages.getString("SessionInfo.DbmsBytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_DBMS_BYTES_ALL = - Messages.getString("SessionInfo.DbmsBytesAll"); //$NON-NLS-1$ - private static final String TITLE_DURATION_CURRENT = - Messages.getString("SessionInfo.DurationCurrent"); //$NON-NLS-1$ - private static final String TITLE_DURATION_LAST_5_MIN = - Messages.getString("SessionInfo.DurationLast5Min"); //$NON-NLS-1$ - private static final String TITLE_DURATION_ALL = - Messages.getString("SessionInfo.DurationAll"); //$NON-NLS-1$ - private static final String TITLE_CALLS_LAST_5_MIN = - Messages.getString("SessionInfo.CallsLast5Min"); //$NON-NLS-1$ - private static final String TITLE_CALLS_ALL = - Messages.getString("SessionInfo.CallsAll"); //$NON-NLS-1$ - private static final String TITLE_BYTES_LAST_5_MIN = - Messages.getString("SessionInfo.BytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_BYTES_ALL = - Messages.getString("SessionInfo.BytesAll"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_CURRENT = - Messages.getString("SessionInfo.MemoryCurrent"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_LAST_5_MIN = - Messages.getString("SessionInfo.MemoryLast5Min"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_TOTAL = - Messages.getString("SessionInfo.MemoryTotal"); //$NON-NLS-1$ - private static final String TITLE_READ_BYTES_CURRENT = - Messages.getString("SessionInfo.ReadBytesCurrent"); //$NON-NLS-1$ - private static final String TITLE_READ_BYTES_LAST_5_MIN = - Messages.getString("SessionInfo.ReadBytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_READ_BYTES_TOTAL = - Messages.getString("SessionInfo.ReadBytesTotal"); //$NON-NLS-1$ - private static final String TITLE_WRITE_BYTES_CURRENT = - Messages.getString("SessionInfo.WriteBytesCurrent"); //$NON-NLS-1$ - private static final String TITLE_WRITE_BYTES_LAST_5_MIN = - Messages.getString("SessionInfo.WriteBytesLast5Min"); //$NON-NLS-1$ - private static final String TITLE_WRITE_BYTES_TOTAL = - Messages.getString("SessionInfo.WriteBytesTotal"); //$NON-NLS-1$ - private static final String TITLE_LICENSE = - Messages.getString("SessionInfo.License"); //$NON-NLS-1$ - private static final String TITLE_IS_SLEEP = - Messages.getString("SessionInfo.IsSleep"); //$NON-NLS-1$ - private static final String TITLE_SLEEP_AFTER = - Messages.getString("SessionInfo.SleepAfter"); //$NON-NLS-1$ - private static final String TITLE_KILL_AFTER = - Messages.getString("SessionInfo.KillAfter"); //$NON-NLS-1$ - private static final String TITLE_CLIENT_IP_ADDRESS = - Messages.getString("SessionInfo.ClientIPAddress"); //$NON-NLS-1$ - private static final String TITLE_DATA_SEPARATION = - Messages.getString("SessionInfo.DataSeparation"); //$NON-NLS-1$ - private static final String TITLE_CURRRENT_SERVICE_NAME = - Messages.getString("SessionInfo.CurrentServiceName"); //$NON-NLS-1$ - private static final String TITLE_DURATION_CURRENT_SERVICE = - Messages.getString("SessionInfo.DurationCurrentService"); //$NON-NLS-1$ - private static final String TITLE_DURATION_LAST_5_MIN_SERVICE = - Messages.getString("SessionInfo.DurationLast5MinService"); //$NON-NLS-1$ - private static final String TITLE_DURATION_ALL_SERVICE = - Messages.getString("SessionInfo.DurationAllService"); //$NON-NLS-1$ - private static final String TITLE_CPU_TIME_CURRENT = - Messages.getString("SessionInfo.CpuTimeCurrent"); //$NON-NLS-1$ - private static final String TITLE_CPU_TIME_LAST_5_MIN = - Messages.getString("SessionInfo.CpuTimeLast5Min"); //$NON-NLS-1$ - private static final String TITLE_CPU_TIME_ALL = - Messages.getString("SessionInfo.CpuTimeAll"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - UUID infobaseId; - ISessionInfo sessionInfo; - List connections; - - Map columnsMap = new LinkedHashMap<>(); +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableItem; +import ru.yanygin.clusterAdminLibrary.CellValue.CELL_VALUE_TYPE; + +/** Расширенная информация для сеанса. */ +public class SessionInfoExtended extends BaseInfoExtended { + + private static final String TITLE_USERNAME = "SessionInfo.Username"; //$NON-NLS-1$ + private static final String TITLE_INFOBASE = "SessionInfo.Infobase"; //$NON-NLS-1$ + private static final String TITLE_SESSION_N = "SessionInfo.SessionN"; //$NON-NLS-1$ + private static final String TITLE_CONNECTION_N = "SessionInfo.ConnectionN"; //$NON-NLS-1$ + private static final String TITLE_STARTED_AT = "SessionInfo.StartedAt"; //$NON-NLS-1$ + private static final String TITLE_LAST_ACTIVE_AT = "SessionInfo.LastActiveAt"; //$NON-NLS-1$ + private static final String TITLE_COMPUTER = "SessionInfo.Computer"; //$NON-NLS-1$ + private static final String TITLE_APPLICATION = "SessionInfo.Application"; //$NON-NLS-1$ + private static final String TITLE_SERVER = "SessionInfo.Server"; //$NON-NLS-1$ + private static final String TITLE_PORT = "SessionInfo.Port"; //$NON-NLS-1$ + private static final String TITLE_PID = "SessionInfo.PID"; //$NON-NLS-1$ + private static final String TITLE_DB_PROC_INFO = "SessionInfo.DbProcInfo"; //$NON-NLS-1$ + private static final String TITLE_DB_PROC_TOOK = "SessionInfo.DbProcTook"; //$NON-NLS-1$ + private static final String TITLE_DB_PROC_TOOK_AT = "SessionInfo.DbProcTookAt"; //$NON-NLS-1$ + private static final String TITLE_BLOCKED_BY_DBMS = "SessionInfo.BlockedByDbms"; //$NON-NLS-1$ + private static final String TITLE_BLOCKED_BY_LS = "SessionInfo.BlockedByLs"; //$NON-NLS-1$ + private static final String TITLE_DURATION_CURRENT_DBMS = "SessionInfo.DurationCurrentDbms"; //$NON-NLS-1$ + private static final String TITLE_DURATION_LAST_5_MIN_DBMS = "SessionInfo.DurationLast5MinDbms"; //$NON-NLS-1$ + private static final String TITLE_DURATION_ALL_DBMS = "SessionInfo.DurationAllDbms"; //$NON-NLS-1$ + private static final String TITLE_DBMS_BYTES_LAST_5_MIN = "SessionInfo.DbmsBytesLast5Min"; //$NON-NLS-1$ + private static final String TITLE_DBMS_BYTES_ALL = "SessionInfo.DbmsBytesAll"; //$NON-NLS-1$ + private static final String TITLE_DURATION_CURRENT = "SessionInfo.DurationCurrent"; //$NON-NLS-1$ + private static final String TITLE_DURATION_LAST_5_MIN = "SessionInfo.DurationLast5Min"; //$NON-NLS-1$ + private static final String TITLE_DURATION_ALL = "SessionInfo.DurationAll"; //$NON-NLS-1$ + private static final String TITLE_CALLS_LAST_5_MIN = "SessionInfo.CallsLast5Min"; //$NON-NLS-1$ + private static final String TITLE_CALLS_ALL = "SessionInfo.CallsAll"; //$NON-NLS-1$ + private static final String TITLE_BYTES_LAST_5_MIN = "SessionInfo.BytesLast5Min"; //$NON-NLS-1$ + private static final String TITLE_BYTES_ALL = "SessionInfo.BytesAll"; //$NON-NLS-1$ + private static final String TITLE_MEMORY_CURRENT = "SessionInfo.MemoryCurrent"; //$NON-NLS-1$ + private static final String TITLE_MEMORY_LAST_5_MIN = "SessionInfo.MemoryLast5Min"; //$NON-NLS-1$ + private static final String TITLE_MEMORY_TOTAL = "SessionInfo.MemoryTotal"; //$NON-NLS-1$ + private static final String TITLE_READ_BYTES_CURRENT = "SessionInfo.ReadBytesCurrent"; //$NON-NLS-1$ + private static final String TITLE_READ_BYTES_LAST_5_MIN = "SessionInfo.ReadBytesLast5Min"; //$NON-NLS-1$ + private static final String TITLE_READ_BYTES_TOTAL = "SessionInfo.ReadBytesTotal"; //$NON-NLS-1$ + private static final String TITLE_WRITE_BYTES_CURRENT = "SessionInfo.WriteBytesCurrent"; //$NON-NLS-1$ + private static final String TITLE_WRITE_BYTES_LAST_5_MIN = "SessionInfo.WriteBytesLast5Min"; //$NON-NLS-1$ + private static final String TITLE_WRITE_BYTES_TOTAL = "SessionInfo.WriteBytesTotal"; //$NON-NLS-1$ + private static final String TITLE_LICENSE = "SessionInfo.License"; //$NON-NLS-1$ + private static final String TITLE_IS_SLEEP = "SessionInfo.IsSleep"; //$NON-NLS-1$ + private static final String TITLE_SLEEP_AFTER = "SessionInfo.SleepAfter"; //$NON-NLS-1$ + private static final String TITLE_KILL_AFTER = "SessionInfo.KillAfter"; //$NON-NLS-1$ + private static final String TITLE_CLIENT_IP_ADDRESS = "SessionInfo.ClientIPAddress"; //$NON-NLS-1$ + private static final String TITLE_DATA_SEPARATION = "SessionInfo.DataSeparation"; //$NON-NLS-1$ + private static final String TITLE_CURRRENT_SERVICE_NAME = "SessionInfo.CurrentServiceName"; //$NON-NLS-1$ + private static final String TITLE_DURATION_CURRENT_SERVICE = "SessionInfo.DurationCurrentService"; //$NON-NLS-1$ + private static final String TITLE_DURATION_LAST_5_MIN_SERVICE = "SessionInfo.DurationLast5MinService"; //$NON-NLS-1$ + private static final String TITLE_DURATION_ALL_SERVICE = "SessionInfo.DurationAllService"; //$NON-NLS-1$ + private static final String TITLE_CPU_TIME_CURRENT = "SessionInfo.CpuTimeCurrent"; //$NON-NLS-1$ + private static final String TITLE_CPU_TIME_LAST_5_MIN = "SessionInfo.CpuTimeLast5Min"; //$NON-NLS-1$ + private static final String TITLE_CPU_TIME_ALL = "SessionInfo.CpuTimeAll"; //$NON-NLS-1$ + + private static Config commonConfig = Config.currentConfig; + private static ColumnProperties columnProperties = + commonConfig.getColumnsProperties(SessionInfoExtended.class); + + private static final String DEFAULT_ICON_FILENAME = "user.png"; //$NON-NLS-1$ + private static final String SLEEP_ICON_FILENAME = "sleepUser.png"; //$NON-NLS-1$ + private static final String SERVICE_ICON_FILENAME = "service.png"; //$NON-NLS-1$ + private static Image defaultIcon; + private static Image sleepUserIcon; + private static Image serviceIcon; + + private static final String TAB_TEXT_TEMPLATE = + Messages.getString("TabText.SessionsCount"); //$NON-NLS-1$ + + private static List watchedSessions = new ArrayList<>(); + + private static TabItem currentTab; + private static int itemCount; + + private ISessionInfo sessionInfo; + + private String connectionNumber = ""; + private String license = ""; + private String wpHostName = ""; + private String wpPort = ""; + private String wpPid = ""; + private String infobaseName = ""; /** - * Create extended info for working server. + * Создание расширенной информации для сеанса. * * @param server - server * @param clusterId - cluster ID - * @param infobaseId - infobase ID * @param sessionInfo - session info - * @param connections - list of connections - * @param columnsMap - columns map */ - public SessionInfoExtended( - Server server, - UUID clusterId, - UUID infobaseId, - ISessionInfo sessionInfo, - List connections, - Map columnsMap) { + public SessionInfoExtended(Server server, UUID clusterId, ISessionInfo sessionInfo) { this.server = server; this.clusterId = clusterId; - this.infobaseId = infobaseId; this.sessionInfo = sessionInfo; - this.connections = connections; - this.columnsMap = columnsMap; - } - /** - * Init columns name. - * - * @param columnsMap - sample map with columns name - */ - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_USERNAME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_INFOBASE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SESSION_N, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTION_N, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_STARTED_AT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LAST_ACTIVE_AT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_APPLICATION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SERVER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PID, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_DB_PROC_INFO, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DB_PROC_TOOK, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DB_PROC_TOOK_AT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_BLOCKED_BY_DBMS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_BLOCKED_BY_LS, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_DURATION_CURRENT_DBMS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_LAST_5_MIN_DBMS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_ALL_DBMS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DBMS_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DBMS_BYTES_ALL, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_DURATION_CURRENT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_ALL, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_CALLS_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CALLS_ALL, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_BYTES_ALL, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_MEMORY_CURRENT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MEMORY_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MEMORY_TOTAL, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_READ_BYTES_CURRENT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_READ_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_READ_BYTES_TOTAL, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_WRITE_BYTES_CURRENT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_WRITE_BYTES_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_WRITE_BYTES_TOTAL, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_LICENSE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_IS_SLEEP, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SLEEP_AFTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_KILL_AFTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CLIENT_IP_ADDRESS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DATA_SEPARATION, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_CURRRENT_SERVICE_NAME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_CURRENT_SERVICE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_LAST_5_MIN_SERVICE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DURATION_ALL_SERVICE, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_CPU_TIME_CURRENT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CPU_TIME_LAST_5_MIN, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CPU_TIME_ALL, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initSessionsColumnCount(columnsMap.size()); - } + switch (sessionInfo.getAppId()) { + case Server.THIN_CLIENT: + case Server.THICK_CLIENT: + case Server.DESIGNER: + this.currentIcon = sessionInfo.getHibernate() ? sleepUserIcon : defaultIcon; + break; + case Server.SERVER_CONSOLE: + case Server.RAS_CONSOLE: + case Server.JOBSCHEDULER: + this.currentIcon = serviceIcon; + break; + default: + this.currentIcon = sessionInfo.getHibernate() ? sleepUserIcon : defaultIcon; + } - @Override - public String[] getExtendedInfo() { + computeSecondaryInfo(); + computeExtendedInfoData(); + } - if (this.infobaseId == null) { - this.infobaseId = sessionInfo.getInfoBaseId(); - } + private void computeSecondaryInfo() { - // connection - var connectionNumber = ""; //$NON-NLS-1$ - if (!sessionInfo.getConnectionId().equals(emptyUuid)) { + if (!sessionInfo.getConnectionId().equals(Helper.EMPTY_UUID)) { IInfoBaseConnectionShort connectionInfoShort = server.getConnectionInfoShort(clusterId, sessionInfo.getConnectionId()); - connectionNumber = String.valueOf(connectionInfoShort.getConnId()); + connectionNumber = + Objects.nonNull(connectionInfoShort) + ? String.valueOf(connectionInfoShort.getConnId()) + : ""; //$NON-NLS-1$ } - // Working Process - var wpHostName = ""; //$NON-NLS-1$ - var wpMainPort = ""; //$NON-NLS-1$ - var wpPid = ""; //$NON-NLS-1$ - if (!sessionInfo.getWorkingProcessId().equals(emptyUuid)) { + license = + sessionInfo.getLicenses().isEmpty() + ? "" //$NON-NLS-1$ + : sessionInfo.getLicenses().get(0).getFullPresentation(); + + if (!sessionInfo.getWorkingProcessId().equals(Helper.EMPTY_UUID)) { IWorkingProcessInfo wpInfo = server.getWorkingProcessInfo(clusterId, sessionInfo.getWorkingProcessId()); - wpHostName = wpInfo.getHostName(); - wpMainPort = Integer.toString(wpInfo.getMainPort()); - wpPid = wpInfo.getPid(); + if (wpInfo != null) { + wpHostName = wpInfo.getHostName(); + wpPort = Integer.toString(wpInfo.getMainPort()); + wpPid = wpInfo.getPid(); + } } - // license - var license = - sessionInfo.getLicenses().isEmpty() - ? "" //$NON-NLS-1$ - : sessionInfo.getLicenses().get(0).getFullPresentation(); + infobaseName = server.getInfoBaseName(clusterId, sessionInfo.getInfoBaseId()); + } - Map session = new LinkedHashMap<>(); - session.putAll(columnsMap); - - session.put(TITLE_USERNAME, sessionInfo.getUserName()); - session.put(TITLE_INFOBASE, server.getInfoBaseName(clusterId, infobaseId)); - session.put(TITLE_SESSION_N, Integer.toString(sessionInfo.getSessionId())); - session.put(TITLE_CONNECTION_N, connectionNumber); - session.put(TITLE_STARTED_AT, dateToString(sessionInfo.getStartedAt())); - session.put(TITLE_LAST_ACTIVE_AT, dateToString(sessionInfo.getLastActiveAt())); - session.put(TITLE_COMPUTER, sessionInfo.getHost()); - session.put(TITLE_APPLICATION, server.getApplicationName(sessionInfo.getAppId())); - session.put(TITLE_SERVER, wpHostName); - session.put(TITLE_PORT, wpMainPort); - session.put(TITLE_PID, wpPid); - - session.put(TITLE_DB_PROC_INFO, sessionInfo.getDbProcInfo()); - session.put(TITLE_DB_PROC_TOOK, double3ToString(sessionInfo.getDbProcTook())); - session.put(TITLE_DB_PROC_TOOK_AT, dateToString(sessionInfo.getDbProcTookAt())); - session.put(TITLE_BLOCKED_BY_DBMS, Integer.toString(sessionInfo.getBlockedByDbms())); - session.put(TITLE_BLOCKED_BY_LS, Integer.toString(sessionInfo.getBlockedByLs())); - - session.put( - TITLE_DURATION_CURRENT_DBMS, millisecondToString(sessionInfo.getDurationCurrentDbms())); - session.put( - TITLE_DURATION_LAST_5_MIN_DBMS, millisecondToString(sessionInfo.getDurationLast5MinDbms())); - session.put(TITLE_DURATION_ALL_DBMS, millisecondToString(sessionInfo.getDurationAllDbms())); - - session.put(TITLE_DBMS_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getDbmsBytesLast5Min())); - session.put(TITLE_DBMS_BYTES_ALL, longToStringGroup(sessionInfo.getDbmsBytesAll())); - - session.put(TITLE_DURATION_CURRENT, millisecondToString(sessionInfo.getDurationCurrent())); - session.put(TITLE_DURATION_LAST_5_MIN, millisecondToString(sessionInfo.getDurationLast5Min())); - session.put(TITLE_DURATION_ALL, millisecondToString(sessionInfo.getDurationAll())); - - session.put(TITLE_CALLS_LAST_5_MIN, Long.toString(sessionInfo.getCallsLast5Min())); - session.put(TITLE_CALLS_ALL, Integer.toString(sessionInfo.getCallsAll())); - - session.put(TITLE_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getBytesLast5Min())); - session.put(TITLE_BYTES_ALL, longToStringGroup(sessionInfo.getBytesAll())); - - session.put(TITLE_MEMORY_CURRENT, longToStringGroup(sessionInfo.getMemoryCurrent())); - session.put(TITLE_MEMORY_LAST_5_MIN, longToStringGroup(sessionInfo.getMemoryLast5Min())); - session.put(TITLE_MEMORY_TOTAL, longToStringGroup(sessionInfo.getMemoryTotal())); - - session.put(TITLE_READ_BYTES_CURRENT, longToStringGroup(sessionInfo.getReadBytesCurrent())); - session.put(TITLE_READ_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getReadBytesLast5Min())); - session.put(TITLE_READ_BYTES_TOTAL, longToStringGroup(sessionInfo.getReadBytesTotal())); - session.put(TITLE_WRITE_BYTES_CURRENT, longToStringGroup(sessionInfo.getWriteBytesCurrent())); - session.put( - TITLE_WRITE_BYTES_LAST_5_MIN, longToStringGroup(sessionInfo.getWriteBytesLast5Min())); - session.put(TITLE_WRITE_BYTES_TOTAL, longToStringGroup(sessionInfo.getWriteBytesTotal())); - - session.put(TITLE_LICENSE, license); - session.put(TITLE_IS_SLEEP, Boolean.toString(sessionInfo.getHibernate())); - session.put(TITLE_SLEEP_AFTER, Integer.toString(sessionInfo.getPassiveSessionHibernateTime())); - session.put( - TITLE_KILL_AFTER, Integer.toString(sessionInfo.getHibernateSessionTerminationTime())); - session.put(TITLE_CLIENT_IP_ADDRESS, sessionInfo.getClientIPAddress()); - session.put(TITLE_DATA_SEPARATION, sessionInfo.getDataSeparation()); - - session.put(TITLE_CURRRENT_SERVICE_NAME, sessionInfo.getCurrentServiceName()); - session.put( + protected void computeExtendedInfoData() { + + columnProperties.prepareDataMap(data); + + putData(TITLE_USERNAME, sessionInfo.getUserName(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_INFOBASE, infobaseName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_SESSION_N, sessionInfo.getSessionId(), CELL_VALUE_TYPE.INT); + putData(TITLE_CONNECTION_N, connectionNumber, CELL_VALUE_TYPE.TEXT); + putData(TITLE_STARTED_AT, sessionInfo.getStartedAt(), CELL_VALUE_TYPE.DATE); + putData(TITLE_LAST_ACTIVE_AT, sessionInfo.getLastActiveAt(), CELL_VALUE_TYPE.DATE); + putData(TITLE_COMPUTER, sessionInfo.getHost(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_APPLICATION, getApplicationName(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_SERVER, wpHostName, CELL_VALUE_TYPE.TEXT); + putData(TITLE_PORT, wpPort, CELL_VALUE_TYPE.TEXT); + putData(TITLE_PID, wpPid, CELL_VALUE_TYPE.TEXT); + + putData(TITLE_DB_PROC_INFO, sessionInfo.getDbProcInfo(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_DB_PROC_TOOK, sessionInfo.getDbProcTook(), CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData(TITLE_DB_PROC_TOOK_AT, sessionInfo.getDbProcTookAt(), CELL_VALUE_TYPE.DATE); + putData(TITLE_BLOCKED_BY_DBMS, sessionInfo.getBlockedByDbms(), CELL_VALUE_TYPE.INT); + putData(TITLE_BLOCKED_BY_LS, sessionInfo.getBlockedByLs(), CELL_VALUE_TYPE.INT); + + putData( + TITLE_DURATION_CURRENT_DBMS, + sessionInfo.getDurationCurrentDbms(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData( + TITLE_DURATION_LAST_5_MIN_DBMS, + sessionInfo.getDurationLast5MinDbms(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData( + TITLE_DURATION_ALL_DBMS, sessionInfo.getDurationAllDbms(), CELL_VALUE_TYPE.DECIMAL_3_CHAR); + + putData( + TITLE_DBMS_BYTES_LAST_5_MIN, + sessionInfo.getDbmsBytesLast5Min(), + CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_DBMS_BYTES_ALL, sessionInfo.getDbmsBytesAll(), CELL_VALUE_TYPE.LONG_GROUP); + + putData( + TITLE_DURATION_CURRENT, sessionInfo.getDurationCurrent(), CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData( + TITLE_DURATION_LAST_5_MIN, + sessionInfo.getDurationLast5Min(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData(TITLE_DURATION_ALL, sessionInfo.getDurationAll(), CELL_VALUE_TYPE.DECIMAL_3_CHAR); + + putData(TITLE_CALLS_LAST_5_MIN, sessionInfo.getCallsLast5Min(), CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_CALLS_ALL, sessionInfo.getCallsAll(), CELL_VALUE_TYPE.INT_GROUP); + + putData(TITLE_BYTES_LAST_5_MIN, sessionInfo.getBytesLast5Min(), CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_BYTES_ALL, sessionInfo.getBytesAll(), CELL_VALUE_TYPE.LONG_GROUP); + + putData(TITLE_MEMORY_CURRENT, sessionInfo.getMemoryCurrent(), CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_MEMORY_LAST_5_MIN, sessionInfo.getMemoryLast5Min(), CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_MEMORY_TOTAL, sessionInfo.getMemoryTotal(), CELL_VALUE_TYPE.LONG_GROUP); + + putData( + TITLE_READ_BYTES_CURRENT, sessionInfo.getReadBytesCurrent(), CELL_VALUE_TYPE.LONG_GROUP); + putData( + TITLE_READ_BYTES_LAST_5_MIN, + sessionInfo.getReadBytesLast5Min(), + CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_READ_BYTES_TOTAL, sessionInfo.getReadBytesTotal(), CELL_VALUE_TYPE.LONG_GROUP); + putData( + TITLE_WRITE_BYTES_CURRENT, sessionInfo.getWriteBytesCurrent(), CELL_VALUE_TYPE.LONG_GROUP); + putData( + TITLE_WRITE_BYTES_LAST_5_MIN, + sessionInfo.getWriteBytesLast5Min(), + CELL_VALUE_TYPE.LONG_GROUP); + putData(TITLE_WRITE_BYTES_TOTAL, sessionInfo.getWriteBytesTotal(), CELL_VALUE_TYPE.LONG_GROUP); + + putData(TITLE_LICENSE, license, CELL_VALUE_TYPE.TEXT); + putData(TITLE_IS_SLEEP, sessionInfo.getHibernate(), CELL_VALUE_TYPE.BOOLEAN); + putData(TITLE_SLEEP_AFTER, sessionInfo.getPassiveSessionHibernateTime(), CELL_VALUE_TYPE.INT); + putData( + TITLE_KILL_AFTER, sessionInfo.getHibernateSessionTerminationTime(), CELL_VALUE_TYPE.INT); + putData(TITLE_CLIENT_IP_ADDRESS, getClientIpAddress(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_DATA_SEPARATION, sessionInfo.getDataSeparation(), CELL_VALUE_TYPE.TEXT); + + putData(TITLE_CURRRENT_SERVICE_NAME, sessionInfo.getCurrentServiceName(), CELL_VALUE_TYPE.TEXT); + putData( TITLE_DURATION_CURRENT_SERVICE, - millisecondToString(sessionInfo.getDurationCurrentService())); - session.put( + sessionInfo.getDurationCurrentService(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData( TITLE_DURATION_LAST_5_MIN_SERVICE, - millisecondToString(sessionInfo.getDurationLast5MinService())); - session.put( - TITLE_DURATION_ALL_SERVICE, millisecondToString(sessionInfo.getDurationAllService())); + sessionInfo.getDurationLast5MinService(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData( + TITLE_DURATION_ALL_SERVICE, + sessionInfo.getDurationAllService(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + + putData( + TITLE_CPU_TIME_CURRENT, sessionInfo.getCpuTimeCurrent(), CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData( + TITLE_CPU_TIME_LAST_5_MIN, + sessionInfo.getCpuTimeLast5Min(), + CELL_VALUE_TYPE.DECIMAL_3_CHAR); + putData(TITLE_CPU_TIME_ALL, sessionInfo.getCpuTimeAll(), CELL_VALUE_TYPE.DECIMAL_3_CHAR); + } - session.put(TITLE_CPU_TIME_CURRENT, millisecondToString(sessionInfo.getCpuTimeCurrent())); - session.put(TITLE_CPU_TIME_LAST_5_MIN, millisecondToString(sessionInfo.getCpuTimeLast5Min())); - session.put(TITLE_CPU_TIME_ALL, millisecondToString(sessionInfo.getCpuTimeAll())); + @Override + public void addToTable(Table table, int index) { + + TableItem tableItem = createTableItem(table, index, sessionInfo.getStartedAt()); + + if (commonConfig.isShadeSleepingSessions() && sessionInfo.getHibernate()) { + tableItem.setForeground(shadowItemColor); + } - return session.values().toArray(new String[0]); + if (watchedSessions.contains(generateWatchId())) { + tableItem.setChecked(true); + tableItem.setForeground(watchedSessionColor); + } } + + /** + * Переключение у сеанса режима наблюдения. + * + * @param item - строка таблицы - сеанс + * @param isChecked - значение + */ + public void switchWatching(TableItem item, Boolean isChecked) { + String watchId = generateWatchId(); + if (Boolean.TRUE.equals(isChecked)) { + watchedSessions.add(watchId); + item.setForeground(watchedSessionColor); + } else { + watchedSessions.remove(watchId); + item.setForeground(standardColor); + } + } + + private String generateWatchId() { + + String[] columnsName = columnProperties.getColumnsName(); + + String infobase = data.get(columnsName[1]).value; + String sn = data.get(columnsName[2]).value; + + return infobase.concat("*").concat(sn); //$NON-NLS-1$ + } + + /** + * Получение SessionInfo. + * + * @return sessionInfo + */ + public ISessionInfo getSessionInfo() { + return sessionInfo; + } + + /** + * Получение номера соединения. + * + * @return Номер соединения + */ + public String getConnectionNumber() { + return connectionNumber; + } + + /** + * Получение лицензии. + * + * @return лицензия + */ + public String getLicense() { + return license; + } + + /** + * Получение имени хоста рабочего процесса. + * + * @return имя хоста рабочего процесса + */ + public String getWorkingProcessHostName() { + return wpHostName; + } + + /** + * Получение порта рабочего процесса. + * + * @return порт рабочего процесса + */ + public String getWorkingProcessPort() { + return wpPort; + } + + /** + * Получение PID рабочего процесса. + * + * @return PID рабочего процесса + */ + public String getWorkingProcessPid() { + return wpPid; + } + + /** + * Получение имени информационной базы. + * + * @return имя информационной базы + */ + public String getInfobaseName() { + return infobaseName; + } + + /** + * Получение IP адреса клиента. + * + * @return IP адрес клиента + */ + public String getClientIpAddress() { + return sessionInfo.getClientIPAddress() == null + ? "" //$NON-NLS-1$ + : sessionInfo.getClientIPAddress(); // 8.3.17+ + } + + /** + * Получение наименования приложения клиента. + * + * @return наименование приложения клиента + */ + public String getApplicationName() { + return server.getApplicationName(sessionInfo.getAppId()); + } + + /** Инициализация имен колонок. */ + protected static void initColumnsName() { + + columnProperties.addColumnsInMap( + TITLE_USERNAME, + TITLE_INFOBASE, + TITLE_SESSION_N, + TITLE_CONNECTION_N, + TITLE_STARTED_AT, + TITLE_LAST_ACTIVE_AT, + TITLE_COMPUTER, + TITLE_APPLICATION, + TITLE_SERVER, + TITLE_PORT, + TITLE_PID, + TITLE_DB_PROC_INFO, + TITLE_DB_PROC_TOOK, + TITLE_DB_PROC_TOOK_AT, + TITLE_BLOCKED_BY_DBMS, + TITLE_BLOCKED_BY_LS, + TITLE_DURATION_CURRENT_DBMS, + TITLE_DURATION_LAST_5_MIN_DBMS, + TITLE_DURATION_ALL_DBMS, + TITLE_DBMS_BYTES_LAST_5_MIN, + TITLE_DBMS_BYTES_ALL, + TITLE_DURATION_CURRENT, + TITLE_DURATION_LAST_5_MIN, + TITLE_DURATION_ALL, + TITLE_CALLS_LAST_5_MIN, + TITLE_CALLS_ALL, + TITLE_BYTES_LAST_5_MIN, + TITLE_BYTES_ALL, + TITLE_MEMORY_CURRENT, + TITLE_MEMORY_LAST_5_MIN, + TITLE_MEMORY_TOTAL, + TITLE_READ_BYTES_CURRENT, + TITLE_READ_BYTES_LAST_5_MIN, + TITLE_READ_BYTES_TOTAL, + TITLE_WRITE_BYTES_CURRENT, + TITLE_WRITE_BYTES_LAST_5_MIN, + TITLE_WRITE_BYTES_TOTAL, + TITLE_LICENSE, + TITLE_IS_SLEEP, + TITLE_SLEEP_AFTER, + TITLE_KILL_AFTER, + TITLE_CLIENT_IP_ADDRESS, + TITLE_DATA_SEPARATION, + TITLE_CURRRENT_SERVICE_NAME, + TITLE_DURATION_CURRENT_SERVICE, + TITLE_DURATION_LAST_5_MIN_SERVICE, + TITLE_DURATION_ALL_SERVICE, + TITLE_CPU_TIME_CURRENT, + TITLE_CPU_TIME_LAST_5_MIN, + TITLE_CPU_TIME_ALL); + + defaultIcon = Helper.getImage(DEFAULT_ICON_FILENAME); + sleepUserIcon = Helper.getImage(SLEEP_ICON_FILENAME); + serviceIcon = Helper.getImage(SERVICE_ICON_FILENAME); + } + + /** + * Обновление заголовка вкладки. + * + * @param count - количество элементов + */ + protected static void updateTabText(int count) { + itemCount = count; + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount)); + } + + /** Сброс заголовка вкладки на неизвестное количество элементов. */ + protected static void resetTabTextCount() { + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount + "*")); + } + + /** + * Установка связи с вкладкой TabItem. + * + * @param tabitem вкладка Tabitem + */ + protected static void linkTabItem(TabItem tabitem) { + currentTab = tabitem; + } + } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/UserPassPair.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/UserPassPair.java new file mode 100644 index 0000000..31e12b3 --- /dev/null +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/UserPassPair.java @@ -0,0 +1,137 @@ +package ru.yanygin.clusterAdminLibrary; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; +import ru.yanygin.clusterAdminLibrary.Server.SaveCredentialsVariant; + +/** Пара логин-пароль с доп. информацией. */ +public class UserPassPair { + + @SerializedName("Username") + @Expose + private String username = ""; + + @SerializedName("Password") + @Expose + private String password = ""; + + @SerializedName("Description") + @Expose + private String description = ""; + + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ + private static final String HIDDEN_PASSWORD = "***"; //$NON-NLS-1$ + + /** Создание экземпляра с пустыми логин/паролем. */ + public UserPassPair() {} + + /** + * Создание экземпляра логин/пароля. + * + * @param username - логин + * @param password - пароль + */ + public UserPassPair(String username, String password) { + this.username = username; + this.password = password; + } + + /** + * Создание экземпляра логин/пароля с доп. информацией. + * + * @param username - логин + * @param password - пароль + * @param description - описание, доп. информация + */ + public UserPassPair(String username, String password, String description) { + this.username = username; + this.password = password; + this.description = description; + } + + /** + * Получение имени пользователя. + * + * @return имя пользователя + */ + public String getUsername() { + return username; + } + + /** + * Получение пароля. + * + * @return пароль + */ + public String getPassword() { + return password; + } + + /** + * Получение пароля. + * + * @param showPasswordMode - если истина возвращается пароль, иначе звездочки + * @return пароль + */ + public String getPassword(Boolean showPasswordMode) { + return Boolean.TRUE.equals(showPasswordMode) ? password : HIDDEN_PASSWORD; + } + + /** + * Получение описания, доп информации. + * + * @return описание + */ + public String getDescription() { + return description; + } + + /** + * Очистка имени пользователя и пароля. + * + * @param variant - вариант хранения логин/пароля + */ + public void clear(SaveCredentialsVariant variant) { + + switch (variant) { + case DISABLE: + this.username = EMPTY_STRING; + this.password = EMPTY_STRING; + break; + + case NAME: + this.password = EMPTY_STRING; + break; + + default: + break; + } + } + + /** + * Установка имени пользователя. + * + * @param username - имя пользователя + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Установка нового паролядля пользователя. + * + * @param password - пароль + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Описание, доп информация. + * + * @param description - описание + */ + public void setDescription(String description) { + this.description = description; + } +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java index 57379ba..eb1121f 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingProcessInfoExtended.java @@ -1,148 +1,122 @@ package ru.yanygin.clusterAdminLibrary; import com._1c.v8.ibis.admin.IWorkingProcessInfo; -import java.util.LinkedHashMap; -import java.util.Map; import java.util.UUID; - -/** Extend info for working process. */ -public class WorkingProcessInfoExtended implements IInfoExtended { - - private static final String TITLE_COMPUTER = - Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_PORT = Messages.getString("SessionInfo.Port"); //$NON-NLS-1$ - private static final String TITLE_USING = Messages.getString("WPInfo.Using"); //$NON-NLS-1$ - private static final String TITLE_ENABLES = Messages.getString("WPInfo.Enabled"); //$NON-NLS-1$ - private static final String TITLE_ACTIVE = Messages.getString("WPInfo.Active"); //$NON-NLS-1$ - private static final String TITLE_PID = Messages.getString("SessionInfo.PID"); //$NON-NLS-1$ - private static final String TITLE_MEMORY = Messages.getString("WPInfo.Memory"); //$NON-NLS-1$ - private static final String TITLE_MEMORY_EXCEEDED = - Messages.getString("WPInfo.MemoryExceeded"); //$NON-NLS-1$ - private static final String TITLE_AVAILABLE_PERFORMANCE = - Messages.getString("WPInfo.AvailablePerformance"); //$NON-NLS-1$ - private static final String TITLE_LICENSE = - Messages.getString("SessionInfo.License"); //$NON-NLS-1$ - private static final String TITLE_STARTED_AT = - Messages.getString("SessionInfo.StartedAt"); //$NON-NLS-1$ - private static final String TITLE_CONNECTIONS_COUNT = - Messages.getString("WPInfo.ConnectionsCount"); //$NON-NLS-1$ - private static final String TITLE_BACK_CALL_TIME = - Messages.getString("WPInfo.BackCallTime"); //$NON-NLS-1$ - private static final String TITLE_SERVER_CALL_TIME = - Messages.getString("WPInfo.ServerCallTime"); //$NON-NLS-1$ - private static final String TITLE_DB_CALL_TIME = - Messages.getString("WPInfo.DBCallTime"); //$NON-NLS-1$ - private static final String TITLE_CALL_TIME = - Messages.getString("WPInfo.CallTime"); //$NON-NLS-1$ - private static final String TITLE_LOCK_CALL_TIME = - Messages.getString("WPInfo.LockCallTime"); //$NON-NLS-1$ - private static final String TITLE_CLIENT_THREADS = - Messages.getString("WPInfo.ClientThreads"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - IWorkingProcessInfo workingProcess; - - Map columnsMap = new LinkedHashMap<>(); +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import ru.yanygin.clusterAdminLibrary.CellValue.CELL_VALUE_TYPE; + +/** Расширенная информация для рабочего процесса. */ +public class WorkingProcessInfoExtended extends BaseInfoExtended { + + private static final String TITLE_COMPUTER = "SessionInfo.Computer"; //$NON-NLS-1$ + private static final String TITLE_PORT = "SessionInfo.Port"; //$NON-NLS-1$ + private static final String TITLE_USING = "WPInfo.Using"; //$NON-NLS-1$ + private static final String TITLE_ENABLES = "WPInfo.Enabled"; //$NON-NLS-1$ + private static final String TITLE_ACTIVE = "WPInfo.Active"; //$NON-NLS-1$ + private static final String TITLE_PID = "SessionInfo.PID"; //$NON-NLS-1$ + private static final String TITLE_MEMORY = "WPInfo.Memory"; //$NON-NLS-1$ + private static final String TITLE_MEMORY_EXCEEDED = "WPInfo.MemoryExceeded"; //$NON-NLS-1$ + private static final String TITLE_AVAILABLE_PERFORMANCE = "WPInfo.AvailablePerformance"; //$NON-NLS-1$ + private static final String TITLE_LICENSE = "SessionInfo.License"; //$NON-NLS-1$ + private static final String TITLE_STARTED_AT = "SessionInfo.StartedAt"; //$NON-NLS-1$ + private static final String TITLE_CONNECTIONS_COUNT = "WPInfo.ConnectionsCount"; //$NON-NLS-1$ + private static final String TITLE_BACK_CALL_TIME = "WPInfo.BackCallTime"; //$NON-NLS-1$ + private static final String TITLE_SERVER_CALL_TIME = "WPInfo.ServerCallTime"; //$NON-NLS-1$ + private static final String TITLE_DB_CALL_TIME = "WPInfo.DBCallTime"; //$NON-NLS-1$ + private static final String TITLE_CALL_TIME = "WPInfo.CallTime"; //$NON-NLS-1$ + private static final String TITLE_LOCK_CALL_TIME = "WPInfo.LockCallTime"; //$NON-NLS-1$ + private static final String TITLE_CLIENT_THREADS = "WPInfo.ClientThreads"; //$NON-NLS-1$ + + private static Config commonConfig = Config.currentConfig; + private static ColumnProperties columnProperties = + commonConfig.getColumnsProperties(WorkingProcessInfoExtended.class); + + private IWorkingProcessInfo workingProcessInfo; + + private static final String DEFAULT_ICON_FILENAME = "wp.png"; + private static Image defaultIcon; + + private static final String TAB_TEXT_TEMPLATE = + Messages.getString("TabText.WorkingProcessesCount"); //$NON-NLS-1$ + + private static TabItem currentTab; + private static int itemCount; /** - * Create extended info for working process. + * Создание расширенной информации для рабочего процесса. * * @param server - server * @param clusterId - cluster ID * @param workingProcess - working process - * @param columnsMap - columns map */ public WorkingProcessInfoExtended( - Server server, - UUID clusterId, - IWorkingProcessInfo workingProcess, - Map columnsMap) { + Server server, UUID clusterId, IWorkingProcessInfo workingProcess) { this.server = server; this.clusterId = clusterId; - this.workingProcess = workingProcess; - this.columnsMap = columnsMap; - } + this.workingProcessInfo = workingProcess; + this.currentIcon = defaultIcon; - /** - * Init columns name. - * - * @param columnsMap - sample map with columns name - */ - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_USING, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_ENABLES, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_ACTIVE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_PID, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MEMORY, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MEMORY_EXCEEDED, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_AVAILABLE_PERFORMANCE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LICENSE, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_STARTED_AT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONNECTIONS_COUNT, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_BACK_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SERVER_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DB_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_LOCK_CALL_TIME, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CLIENT_THREADS, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initWorkingProcessesColumnCount(columnsMap.size()); + computeExtendedInfoData(); } - @Override - public String[] getExtendedInfo() { - - Map wp = new LinkedHashMap<>(); - wp.putAll(columnsMap); + protected void computeExtendedInfoData() { // license - var license = - workingProcess.getLicense().isEmpty() + final var license = + workingProcessInfo.getLicense().isEmpty() ? "" //$NON-NLS-1$ - : workingProcess.getLicense().get(0).getFullPresentation(); - - wp.put(TITLE_COMPUTER, workingProcess.getHostName()); - wp.put(TITLE_PORT, Integer.toString(workingProcess.getMainPort())); - wp.put(TITLE_USING, isUse()); - wp.put(TITLE_ENABLES, Boolean.toString(workingProcess.isEnable())); - wp.put(TITLE_ACTIVE, isRunning()); - wp.put(TITLE_PID, workingProcess.getPid()); - wp.put(TITLE_MEMORY, longToStringGroup(workingProcess.getMemorySize())); - wp.put(TITLE_MEMORY_EXCEEDED, Long.toString(workingProcess.getMemoryExcessTime())); - wp.put(TITLE_AVAILABLE_PERFORMANCE, Integer.toString(workingProcess.getAvailablePerfomance())); - wp.put(TITLE_LICENSE, license); - wp.put(TITLE_STARTED_AT, dateToString(workingProcess.getStartedAt())); - wp.put(TITLE_CONNECTIONS_COUNT, Integer.toString(workingProcess.getConnections())); - - wp.put(TITLE_BACK_CALL_TIME, double6ToString(workingProcess.getAvgBackCallTime())); - wp.put(TITLE_SERVER_CALL_TIME, double6ToString(workingProcess.getAvgServerCallTime())); - wp.put(TITLE_DB_CALL_TIME, double6ToString(workingProcess.getAvgDBCallTime())); - wp.put(TITLE_CALL_TIME, double6ToString(workingProcess.getAvgCallTime())); - wp.put(TITLE_LOCK_CALL_TIME, double6ToString(workingProcess.getAvgLockCallTime())); - wp.put(TITLE_CLIENT_THREADS, double6ToString(workingProcess.getAvgThreads())); - - return wp.values().toArray(new String[0]); + : workingProcessInfo.getLicense().get(0).getFullPresentation(); + + columnProperties.prepareDataMap(data); + + putData(TITLE_COMPUTER, workingProcessInfo.getHostName(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_PORT, workingProcessInfo.getMainPort(), CELL_VALUE_TYPE.INT); + putData(TITLE_USING, isUse(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_ENABLES, workingProcessInfo.isEnable(), CELL_VALUE_TYPE.BOOLEAN); + putData(TITLE_ACTIVE, isRunning(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_PID, workingProcessInfo.getPid(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_MEMORY, workingProcessInfo.getMemorySize(), CELL_VALUE_TYPE.INT_GROUP); + putData(TITLE_MEMORY_EXCEEDED, workingProcessInfo.getMemoryExcessTime(), CELL_VALUE_TYPE.LONG_GROUP); + putData( + TITLE_AVAILABLE_PERFORMANCE, + workingProcessInfo.getAvailablePerfomance(), + CELL_VALUE_TYPE.INT_GROUP); + putData(TITLE_LICENSE, license, CELL_VALUE_TYPE.TEXT); + putData(TITLE_STARTED_AT, workingProcessInfo.getStartedAt(), CELL_VALUE_TYPE.DATE); + putData(TITLE_CONNECTIONS_COUNT, workingProcessInfo.getConnections(), CELL_VALUE_TYPE.INT_GROUP); + + putData( + TITLE_BACK_CALL_TIME, workingProcessInfo.getAvgBackCallTime(), CELL_VALUE_TYPE.DECIMAL_6_CHAR); + putData( + TITLE_SERVER_CALL_TIME, + workingProcessInfo.getAvgServerCallTime(), + CELL_VALUE_TYPE.DECIMAL_6_CHAR); + putData(TITLE_DB_CALL_TIME, workingProcessInfo.getAvgDBCallTime(), CELL_VALUE_TYPE.DECIMAL_6_CHAR); + putData(TITLE_CALL_TIME, workingProcessInfo.getAvgCallTime(), CELL_VALUE_TYPE.DECIMAL_6_CHAR); + putData( + TITLE_LOCK_CALL_TIME, workingProcessInfo.getAvgLockCallTime(), CELL_VALUE_TYPE.DECIMAL_6_CHAR); + putData(TITLE_CLIENT_THREADS, workingProcessInfo.getAvgThreads(), CELL_VALUE_TYPE.DECIMAL_6_CHAR); + } + + @Override + public void addToTable(Table table, int index) { + createTableItem(table, index, workingProcessInfo.getStartedAt()); } private String isUse() { String isUse; - switch (workingProcess.getUse()) { - case 0: - isUse = Messages.getString("WPInfo.NotUsed"); //$NON-NLS-1$ - break; + switch (workingProcessInfo.getUse()) { case 1: isUse = Messages.getString("WPInfo.Used"); //$NON-NLS-1$ break; case 2: isUse = Messages.getString("WPInfo.UsedAsReserve"); //$NON-NLS-1$ break; + case 0: default: isUse = Messages.getString("WPInfo.NotUsed"); //$NON-NLS-1$ break; @@ -153,17 +127,84 @@ private String isUse() { private String isRunning() { String isRunning; - switch (workingProcess.getRunning()) { - case 0: - isRunning = Messages.getString("WPInfo.ProcessIsStopped"); //$NON-NLS-1$ - break; + switch (workingProcessInfo.getRunning()) { case 1: isRunning = Messages.getString("WPInfo.ProcessIsRunning"); //$NON-NLS-1$ break; + case 0: default: isRunning = Messages.getString("WPInfo.ProcessIsStopped"); //$NON-NLS-1$ break; } return isRunning; } + + /** + * Get WorkingProcessInfo. + * + * @return the workingProcessInfo + */ + public IWorkingProcessInfo getWorkingProcessInfo() { + return workingProcessInfo; + } + + /** + * Получение строки заголовка узла рабочих процессов. + * + * @param count - количество элементов + * @return строку с текстом заголовка + */ + public static String getNodeTitle(int count) { + return String.format(TAB_TEXT_TEMPLATE, count); + } + + /** Инициализация имен колонок. */ + protected static void initColumnsName() { + + columnProperties.addColumnsInMap( + TITLE_COMPUTER, + TITLE_PORT, + TITLE_USING, + TITLE_ENABLES, + TITLE_ACTIVE, + TITLE_PID, + TITLE_MEMORY, + TITLE_MEMORY_EXCEEDED, + TITLE_AVAILABLE_PERFORMANCE, + TITLE_LICENSE, + TITLE_STARTED_AT, + TITLE_CONNECTIONS_COUNT, + TITLE_BACK_CALL_TIME, + TITLE_SERVER_CALL_TIME, + TITLE_DB_CALL_TIME, + TITLE_CALL_TIME, + TITLE_LOCK_CALL_TIME, + TITLE_CLIENT_THREADS); + + defaultIcon = Helper.getImage(DEFAULT_ICON_FILENAME); + } + + /** + * Обновление заголовка вкладки. + * + * @param count - количество элементов + */ + protected static void updateTabText(int count) { + itemCount = count; + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount)); + } + + /** Сброс заголовка вкладки на неизвестное количество элементов. */ + protected static void resetTabTextCount() { + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount + "*")); + } + + /** + * Установка связи с вкладкой TabItem. + * + * @param tabitem вкладка Tabitem + */ + protected static void linkTabItem(TabItem tabitem) { + currentTab = tabitem; + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java index 52b5bb3..3fbc146 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/WorkingServerInfoExtended.java @@ -2,140 +2,184 @@ import com._1c.v8.ibis.admin.IPortRangeInfo; import com._1c.v8.ibis.admin.IWorkingServerInfo; -import java.util.LinkedHashMap; -import java.util.Map; import java.util.UUID; - -/** Extend info for working server. */ -public class WorkingServerInfoExtended implements IInfoExtended { - - private static final String TITLE_DESCRIPTION = - Messages.getString("InfoTables.Description"); //$NON-NLS-1$ - private static final String TITLE_COMPUTER = - Messages.getString("SessionInfo.Computer"); //$NON-NLS-1$ - private static final String TITLE_IP_PORT = Messages.getString("WSInfo.IPPort"); //$NON-NLS-1$ - private static final String TITLE_RANGE_IP_PORTS = - Messages.getString("WSInfo.RangeIPPorts"); //$NON-NLS-1$ - private static final String TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT = - Messages.getString("WSInfo.SafeWorkingProcessesMemoryLimit"); //$NON-NLS-1$ - private static final String TITLE_SAFE_CALL_MEMORY_LIMIT = - Messages.getString("WSInfo.SafeCallMemoryLimit"); //$NON-NLS-1$ - private static final String TITLE_WORKING_PROCESS_MEMORY_LIMIT = - Messages.getString("WSInfo.WorkingProcessMemoryLimit"); //$NON-NLS-1$ - private static final String TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY = - Messages.getString("WSInfo.CriticalProcessesTotalMemory"); //$NON-NLS-1$ - private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY = - Messages.getString("WSInfo.TemporaryAllowedProcessesTotalMemory"); //$NON-NLS-1$ - private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT = - Messages.getString("WSInfo.TemporaryAllowedProcessesTotalMemoryTimeLimit"); //$NON-NLS-1$ - private static final String TITLE_IB_PER_PROCESS_LIMIT = - Messages.getString("WSInfo.IBPerProcessLimit"); //$NON-NLS-1$ - private static final String TITLE_CONN_PER_PROCESS_LIMIT = - Messages.getString("WSInfo.ConnPerProcessLimit"); //$NON-NLS-1$ - private static final String TITLE_IP_PORT_MAIN_MANAGER = - Messages.getString("WSInfo.IPPortMainManager"); //$NON-NLS-1$ - private static final String TITLE_DEDICATED_MANAGERS = - Messages.getString("WSInfo.DedicatedManagers"); //$NON-NLS-1$ - private static final String TITLE_MAIN_SERVER = - Messages.getString("WSInfo.MainServer"); //$NON-NLS-1$ - - Server server; - UUID clusterId; - IWorkingServerInfo workingServer; - - Map columnsMap = new LinkedHashMap<>(); +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import ru.yanygin.clusterAdminLibrary.CellValue.CELL_VALUE_TYPE; + +/** Расширенная информация для рабочего сервера. */ +public class WorkingServerInfoExtended extends BaseInfoExtended { + + private static final String TITLE_DESCRIPTION = "InfoTables.Description"; //$NON-NLS-1$ + private static final String TITLE_COMPUTER = "SessionInfo.Computer"; //$NON-NLS-1$ + private static final String TITLE_IP_PORT = "WSInfo.IPPort"; //$NON-NLS-1$ + private static final String TITLE_RANGE_IP_PORTS = "WSInfo.RangeIPPorts"; //$NON-NLS-1$ + private static final String TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT = "WSInfo.SafeWorkingProcessesMemoryLimit"; //$NON-NLS-1$ + private static final String TITLE_SAFE_CALL_MEMORY_LIMIT = "WSInfo.SafeCallMemoryLimit"; //$NON-NLS-1$ + private static final String TITLE_WORKING_PROCESS_MEMORY_LIMIT = "WSInfo.WorkingProcessMemoryLimit"; //$NON-NLS-1$ + private static final String TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY = "WSInfo.CriticalProcessesTotalMemory"; //$NON-NLS-1$ + private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY = "WSInfo.TemporaryAllowedProcessesTotalMemory"; //$NON-NLS-1$ + private static final String TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT = "WSInfo.TemporaryAllowedProcessesTotalMemoryTimeLimit"; //$NON-NLS-1$ + private static final String TITLE_IB_PER_PROCESS_LIMIT = "WSInfo.IBPerProcessLimit"; //$NON-NLS-1$ + private static final String TITLE_CONN_PER_PROCESS_LIMIT = "WSInfo.ConnPerProcessLimit"; //$NON-NLS-1$ + private static final String TITLE_IP_PORT_MAIN_MANAGER = "WSInfo.IPPortMainManager"; //$NON-NLS-1$ + private static final String TITLE_DEDICATED_MANAGERS = "WSInfo.DedicatedManagers"; //$NON-NLS-1$ + private static final String TITLE_MAIN_SERVER = "WSInfo.MainServer"; //$NON-NLS-1$ + + private static Config commonConfig = Config.currentConfig; + private static ColumnProperties columnProperties = + commonConfig.getColumnsProperties(WorkingServerInfoExtended.class); + + private static final String DEFAULT_ICON_FILENAME = "working_server_24.png"; + private static Image defaultIcon; + + private static final String TAB_TEXT_TEMPLATE = + Messages.getString("TabText.WorkingServersCount"); //$NON-NLS-1$ + + private static TabItem currentTab; + private static int itemCount; + + IWorkingServerInfo workingServerInfo; /** - * Create extended info for working server. + * Создание расширенной информации для рабочего сервера. * * @param server - server * @param clusterId - cluster ID * @param workingServer - working server info - * @param columnsMap - columns map */ public WorkingServerInfoExtended( - Server server, - UUID clusterId, - IWorkingServerInfo workingServer, - Map columnsMap) { + Server server, UUID clusterId, IWorkingServerInfo workingServer) { this.server = server; this.clusterId = clusterId; - this.workingServer = workingServer; - this.columnsMap = columnsMap; - } + this.workingServerInfo = workingServer; + this.currentIcon = defaultIcon; - /** - * Init columns name. - * - * @param columnsMap - sample map with columns name - */ - public static void initColumnsName(Map columnsMap) { - - columnsMap.put(TITLE_DESCRIPTION, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_COMPUTER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_IP_PORT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_RANGE_IP_PORTS, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_SAFE_CALL_MEMORY_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_WORKING_PROCESS_MEMORY_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, ""); //$NON-NLS-1$ - - columnsMap.put(TITLE_IB_PER_PROCESS_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_CONN_PER_PROCESS_LIMIT, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_IP_PORT_MAIN_MANAGER, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_DEDICATED_MANAGERS, ""); //$NON-NLS-1$ - columnsMap.put(TITLE_MAIN_SERVER, ""); //$NON-NLS-1$ - - ClusterProvider.getCommonConfig().initWorkingServersColumnCount(columnsMap.size()); + computeExtendedInfoData(); } - @Override - public String[] getExtendedInfo() { + protected void computeExtendedInfoData() { - Map ws = new LinkedHashMap<>(); - ws.putAll(columnsMap); + columnProperties.prepareDataMap(data); - ws.put(TITLE_DESCRIPTION, workingServer.getName()); - ws.put(TITLE_COMPUTER, workingServer.getHostName()); - ws.put(TITLE_IP_PORT, Integer.toString(workingServer.getMainPort())); - ws.put(TITLE_RANGE_IP_PORTS, getPortRange()); - ws.put( + putData(TITLE_DESCRIPTION, workingServerInfo.getName(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_COMPUTER, workingServerInfo.getHostName(), CELL_VALUE_TYPE.TEXT); + putData(TITLE_IP_PORT, workingServerInfo.getMainPort(), CELL_VALUE_TYPE.INT); + putData(TITLE_RANGE_IP_PORTS, getPortRange(), CELL_VALUE_TYPE.TEXT); + putData( TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, - longToStringGroup(workingServer.getSafeWorkingProcessesMemoryLimit())); - ws.put(TITLE_SAFE_CALL_MEMORY_LIMIT, longToStringGroup(workingServer.getSafeCallMemoryLimit())); - ws.put( + workingServerInfo.getSafeWorkingProcessesMemoryLimit(), + CELL_VALUE_TYPE.LONG_GROUP); + putData( + TITLE_SAFE_CALL_MEMORY_LIMIT, + workingServerInfo.getSafeCallMemoryLimit(), + CELL_VALUE_TYPE.LONG_GROUP); + putData( TITLE_WORKING_PROCESS_MEMORY_LIMIT, - longToStringGroup(workingServer.getWorkingProcessMemoryLimit())); - ws.put( + workingServerInfo.getWorkingProcessMemoryLimit(), + CELL_VALUE_TYPE.LONG_GROUP); + putData( TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, - longToStringGroup(workingServer.getCriticalProcessesTotalMemory())); - ws.put( + workingServerInfo.getCriticalProcessesTotalMemory(), + CELL_VALUE_TYPE.LONG_GROUP); + putData( TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, - longToStringGroup(workingServer.getTemporaryAllowedProcessesTotalMemory())); - ws.put( + workingServerInfo.getTemporaryAllowedProcessesTotalMemory(), + CELL_VALUE_TYPE.LONG_GROUP); + putData( TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, - longToStringGroup(workingServer.getTemporaryAllowedProcessesTotalMemoryTimeLimit())); - ws.put( + workingServerInfo.getTemporaryAllowedProcessesTotalMemoryTimeLimit(), + CELL_VALUE_TYPE.LONG_GROUP); + putData( TITLE_IB_PER_PROCESS_LIMIT, - Integer.toString(workingServer.getInfoBasesPerWorkingProcessLimit())); - ws.put( + workingServerInfo.getInfoBasesPerWorkingProcessLimit(), + CELL_VALUE_TYPE.INT); + putData( TITLE_CONN_PER_PROCESS_LIMIT, - Integer.toString(workingServer.getConnectionsPerWorkingProcessLimit())); - ws.put(TITLE_IP_PORT_MAIN_MANAGER, Integer.toString(workingServer.getClusterMainPort())); - ws.put(TITLE_DEDICATED_MANAGERS, Boolean.toString(workingServer.isDedicatedManagers())); - ws.put(TITLE_MAIN_SERVER, Boolean.toString(workingServer.isMainServer())); + workingServerInfo.getConnectionsPerWorkingProcessLimit(), + CELL_VALUE_TYPE.INT); + putData(TITLE_IP_PORT_MAIN_MANAGER, workingServerInfo.getClusterMainPort(), CELL_VALUE_TYPE.INT); + putData(TITLE_DEDICATED_MANAGERS, workingServerInfo.isDedicatedManagers(), CELL_VALUE_TYPE.BOOLEAN); + putData(TITLE_MAIN_SERVER, workingServerInfo.isMainServer(), CELL_VALUE_TYPE.BOOLEAN); + } - return ws.values().toArray(new String[0]); + @Override + public void addToTable(Table table, int index) { + createTableItem(table, index, null); } private String getPortRange() { - IPortRangeInfo portRangesInfo = workingServer.getPortRanges().get(0); + IPortRangeInfo portRangesInfo = workingServerInfo.getPortRanges().get(0); return Integer.toString(portRangesInfo.getLowBound()) .concat(":") //$NON-NLS-1$ .concat(Integer.toString(portRangesInfo.getHighBound())); } + + /** + * Получение строки заголовка узла рабочих серверов. + * + * @param count - количество элементов + * @return строку с текстом заголовка + */ + public static String getNodeTitle(int count) { + return String.format(TAB_TEXT_TEMPLATE, count); + } + + /** + * Получение UUID рабочего сервера. + * + * @return UUID рабочего сервера + */ + public UUID getWorkingServerId() { + return workingServerInfo.getWorkingServerId(); + } + + /** Инициализация имен колонок. */ + protected static void initColumnsName() { + + columnProperties.addColumnsInMap( + TITLE_DESCRIPTION, + TITLE_COMPUTER, + TITLE_IP_PORT, + TITLE_RANGE_IP_PORTS, + TITLE_SAFE_WORKING_PROCESSES_MEMORY_LIMIT, + TITLE_SAFE_CALL_MEMORY_LIMIT, + TITLE_WORKING_PROCESS_MEMORY_LIMIT, + TITLE_CRITICAL_PROCESSES_TOTAL_MEMORY, + TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY, + TITLE_TEMP_ALLOWED_PROC_TOTAL_MEMORY_TIME_LIMIT, + TITLE_IB_PER_PROCESS_LIMIT, + TITLE_CONN_PER_PROCESS_LIMIT, + TITLE_IP_PORT_MAIN_MANAGER, + TITLE_DEDICATED_MANAGERS, + TITLE_MAIN_SERVER); + + defaultIcon = Helper.getImage(DEFAULT_ICON_FILENAME); + } + + /** + * Обновление заголовка вкладки. + * + * @param count - количество элементов + */ + protected static void updateTabText(int count) { + itemCount = count; + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount)); + } + + /** Сброс заголовка вкладки на неизвестное количество элементов. */ + protected static void resetTabTextCount() { + currentTab.setText(String.format(TAB_TEXT_TEMPLATE, itemCount + "*")); + } + + /** + * Установка связи с вкладкой TabItem. + * + * @param tabitem вкладка Tabitem + */ + protected static void linkTabItem(TabItem tabitem) { + currentTab = tabitem; + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages.properties b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages.properties index 5cfc0a5..7a59c68 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages.properties +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages.properties @@ -17,6 +17,7 @@ Server.AdministrationServer = Administration Server Server.AuthenticationOfCentralServerAdministrator = Authentication of the Central server administrator <%s:%s> Server.AuthenticationOfClusterAdminnistrator = Authentication of the cluster administrator on the <%s/%s> Server.AuthenticationOfInfobase = Authentication of the infobase +Server.BackgroundJob = Background job Server.ClusterConsole = Cluster Console Server.Designer = Designer Server.JobScheduler = Job scheduler @@ -31,6 +32,7 @@ Server.ThinClient = Thin client Server.UnknownAgentVersion = Unknown Server.UnknownClient = Unknown client (%s) Server.UnresolvedAddress = Unresolved server address +Server.WebClient = Web client SessionInfo.Application = Application SessionInfo.BlockedByDbms = Blocked by Dbms @@ -78,11 +80,18 @@ SessionInfo.Server = Server SessionInfo.SessionN = Session N SessionInfo.SleepAfter = Sleep after SessionInfo.StartedAt = Started At +SessionInfo.TitleDialog = Session info SessionInfo.Username = Username SessionInfo.WriteBytesCurrent = Write (current) SessionInfo.WriteBytesLast5Min = Write (last 5 min) SessionInfo.WriteBytesTotal = Write (total) +TabText.ConnectionsCount = Connections (%s) +TabText.LocksCount = Locks (%s) +TabText.SessionsCount = Sessions (%s) +TabText.WorkingProcessesCount = Working processes (%s) +TabText.WorkingServersCount = Working servers (%s) + WPInfo.Active = Active WPInfo.AvailablePerformance = Available performance WPInfo.BackCallTime = Back call time diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages_ru_RU.properties b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages_ru_RU.properties index eb23b58..4da4f24 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages_ru_RU.properties +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/messages_ru_RU.properties @@ -15,6 +15,7 @@ Server.AdministrationServer = \u0421\u0435\u0440\u0432\u04 Server.AuthenticationOfCentralServerAdministrator = \u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0430\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0430\u0442\u043E\u0440\u0430 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 <%s:%s> Server.AuthenticationOfClusterAdminnistrator = \u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0430\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0430\u0442\u043E\u0440\u0430 \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 \u043D\u0430 <%s/%s> Server.AuthenticationOfInfobase = \u0410\u0443\u0442\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0446\u0438\u044F \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B +Server.BackgroundJob = \u0424\u043E\u043D\u043E\u0432\u043E\u0435 \u0437\u0430\u0434\u0430\u043D\u0438\u0435 Server.ClusterConsole = \u041A\u043E\u043D\u0441\u043E\u043B\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 Server.Designer = \u041A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0442\u043E\u0440 Server.JobScheduler = \u041F\u043B\u0430\u043D\u0438\u0440\u043E\u0432\u0449\u0438\u043A \u0437\u0430\u0434\u0430\u043D\u0438\u0439 @@ -27,8 +28,9 @@ Server.TheConnectionAClusterIsNotEstablished = \u0421\u043E\u0435\u0434\u04 Server.ThickClient = \u0422\u043E\u043B\u0441\u0442\u044B\u0439 \u043A\u043B\u0438\u0435\u043D\u0442 Server.ThinClient = \u0422\u043E\u043D\u043A\u0438\u0439 \u043A\u043B\u0438\u0435\u043D\u0442 Server.UnknownAgentVersion = \u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u043E -Server.UnknownClient = \u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u043A\u043B\u0438\u0435\u043D\u0442 +Server.UnknownClient = \u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u043A\u043B\u0438\u0435\u043D\u0442 (%s) Server.UnresolvedAddress = \u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u0430\u0434\u0440\u0435\u0441 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +Server.WebClient = \u0412\u0435\u0431-\u043A\u043B\u0438\u0435\u043D\u0442 SessionInfo.Application = \u041F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u0435 SessionInfo.BlockedByDbms = \u0417\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043E \u0421\u0423\u0411\u0414 @@ -76,11 +78,18 @@ SessionInfo.Server = \u0421\u0435\u0440\u0432\u0435\u0440 SessionInfo.SessionN = N \u0441\u0435\u0430\u043D\u0441\u0430 SessionInfo.SleepAfter = \u0417\u0430\u0441\u043D\u0443\u0442\u044C \u0447\u0435\u0440\u0435\u0437 SessionInfo.StartedAt = \u0412\u0440\u0435\u043C\u044F \u0437\u0430\u043F\u0443\u0441\u043A\u0430 +SessionInfo.TitleDialog = \u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u0441\u0435\u0430\u043D\u0441\u0435 SessionInfo.Username = \u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F SessionInfo.WriteBytesCurrent = \u0417\u0430\u043F\u0438\u0441\u044C (\u0442\u0435\u043A\u0443\u0449\u0430\u044F) SessionInfo.WriteBytesLast5Min = \u0417\u0430\u043F\u0438\u0441\u044C (5 \u043C\u0438\u043D) SessionInfo.WriteBytesTotal = \u0417\u0430\u043F\u0438\u0441\u044C (\u0432\u0441\u0435\u0433\u043E) +TabText.ConnectionsCount = \u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F (%s) +TabText.LocksCount = \u0411\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438 (%s) +TabText.SessionsCount = \u0421\u0435\u0430\u043D\u0441\u044B (%s) +TabText.WorkingProcessesCount = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B (%s) +TabText.WorkingServersCount = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u044B (%s) + WPInfo.Active = \u0410\u043A\u0442\u0438\u0432\u0435\u043D WPInfo.AvailablePerformance = \u0414\u043E\u0441\u0442\u0443\u043F\u043D\u0430\u044F \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C WPInfo.BackCallTime = \u0420\u0435\u0430\u043A\u0446\u0438\u044F \u0441\u0435\u0440\u0432\u0435\u0440\u0430 diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java index a1a7350..ab0af08 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AboutDialog.java @@ -1,5 +1,6 @@ package ru.yanygin.clusterAdminLibraryUI; +import java.lang.module.ModuleDescriptor.Version; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -15,10 +16,21 @@ import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Shell; import org.eclipse.wb.swt.SWTResourceManager; +import ru.yanygin.clusterAdminLibrary.Config; -/** About dialog. */ +/** Диалог "О программе". */ public class AboutDialog extends Dialog { + private static final String SEGOE_FONT = "Segoe UI"; //$NON-NLS-1$ + private static final String GITHUB_LINK = + "https://github.com/YanSergey/OneS_ClusterAdmin"; //$NON-NLS-1$ + private static final String TELEGRAM_LINK = "https://t.me/YanSergey"; //$NON-NLS-1$ + private static final String EMAIL_LINK = "mailto:yanyginsa@gmail.com"; //$NON-NLS-1$ + + Config config = Config.currentConfig; + + private Link linkLatestVersion; + /** * Create the dialog. * @@ -29,6 +41,12 @@ public AboutDialog(Shell parentShell) { setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); } + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + /** * Create contents of the dialog. * @@ -41,51 +59,56 @@ protected Control createDialogArea(Composite parent) { Label lblMainTitle = new Label(container, SWT.NONE); lblMainTitle.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1)); - lblMainTitle.setFont(SWTResourceManager.getFont("Segoe UI", 20, SWT.BOLD)); //$NON-NLS-1$ - lblMainTitle.setText(Messages.getString("AboutDialog.MainTitle")); + lblMainTitle.setFont(SWTResourceManager.getFont(SEGOE_FONT, 20, SWT.BOLD)); + lblMainTitle.setText(Strings.MAIN_TITLE); Label lblDescription = new Label(container, SWT.NONE); lblDescription.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); - lblDescription.setText(Messages.getString("AboutDialog.Description")); //$NON-NLS-1$ - lblDescription.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL)); + lblDescription.setText(Strings.DESCRIPTION); + lblDescription.setFont(SWTResourceManager.getFont(SEGOE_FONT, 10, SWT.NORMAL)); + + Link linkCurrentVersion = new Link(container, 0); + linkCurrentVersion.setFont(SWTResourceManager.getFont(SEGOE_FONT, 10, SWT.NORMAL)); + linkCurrentVersion.setText(String.format(Strings.CURRENT_VERSION, config.getCurrentVersion())); + + linkLatestVersion = new Link(container, 0); + linkLatestVersion.setText(Strings.CURRENT_VERSION_IS_UNKNOWN); + linkLatestVersion.addSelectionListener(downloadLatestVersionListener); + makeLatestVersionTitle(); Label lblAutor = new Label(container, SWT.NONE); - lblAutor.setText(Messages.getString("AboutDialog.Autor")); - lblAutor.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.NORMAL)); + lblAutor.setText(Strings.AUTOR); Link linkGitHub = new Link(container, SWT.NONE); - linkGitHub.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Program.launch("https://github.com/YanSergey/OneS_ClusterAdmin"); - } - }); - linkGitHub.setText(Messages.getString("AboutDialog.GitHub")); + linkGitHub.setText(Strings.GITHUB_DESCRIPTION); + linkGitHub.addSelectionListener(goToLinkListener); Link linkTelegram = new Link(container, 0); - linkTelegram.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Program.launch("https://t.me/YanSergey"); - } - }); - linkTelegram.setText(Messages.getString("AboutDialog.Telegram")); + linkTelegram.setText(Strings.TELEGRAM_DESCRIPTION); + linkTelegram.addSelectionListener(goToLinkListener); Link linkEmail = new Link(container, 0); - linkEmail.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - Program.launch("mailto:yanyginsa@gmail.com"); - } - }); - linkEmail.setText(Messages.getString("AboutDialog.Email")); + linkEmail.setText(Strings.EMAIL_DESCRIPTION); + linkEmail.addSelectionListener(goToLinkListener); return container; } + private void makeLatestVersionTitle() { + + final Version currentVersion = config.getCurrentVersion(); + final Version latestVersion = config.getLatestVersion(); + + if (latestVersion == null) { + linkLatestVersion.setText(Strings.CURRENT_VERSION_IS_UNKNOWN); + } else if (currentVersion.equals(latestVersion) + || currentVersion.compareTo(latestVersion) > 0) { + linkLatestVersion.setText(Strings.CURRENT_VERSION_IS_LATEST); + } else { + linkLatestVersion.setText(String.format(Strings.CURRENT_VERSION_IS_OLD, latestVersion)); + } + } + /** * Create contents of the button bar. * @@ -104,8 +127,53 @@ public void widgetSelected(SelectionEvent e) { }); } + SelectionAdapter downloadLatestVersionListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (config.getLatestVersion() == null) { + config.readUpstreamVersion(); + makeLatestVersionTitle(); + } else { + config.runDownloadRelease(getParentShell()); + } + } + }; + + SelectionAdapter goToLinkListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + Program.launch(e.text); + } + }; + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + static final String MAIN_TITLE = getString("MainTitle"); + + static final String CURRENT_VERSION = getString("CurrentVersion"); + static final String CURRENT_VERSION_IS_LATEST = getString("CurrentVersionIsLatest"); + static final String CURRENT_VERSION_IS_OLD = getString("CurrentVersionIsOld"); + static final String CURRENT_VERSION_IS_UNKNOWN = getString("CurrentVersionIsUnknown"); + + static final String DESCRIPTION = getString("Description"); + static final String AUTOR = getString("Autor"); + static final String GITHUB_DESCRIPTION = + String.format(getString("GitHub_Description"), GITHUB_LINK); + static final String TELEGRAM_DESCRIPTION = + String.format(getString("Telegram_Description"), TELEGRAM_LINK); + static final String EMAIL_DESCRIPTION = + String.format(getString("Email_Description"), EMAIL_LINK); + + static String getString(String key) { + return Messages.getString("AboutDialog." + key); //$NON-NLS-1$ + } + } + @Override protected Point getInitialSize() { - return new Point(500, 330); + return new Point(500, 380); } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java index 831f280..a42dad7 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/AuthenticateDialog.java @@ -1,59 +1,81 @@ package ru.yanygin.clusterAdminLibraryUI; +import java.util.ArrayList; +import java.util.List; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; +import ru.yanygin.clusterAdminLibrary.UserPassPair; -/** Authenticate dialog. */ +/** Диалог для ввода логина и пароля. */ public class AuthenticateDialog extends Dialog { - private Text txtUsername; - private Text txtPassword; - - private String username; - private String password; + private UserPassPair currentUserPass; + private List credentials = new ArrayList<>(); private String authExcpMessage; - private String authDescription; + private String authTitle; - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } + private Combo txtUsername; + private Text txtPassword; /** - * Create the dialog. + * Создание диалога ввода имени пользователя и пароля. * * @param parentShell - parent shell - * @param username - username - * @param authDescription - authenticate description - * @param authExcpMessage - authenticate exception message + * @param currentUserPass - текущие имя пользователя и пароль + * @param authTitle - заголовок окна аутентификации + * @param authExcpMessage - ошибка аутентификации для вывода пользователю + * @wbp.parser.constructor */ public AuthenticateDialog( - Shell parentShell, String username, String authDescription, String authExcpMessage) { + Shell parentShell, UserPassPair currentUserPass, String authTitle, String authExcpMessage) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.username = username; - this.authDescription = authDescription; + this.currentUserPass = currentUserPass; + this.authTitle = authTitle; this.authExcpMessage = authExcpMessage; } + /** + * Создание диалога ввода имени пользователя и пароля с возможностью выбора пользователя. + * + * @param parentShell - parent shell + * @param userPass - имя пользователя и пароль + * @param authTitle - заголовок окна аутентификации + * @param authExcpMessage - ошибка аутентификации для вывода пользователю + * @param credentials - список сохраненных логин/паролей + */ + public AuthenticateDialog( + Shell parentShell, + UserPassPair userPass, + String authTitle, + String authExcpMessage, + List credentials) { + + this(parentShell, userPass, authTitle, authExcpMessage); + this.credentials = credentials; + } + + @Override + protected void configureShell(Shell newShell) { + newShell.setMinimumSize(new Point(300, 39)); + super.configureShell(newShell); + newShell.setText(authTitle); + } + /** * Create contents of the dialog. * @@ -68,20 +90,34 @@ protected Control createDialogArea(Composite parent) { Label lblAuthenticateInfo = new Label(container, SWT.WRAP); lblAuthenticateInfo.setLayoutData(new GridData(SWT.LEFT, SWT.FILL, true, true, 2, 1)); - lblAuthenticateInfo.setText(authDescription); + lblAuthenticateInfo.setText(authTitle); Label lblUsername = new Label(container, SWT.NONE); - lblUsername.setText(Messages.getString("Dialogs.Username")); //$NON-NLS-1$ + lblUsername.setText(Strings.USERNAME); - txtUsername = new Text(container, SWT.BORDER); - txtUsername.setToolTipText(Messages.getString("Dialogs.Username")); //$NON-NLS-1$ + txtUsername = new Combo(container, SWT.NONE); + txtUsername.setToolTipText(Strings.USERNAME); txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + txtUsername.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + String pass = (String) txtUsername.getData(txtUsername.getText()); + txtPassword.setText(pass); + } + }); + + credentials.forEach( + userpass -> { + txtUsername.add(userpass.getUsername()); + txtUsername.setData(userpass.getUsername(), userpass.getPassword()); + }); Label lblPassword = new Label(container, SWT.NONE); - lblPassword.setText(Messages.getString("Dialogs.Password")); //$NON-NLS-1$ + lblPassword.setText(Strings.PASSWORD); txtPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); - txtPassword.setToolTipText(Messages.getString("Dialogs.Password")); //$NON-NLS-1$ + txtPassword.setToolTipText(Strings.PASSWORD); txtPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblAuthExcpMessage = new Label(container, SWT.WRAP); @@ -93,14 +129,25 @@ protected Control createDialogArea(Composite parent) { return container; } + /** + * Получает введенный пользователем логин. + * + * @return логин + */ + public UserPassPair getUserPass() { + return currentUserPass; + } + private void initProperties() { - this.txtUsername.setText(username); + this.txtUsername.setText(currentUserPass.getUsername()); + this.txtPassword.setText(currentUserPass.getPassword()); } private void extractVariablesFromControls() { - username = txtUsername.getText(); - password = txtPassword.getText(); + currentUserPass = + new UserPassPair( + txtUsername.getText(), txtPassword.getText(), currentUserPass.getDescription()); } /** @@ -123,4 +170,15 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } + + private static class Strings { + + // static final String TITLE_WINDOW = getString("ServerParameters"); + static final String USERNAME = getString("Username"); //$NON-NLS-1$ + static final String PASSWORD = getString("Password"); //$NON-NLS-1$ + + static String getString(String key) { + return Messages.getString("Dialogs." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ClusterDialog.java similarity index 71% rename from clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java rename to clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ClusterDialog.java index 64b6f7d..45551ed 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditClusterDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ClusterDialog.java @@ -23,27 +23,32 @@ import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import org.eclipse.wb.swt.SWTResourceManager; +import ru.yanygin.clusterAdminLibrary.Helper; import ru.yanygin.clusterAdminLibrary.Server; -/** Dialog for сreate and edit cluster. */ -public class CreateEditClusterDialog extends Dialog { +/** Диалог редактирования параметров кластера. */ +public class ClusterDialog extends Dialog { + + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ - private UUID clusterId; private Server server; + private UUID clusterId; - private Button btnClusterRecyclingKillProblemProcesses; + // Controls private Text txtClusterName; private Text txtComputerName; private Text txtIpPort; - private Combo comboSecurityLevel; private Text txtLifeTimeLimit; private Text txtMaxMemorySize; private Text txtMaxMemoryTimeLimit; private Text txtClusterRecyclingErrorsCountThreshold; private Text txtExpirationTimeout; private Text txtSessionFaultToleranceLevel; + + private Combo comboSecurityLevel; private Combo comboLoadBalancingMode; + + private Button btnClusterRecyclingKillProblemProcesses; private Button btnClusterRecyclingKillByMemoryWithDump; /** @@ -53,17 +58,20 @@ public class CreateEditClusterDialog extends Dialog { * @param server - server * @param clusterId - cluster ID */ - public CreateEditClusterDialog(Shell parentShell, Server server, UUID clusterId) { + public ClusterDialog(Shell parentShell, Server server, UUID clusterId) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - this.server = server; this.clusterId = clusterId; } + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + /** * Create contents of the dialog. * @@ -80,57 +88,52 @@ protected Control createDialogArea(Composite parent) { Label lblClusterName = new Label(container, SWT.NONE); lblClusterName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblClusterName.setText(Messages.getString("ClusterDialog.ClusterName")); //$NON-NLS-1$ + lblClusterName.setText(Strings.CLUSTER_NAME); txtClusterName = new Text(container, SWT.BORDER); - txtClusterName.setToolTipText(Messages.getString("ClusterDialog.ClusterName")); GridData gdtxtClusterName = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdtxtClusterName.widthHint = 200; txtClusterName.setLayoutData(gdtxtClusterName); Label lblComputerName = new Label(container, SWT.NONE); lblComputerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblComputerName.setText(Messages.getString("ClusterDialog.ComputerName")); //$NON-NLS-1$ + lblComputerName.setText(Strings.COMPUTER_NAME); txtComputerName = new Text(container, SWT.BORDER); - txtComputerName.setToolTipText(Messages.getString("ClusterDialog.ComputerName")); GridData gdtxtComputerName = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdtxtComputerName.widthHint = 200; txtComputerName.setLayoutData(gdtxtComputerName); Label lblIpPort = new Label(container, SWT.NONE); lblIpPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblIpPort.setText(Messages.getString("ClusterDialog.IPPort")); //$NON-NLS-1$ + lblIpPort.setText(Strings.IP_PORT); txtIpPort = new Text(container, SWT.BORDER); - txtIpPort.setToolTipText(Messages.getString("ClusterDialog.IPPort")); GridData gdtxtIpPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdtxtIpPort.widthHint = 200; txtIpPort.setLayoutData(gdtxtIpPort); Label lblSecurityLevel = new Label(container, SWT.NONE); lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + lblSecurityLevel.setText(Strings.SECURITY_LEVEL); comboSecurityLevel = new Combo(container, SWT.READ_ONLY); comboSecurityLevel.setVisibleItemCount(3); comboSecurityLevel.setTouchEnabled(true); - comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); GridData gdcomboSecurityLevel = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdcomboSecurityLevel.widthHint = 200; comboSecurityLevel.setLayoutData(gdcomboSecurityLevel); - comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ + comboSecurityLevel.add(Strings.SECURITY_LEVEL_DISABLE); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_DISABLE, 0); + comboSecurityLevel.add(Strings.SECURITY_LEVEL_CONNECTIONONLY); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_CONNECTIONONLY, 1); + comboSecurityLevel.add(Strings.SECURITY_LEVEL_CONSTANTLY); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_CONSTANTLY, 2); comboSecurityLevel.select(0); Group groupWorkProcessesParams = new Group(container, SWT.NONE); - groupWorkProcessesParams.setText( - Messages.getString("ClusterDialog.RestartWorkProcesses")); //$NON-NLS-1$ + groupWorkProcessesParams.setText(Strings.WP_RESTART); GridLayout glgroupWorkProcessesParams = new GridLayout(2, true); glgroupWorkProcessesParams.verticalSpacing = 8; groupWorkProcessesParams.setLayout(glgroupWorkProcessesParams); @@ -138,47 +141,37 @@ protected Control createDialogArea(Composite parent) { Label lblLifeTimeLimit = new Label(groupWorkProcessesParams, SWT.NONE); lblLifeTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLifeTimeLimit.setText(Messages.getString("ClusterDialog.RestartInterval")); //$NON-NLS-1$ + lblLifeTimeLimit.setText(Strings.WP_RESTART_INTERVAL); txtLifeTimeLimit = new Text(groupWorkProcessesParams, SWT.BORDER); GridData gdtxtLifeTimeLimit = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gdtxtLifeTimeLimit.widthHint = 200; txtLifeTimeLimit.setLayoutData(gdtxtLifeTimeLimit); - txtLifeTimeLimit.setToolTipText( - Messages.getString("ClusterDialog.RestartInterval")); //$NON-NLS-1$ Label lblMaxMemorySize = new Label(groupWorkProcessesParams, SWT.NONE); lblMaxMemorySize.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblMaxMemorySize.setText( - Messages.getString("ClusterDialog.AllowedAmountOfMemoryWithLineBreak")); //$NON-NLS-1$ + lblMaxMemorySize.setText(Strings.WP_ALLOWED_AMOUNT_OFMEMORY); txtMaxMemorySize = new Text(groupWorkProcessesParams, SWT.BORDER); GridData gdtxtMaxMemorySize = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gdtxtMaxMemorySize.widthHint = 200; txtMaxMemorySize.setLayoutData(gdtxtMaxMemorySize); - txtMaxMemorySize.setToolTipText( - Messages.getString("ClusterDialog.AllowedAmountOfMemory")); //$NON-NLS-1$ Label lblMaxMemoryTimeLimit = new Label(groupWorkProcessesParams, SWT.WRAP); lblMaxMemoryTimeLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, true, 1, 1)); - lblMaxMemoryTimeLimit.setText( - Messages.getString( - "ClusterDialog.IntervalExceedingAllowedAmountOfMemoryWithLineBreak")); //$NON-NLS-1$ + lblMaxMemoryTimeLimit.setText(Strings.WP_INTERVAL_EXCEEDING_ALLOWED_AMOUNT_OFMEMORY); txtMaxMemoryTimeLimit = new Text(groupWorkProcessesParams, SWT.BORDER); GridData gdtxtMaxMemoryTimeLimit = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gdtxtMaxMemoryTimeLimit.widthHint = 200; txtMaxMemoryTimeLimit.setLayoutData(gdtxtMaxMemoryTimeLimit); - txtMaxMemoryTimeLimit.setToolTipText( - Messages.getString("ClusterDialog.IntervalExceedingAllowedAmountOfMemory")); //$NON-NLS-1$ Label lblAcceptableDeviationOfNumberOfServerErrors = new Label(groupWorkProcessesParams, SWT.WRAP); lblAcceptableDeviationOfNumberOfServerErrors.setLayoutData( new GridData(SWT.RIGHT, SWT.FILL, false, true, 1, 1)); lblAcceptableDeviationOfNumberOfServerErrors.setText( - Messages.getString( - "ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrorsWithLineBreak")); //$NON-NLS-1$ + Strings.ACCEPTABLE_DEVIATION_OFTHENUMBER_OFSERVER_ERRORS); txtClusterRecyclingErrorsCountThreshold = new Text(groupWorkProcessesParams, SWT.BORDER); GridData gdtxtClusterRecyclingErrorsCountThreshold = @@ -186,30 +179,23 @@ protected Control createDialogArea(Composite parent) { gdtxtClusterRecyclingErrorsCountThreshold.widthHint = 200; txtClusterRecyclingErrorsCountThreshold.setLayoutData( gdtxtClusterRecyclingErrorsCountThreshold); - txtClusterRecyclingErrorsCountThreshold.setToolTipText( - Messages.getString( - "ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors")); //$NON-NLS-1$ btnClusterRecyclingKillProblemProcesses = new Button(groupWorkProcessesParams, SWT.CHECK); btnClusterRecyclingKillProblemProcesses.setLayoutData( new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1)); - btnClusterRecyclingKillProblemProcesses.setText( - Messages.getString("ClusterDialog.ForceShutdownOfProblematicProcesses")); //$NON-NLS-1$ + btnClusterRecyclingKillProblemProcesses.setText(Strings.FORCE_SHUTDOWN_OFPROBLEMATIC_PROCESSES); btnClusterRecyclingKillByMemoryWithDump = new Button(groupWorkProcessesParams, SWT.CHECK); btnClusterRecyclingKillByMemoryWithDump.setLayoutData( new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1)); btnClusterRecyclingKillByMemoryWithDump.setText( - Messages.getString("ClusterDialog.ClusterRecyclingKillByMemoryWithDump")); //$NON-NLS-1$ + Strings.CLUSTER_RECYCLING_KILL_BYMEMORY_WITHDUMP); Label lblExpirationTimeout = new Label(container, SWT.NONE); lblExpirationTimeout.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblExpirationTimeout.setText( - Messages.getString("ClusterDialog.ShutDownProcessesStopAfterSecond")); //$NON-NLS-1$ + lblExpirationTimeout.setText(Strings.SHUTDOWN_PROCESSES_STOP_AFTER); txtExpirationTimeout = new Text(container, SWT.BORDER); - txtExpirationTimeout.setToolTipText( - Messages.getString("ClusterDialog.ShutDownProcessesStopAfter")); GridData gdtxtExpirationTimeout = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdtxtExpirationTimeout.widthHint = 200; txtExpirationTimeout.setLayoutData(gdtxtExpirationTimeout); @@ -217,12 +203,9 @@ protected Control createDialogArea(Composite parent) { Label lblSessionFaultToleranceLevel = new Label(container, SWT.NONE); lblSessionFaultToleranceLevel.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSessionFaultToleranceLevel.setText( - Messages.getString("ClusterDialog.FaultToleranceLevel")); //$NON-NLS-1$ + lblSessionFaultToleranceLevel.setText(Strings.FAULT_TOLERANCE_LEVEL); txtSessionFaultToleranceLevel = new Text(container, SWT.BORDER); - txtSessionFaultToleranceLevel.setToolTipText( - Messages.getString("ClusterDialog.FaultToleranceLevel")); GridData gdtxtSessionFaultToleranceLevel = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdtxtSessionFaultToleranceLevel.widthHint = 200; @@ -230,29 +213,26 @@ protected Control createDialogArea(Composite parent) { Label lblLoadBalancingMode = new Label(container, SWT.NONE); lblLoadBalancingMode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLoadBalancingMode.setText( - Messages.getString("ClusterDialog.LoadBalancingMode")); //$NON-NLS-1$ + lblLoadBalancingMode.setText(Strings.LOAD_BALANCING_MODE); comboLoadBalancingMode = new Combo(container, SWT.READ_ONLY); comboLoadBalancingMode.setVisibleItemCount(2); - comboLoadBalancingMode.setToolTipText(Messages.getString("ClusterDialog.LoadBalancingMode")); GridData gdcomboLoadBalancingMode = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gdcomboLoadBalancingMode.widthHint = 200; comboLoadBalancingMode.setLayoutData(gdcomboLoadBalancingMode); - comboLoadBalancingMode.add(Messages.getString("Dialogs.PerformancePriority")); //$NON-NLS-1$ - comboLoadBalancingMode.setData( - Messages.getString("Dialogs.PerformancePriority"), 0); //$NON-NLS-1$ - comboLoadBalancingMode.add(Messages.getString("Dialogs.MemoryPriority")); //$NON-NLS-1$ - comboLoadBalancingMode.setData(Messages.getString("Dialogs.MemoryPriority"), 1); //$NON-NLS-1$ + comboLoadBalancingMode.add(Strings.LOAD_BALANCING_MODE_PERFORMANCEPRIORITY); + comboLoadBalancingMode.setData(Strings.LOAD_BALANCING_MODE_PERFORMANCEPRIORITY, 0); + comboLoadBalancingMode.add(Strings.LOAD_BALANCING_MODE_MEMORYPRIORITY); + comboLoadBalancingMode.setData(Strings.LOAD_BALANCING_MODE_MEMORYPRIORITY, 1); comboLoadBalancingMode.select(0); - initServerProperties(); + initProperties(); return container; } - private void initServerProperties() { + private void initProperties() { IClusterInfo clusterInfo; if (clusterId != null) { @@ -263,8 +243,8 @@ private void initServerProperties() { } else { clusterInfo = new ClusterInfo(); - txtClusterName.setText(""); //$NON-NLS-1$ - txtComputerName.setText(""); //$NON-NLS-1$ + txtClusterName.setText(EMPTY_STRING); + txtComputerName.setText(EMPTY_STRING); } txtIpPort.setText(Integer.toString(clusterInfo.getMainPort())); @@ -290,17 +270,12 @@ private void initServerProperties() { txtMaxMemoryTimeLimit.setEditable(false); txtClusterRecyclingErrorsCountThreshold.setEditable(false); - txtMaxMemorySize.setToolTipText( - Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - txtMaxMemoryTimeLimit.setToolTipText( - Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - txtClusterRecyclingErrorsCountThreshold.setToolTipText( - Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + txtMaxMemorySize.setToolTipText(Strings.DEPRECATED_IN_FIFTEEN); + txtMaxMemoryTimeLimit.setToolTipText(Strings.DEPRECATED_IN_FIFTEEN); + txtClusterRecyclingErrorsCountThreshold.setToolTipText(Strings.DEPRECATED_IN_FIFTEEN); } else { btnClusterRecyclingKillByMemoryWithDump.setEnabled(false); - - btnClusterRecyclingKillByMemoryWithDump.setToolTipText( - Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ + btnClusterRecyclingKillByMemoryWithDump.setToolTipText(Strings.APPEARED_IN_FIFTEEN); } // У уже созданного кластера запрещено менять хост и порт @@ -310,10 +285,6 @@ private void initServerProperties() { } } - private void resetToProf() { - comboLoadBalancingMode.select(0); - } - private boolean checkVariablesFromControls() { var existsError = false; @@ -325,10 +296,10 @@ private boolean checkVariablesFromControls() { for (Text control : checksTextControls) { if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + control.setBackground(Helper.getPinkColor()); existsError = true; } else { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + control.setBackground(Helper.getWhiteColor()); } } @@ -344,9 +315,9 @@ private boolean checkVariablesFromControls() { for (Text control : checksIntControls) { try { Integer.parseInt(control.getText()); - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + control.setBackground(Helper.getWhiteColor()); } catch (Exception e) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + control.setBackground(Helper.getPinkColor()); existsError = true; } } @@ -427,12 +398,7 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - Button buttonApply = - createButton( - parent, - IDialogConstants.PROCEED_ID, - Messages.getString("Dialogs.Apply"), //$NON-NLS-1$ - false); + Button buttonApply = createButton(parent, IDialogConstants.PROCEED_ID, Strings.APPLY, false); buttonApply.setEnabled(clusterId != null); buttonApply.addSelectionListener( new SelectionAdapter() { @@ -441,39 +407,32 @@ public void widgetSelected(SelectionEvent e) { saveNewClusterProperties(); } }); - Button buttonReset = - createButton( - parent, - IDialogConstants.RETRY_ID, - Messages.getString("Dialogs.Reset"), //$NON-NLS-1$ - false); - buttonReset.setText(Messages.getString("Dialogs.Reset")); //$NON-NLS-1$ + + Button buttonReset = createButton(parent, IDialogConstants.RETRY_ID, Strings.RESET, false); + buttonReset.setText(Strings.RESET); buttonReset.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - initServerProperties(); + initProperties(); } }); + Button buttonResetToProf = - createButton( - parent, - IDialogConstants.RETRY_ID, - Messages.getString("Dialogs.ResetToPROF"), //$NON-NLS-1$ - false); + createButton(parent, IDialogConstants.RETRY_ID, Strings.RESET_TO_PROF, false); buttonResetToProf.addMouseTrackListener( new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { - comboLoadBalancingMode.setBackground(SWTResourceManager.getLightGreenColor()); + comboLoadBalancingMode.setBackground(Helper.getLightGreenColor()); } @Override public void mouseExit(MouseEvent e) { - comboLoadBalancingMode.setBackground(SWTResourceManager.getWhiteColor()); + comboLoadBalancingMode.setBackground(Helper.getWhiteColor()); } }); - buttonResetToProf.setText(Messages.getString("Dialogs.ResetToPROF")); //$NON-NLS-1$ + buttonResetToProf.setText(Strings.RESET_TO_PROF); buttonResetToProf.addSelectionListener( new SelectionAdapter() { @Override @@ -482,4 +441,49 @@ public void widgetSelected(SelectionEvent e) { } }); } + + private void resetToProf() { + comboLoadBalancingMode.select(0); + } + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + static final String CLUSTER_NAME = getString("ClusterName"); + static final String COMPUTER_NAME = getString("ComputerName"); + static final String IP_PORT = getString("IPPort"); + static final String SECURITY_LEVEL = Messages.getString("Dialogs.SecurityLevel"); + static final String SECURITY_LEVEL_DISABLE = Messages.getString("Dialogs.Disable"); + static final String SECURITY_LEVEL_CONNECTIONONLY = + Messages.getString("Dialogs.ConnectionOnly"); + static final String SECURITY_LEVEL_CONSTANTLY = Messages.getString("Dialogs.Constantly"); + static final String WP_RESTART = getString("WorkingProcessesRestart"); + static final String WP_RESTART_INTERVAL = getString("WorkingProcessesRestartInterval"); + static final String WP_ALLOWED_AMOUNT_OFMEMORY = + getString("WorkingProcessesAllowedAmountOfMemory"); + static final String WP_INTERVAL_EXCEEDING_ALLOWED_AMOUNT_OFMEMORY = + getString("WorkingProcessesIntervalExceedingAllowedAmountOfMemory"); + static final String ACCEPTABLE_DEVIATION_OFTHENUMBER_OFSERVER_ERRORS = + getString("AcceptableDeviationOfTheNumberOfServerErrors"); + static final String FORCE_SHUTDOWN_OFPROBLEMATIC_PROCESSES = + getString("ForceShutdownOfProblematicProcesses"); + static final String CLUSTER_RECYCLING_KILL_BYMEMORY_WITHDUMP = + getString("ClusterRecyclingKillByMemoryWithDump"); + static final String SHUTDOWN_PROCESSES_STOP_AFTER = getString("ShutDownProcessesStopAfter"); + static final String FAULT_TOLERANCE_LEVEL = getString("FaultToleranceLevel"); + static final String LOAD_BALANCING_MODE = getString("LoadBalancingMode"); + static final String LOAD_BALANCING_MODE_PERFORMANCEPRIORITY = + getString("LoadBalancingModePerformancePriority"); + static final String LOAD_BALANCING_MODE_MEMORYPRIORITY = + getString("LoadBalancingModeMemoryPriority"); + static final String DEPRECATED_IN_FIFTEEN = Messages.getString("Dialogs.DeprecatedInFifteen"); + static final String APPEARED_IN_FIFTEEN = Messages.getString("Dialogs.AppearedInFifteen"); + static final String APPLY = Messages.getString("Dialogs.Apply"); + static final String RESET = Messages.getString("Dialogs.Reset"); + static final String RESET_TO_PROF = Messages.getString("Dialogs.ResetToPROF"); + + static String getString(String key) { + return Messages.getString("ClusterDialog." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java deleted file mode 100644 index 8e4e830..0000000 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditServerDialog.java +++ /dev/null @@ -1,427 +0,0 @@ -package ru.yanygin.clusterAdminLibraryUI; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import org.eclipse.jface.dialogs.Dialog; -import org.eclipse.jface.dialogs.IDialogConstants; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ModifyEvent; -import org.eclipse.swt.events.ModifyListener; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.MessageBox; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.swt.widgets.TabFolder; -import org.eclipse.swt.widgets.TabItem; -import org.eclipse.swt.widgets.Table; -import org.eclipse.swt.widgets.TableColumn; -import org.eclipse.swt.widgets.TableItem; -import org.eclipse.swt.widgets.Text; -import ru.yanygin.clusterAdminLibrary.ClusterProvider; -import ru.yanygin.clusterAdminLibrary.Server; - -/** Dialog for create and edit Server parameters. */ -public class CreateEditServerDialog extends Dialog { - - private Server serverParams; - private boolean rasOnSameHost; - - private Text txtRasHost; - private Text txtRasPort; - - private Text txtAgentHost; - private Text txtAgentPort; - private Text txtLocalRasPort; - private Combo comboV8Version; - - private Button btnAutoconnect; - private Text txtAgentUser; - private Text txtAgentPasswors; - private Table tableCredentials; - private Button radioUseRemoteRas; - private Button radioUseLocalRas; - private Button btnSaveCredentials; - private Text txtDescription; - - /** - * Create the dialog. - * - * @param parentShell - parent shell - * @param serverParams - server params - */ - public CreateEditServerDialog(Shell parentShell, Server serverParams) { - super(parentShell); - setShellStyle(SWT.DIALOG_TRIM); - - // найти способ установить заголовок окна - // parentShell.setText("Parameters of the central server 1C:Enterprise"); - - this.serverParams = serverParams; - } - - /** - * Create contents of the dialog. - * - * @param parent - parent composite - */ - @Override - protected Control createDialogArea(Composite parent) { - - Composite container = (Composite) super.createDialogArea(parent); - GridLayout gridLayout = (GridLayout) container.getLayout(); - gridLayout.marginHeight = 0; - gridLayout.marginWidth = 0; - - TabFolder tabFolder = new TabFolder(container, SWT.NONE); - - TabItem tabConnect = new TabItem(tabFolder, SWT.NONE); - tabConnect.setText(Messages.getString("ServerDialog.ConnectParameters")); //$NON-NLS-1$ - - Composite connectContainer = new Composite(tabFolder, SWT.NONE); - tabConnect.setControl(connectContainer); - GridLayout glconnectContainer = new GridLayout(2, false); - connectContainer.setLayout(glconnectContainer); - - Composite composite = new Composite(connectContainer, SWT.NONE); - composite.setLayout(new GridLayout(2, false)); - composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); - - Label lblDescription = new Label(composite, SWT.NONE); - lblDescription.setText(Messages.getString("ServerDialog.Description")); //$NON-NLS-1$ - - txtDescription = new Text(composite, SWT.BORDER); - txtDescription.setToolTipText(Messages.getString("ServerDialog.Description")); //$NON-NLS-1$ - txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - - btnAutoconnect = new Button(connectContainer, SWT.CHECK); - GridData gdbtnAutoconnect = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdbtnAutoconnect.horizontalIndent = 5; - btnAutoconnect.setLayoutData(gdbtnAutoconnect); - btnAutoconnect.setText(Messages.getString("ServerDialog.AutoconnectAtStartup")); //$NON-NLS-1$ - new Label(connectContainer, SWT.NONE); - - radioUseRemoteRas = new Button(connectContainer, SWT.RADIO); - GridData gdradioUseRemoteRas = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdradioUseRemoteRas.horizontalIndent = 5; - radioUseRemoteRas.setLayoutData(gdradioUseRemoteRas); - radioUseRemoteRas.setSelection(true); - radioUseRemoteRas.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - setEnabledRasGroupParameters(); - } - }); - radioUseRemoteRas.setBounds(0, 0, 90, 16); - radioUseRemoteRas.setText(Messages.getString("ServerDialog.UseRemoteRAS")); //$NON-NLS-1$ - - radioUseLocalRas = new Button(connectContainer, SWT.RADIO); - GridData gdradioUseLocalRas = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdradioUseLocalRas.horizontalIndent = 5; - radioUseLocalRas.setLayoutData(gdradioUseLocalRas); - radioUseLocalRas.setBounds(0, 0, 90, 16); - radioUseLocalRas.setText(Messages.getString("ServerDialog.UseLocalRAS")); //$NON-NLS-1$ - - Group grpRemoteRasParameters = new Group(connectContainer, SWT.NONE); - grpRemoteRasParameters.setText( - Messages.getString("ServerDialog.RemoteRASParameters")); //$NON-NLS-1$ - grpRemoteRasParameters.setLayout(new GridLayout(2, false)); - - Label lblRasHost = new Label(grpRemoteRasParameters, SWT.NONE); - lblRasHost.setText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - Label lblRasPort = new Label(grpRemoteRasParameters, SWT.NONE); - lblRasPort.setSize(46, 15); - lblRasPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - txtRasHost = new Text(grpRemoteRasParameters, SWT.BORDER); - txtRasHost.addModifyListener( - new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - if (rasOnSameHost) { - txtAgentHost.setText(((Text) e.widget).getText()); - } - checkRasOnSameHost(); - } - }); - GridData gdtxtRasHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdtxtRasHost.widthHint = 200; - txtRasHost.setLayoutData(gdtxtRasHost); - txtRasHost.setToolTipText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - txtRasPort = new Text(grpRemoteRasParameters, SWT.BORDER); - GridData gdtxtRasPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtRasPort.widthHint = 50; - txtRasPort.setLayoutData(gdtxtRasPort); - txtRasPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - Group grpLocalRasParameters = new Group(connectContainer, SWT.NONE); - grpLocalRasParameters.setSize(417, 90); - grpLocalRasParameters.setText( - Messages.getString("ServerDialog.LocalRASParameters")); //$NON-NLS-1$ - grpLocalRasParameters.setLayout(new GridLayout(2, false)); - - Label lblV8Version = new Label(grpLocalRasParameters, SWT.NONE); - lblV8Version.setSize(124, 15); - lblV8Version.setText(Messages.getString("ServerDialog.V8Version")); //$NON-NLS-1$ - - Label lblLocalRasPort = new Label(grpLocalRasParameters, SWT.NONE); - lblLocalRasPort.setSize(77, 15); - lblLocalRasPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - comboV8Version = new Combo(grpLocalRasParameters, SWT.READ_ONLY); - GridData gdcomboV8Version = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdcomboV8Version.widthHint = 140; - comboV8Version.setLayoutData(gdcomboV8Version); - comboV8Version.setSize(389, 21); - comboV8Version.setToolTipText(Messages.getString("ServerDialog.V8Version")); //$NON-NLS-1$ - - txtLocalRasPort = new Text(grpLocalRasParameters, SWT.BORDER); - GridData gdtxtLocalRasPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); - gdtxtLocalRasPort.widthHint = 50; - txtLocalRasPort.setLayoutData(gdtxtLocalRasPort); - txtLocalRasPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - Group grpRagentParameters = new Group(connectContainer, SWT.NONE); - grpRagentParameters.setText(Messages.getString("ServerDialog.AgentParameters")); //$NON-NLS-1$ - grpRagentParameters.setLayout(new GridLayout(2, false)); - - Label lblAgentHost = new Label(grpRagentParameters, SWT.NONE); - lblAgentHost.setText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - Label lblAgentPort = new Label(grpRagentParameters, SWT.NONE); - lblAgentPort.setText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - - txtAgentHost = new Text(grpRagentParameters, SWT.BORDER); - txtAgentHost.addModifyListener( - new ModifyListener() { - @Override - public void modifyText(ModifyEvent e) { - checkRasOnSameHost(); - } - }); - GridData gdtxtAgentHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); - gdtxtAgentHost.widthHint = 200; - txtAgentHost.setLayoutData(gdtxtAgentHost); - txtAgentHost.setToolTipText(Messages.getString("ServerDialog.Host")); //$NON-NLS-1$ - - txtAgentPort = new Text(grpRagentParameters, SWT.BORDER); - GridData gdtxtAgentPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtAgentPort.widthHint = 50; - txtAgentPort.setLayoutData(gdtxtAgentPort); - txtAgentPort.setToolTipText(Messages.getString("ServerDialog.Port")); //$NON-NLS-1$ - new Label(connectContainer, SWT.NONE); - - TabItem tabCredentials = new TabItem(tabFolder, SWT.NONE); - tabCredentials.setText(Messages.getString("ServerDialog.Credentials")); //$NON-NLS-1$ - - Composite credentialsContainer = new Composite(tabFolder, SWT.NONE); - tabCredentials.setControl(credentialsContainer); - credentialsContainer.setLayout(new GridLayout(1, false)); - - btnSaveCredentials = new Button(credentialsContainer, SWT.CHECK); - btnSaveCredentials.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - btnSaveCredentials.setSize(155, 16); - btnSaveCredentials.setText(Messages.getString("ServerDialog.SaveCredentials")); //$NON-NLS-1$ - - Group grpCentralServerCredential = new Group(credentialsContainer, SWT.NONE); - grpCentralServerCredential.setText( - Messages.getString("ServerDialog.CentralServerAdminstrator")); //$NON-NLS-1$ - grpCentralServerCredential.setLayout(new GridLayout(4, false)); - GridData gdgrpCentralServerCredential = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); - gdgrpCentralServerCredential.verticalIndent = 5; - grpCentralServerCredential.setLayoutData(gdgrpCentralServerCredential); - - Label lblAgentUser = new Label(grpCentralServerCredential, SWT.NONE); - lblAgentUser.setSize(23, 15); - lblAgentUser.setText(Messages.getString("ServerDialog.User")); //$NON-NLS-1$ - - txtAgentUser = new Text(grpCentralServerCredential, SWT.BORDER); - GridData gdtxtAgentUser = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtAgentUser.widthHint = 200; - txtAgentUser.setLayoutData(gdtxtAgentUser); - txtAgentUser.setSize(76, 21); - txtAgentUser.setToolTipText(Messages.getString("ServerDialog.User")); //$NON-NLS-1$ - - Label lblAgentPwd = new Label(grpCentralServerCredential, SWT.NONE); - lblAgentPwd.setSize(50, 15); - lblAgentPwd.setText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ - - txtAgentPasswors = new Text(grpCentralServerCredential, SWT.BORDER | SWT.PASSWORD); - GridData gdtxtAgentPasswors = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); - gdtxtAgentPasswors.widthHint = 100; - txtAgentPasswors.setLayoutData(gdtxtAgentPasswors); - txtAgentPasswors.setSize(76, 21); - txtAgentPasswors.setToolTipText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ - - tableCredentials = new Table(credentialsContainer, SWT.BORDER | SWT.FULL_SELECTION); - GridData gdtableCredentials = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); - gdtableCredentials.heightHint = 183; - gdtableCredentials.verticalIndent = 5; - tableCredentials.setLayoutData(gdtableCredentials); - tableCredentials.setHeaderVisible(true); - tableCredentials.setLinesVisible(true); - - TableColumn tblclmnType = new TableColumn(tableCredentials, SWT.NONE); - tblclmnType.setWidth(60); - tblclmnType.setText(Messages.getString("ServerDialog.Type")); //$NON-NLS-1$ - - TableColumn tblclmnName = new TableColumn(tableCredentials, SWT.NONE); - tblclmnName.setWidth(160); - tblclmnName.setText(Messages.getString("ServerDialog.Name")); //$NON-NLS-1$ - - TableColumn tblclmnId = new TableColumn(tableCredentials, SWT.NONE); - tblclmnId.setWidth(100); - tblclmnId.setText(Messages.getString("ServerDialog.ID")); //$NON-NLS-1$ - - TableColumn tblclmnUsername = new TableColumn(tableCredentials, SWT.NONE); - tblclmnUsername.setWidth(100); - tblclmnUsername.setText(Messages.getString("ServerDialog.Username")); //$NON-NLS-1$ - - TableColumn tblclmnPassword = new TableColumn(tableCredentials, SWT.NONE); - tblclmnPassword.setWidth(100); - tblclmnPassword.setText(Messages.getString("ServerDialog.Password")); //$NON-NLS-1$ - new Label(container, SWT.NONE); - - initServerProperties(); - checkRasOnSameHost(); - setEnabledRasGroupParameters(); - - return container; - } - - private void initServerProperties() { - if (serverParams != null) { - this.txtDescription.setText(serverParams.getDescription()); - - this.txtRasHost.setText(serverParams.getRasHost()); - this.txtRasPort.setText(serverParams.getRasPortAsString()); - - this.txtAgentHost.setText(serverParams.getAgentHost()); - this.txtAgentPort.setText(serverParams.getAgentPortAsString()); - - this.radioUseRemoteRas.setSelection(!serverParams.getUseLocalRas()); - this.radioUseLocalRas.setSelection(serverParams.getUseLocalRas()); - List installedV8Versions = new ArrayList<>(); - ClusterProvider.getInstalledV8Versions() - .forEach( - (desc, path) -> { - installedV8Versions.add(desc); - }); - installedV8Versions.sort(String.CASE_INSENSITIVE_ORDER); - comboV8Version.setItems(installedV8Versions.toArray(new String[0])); - - this.comboV8Version.setText(serverParams.getLocalRasV8version()); - - this.txtLocalRasPort.setText(serverParams.getLocalRasPortAsString()); - - this.btnAutoconnect.setSelection(serverParams.getAutoconnect()); - this.btnSaveCredentials.setSelection(serverParams.getSaveCredentials()); - this.txtAgentUser.setText(serverParams.getAgentUserName()); - this.txtAgentPasswors.setText(serverParams.getAgentPassword()); - - serverParams.getCredentials().forEach( - (uuid, userPass) -> { - TableItem credentialItem = new TableItem(this.tableCredentials, SWT.NONE); - - String[] itemText = { - "cluster", //$NON-NLS-1$ - userPass[2], // clusterName - uuid.toString(), - userPass[0], // username - userPass[1] // pass - }; - - credentialItem.setText(itemText); - credentialItem.setData("UUID", uuid); //$NON-NLS-1$ - credentialItem.setChecked(false); - }); - } - } - - private boolean saveNewServerProperties() { - try { - serverParams.setDescription(txtDescription.getText()); - - Map credentialsClustersCashe = new HashMap<>(); - if (btnSaveCredentials.getSelection()) { - TableItem[] credentials = tableCredentials.getItems(); - for (TableItem credential : credentials) { - UUID uuid = (UUID) credential.getData("UUID"); //$NON-NLS-1$ - credentialsClustersCashe.put( - uuid, - new String[] {credential.getText(3), credential.getText(4), credential.getText(1)}); - } - } - - serverParams.setAgentHost(txtAgentHost.getText()); - serverParams.setAgentPort(Integer.parseInt(txtAgentPort.getText())); - serverParams.setRasHost(txtRasHost.getText()); - serverParams.setRasPort(Integer.parseInt(txtRasPort.getText())); - serverParams.setUseLocalRas(!radioUseRemoteRas.getSelection()); - serverParams.setLocalRasPort(Integer.parseInt(txtLocalRasPort.getText())); - - serverParams.setLocalRasV8version(comboV8Version.getText()); - serverParams.setAutoconnect(btnAutoconnect.getSelection()); - serverParams.setSaveCredentials(btnSaveCredentials.getSelection()); - serverParams.setAgentUserName(txtAgentUser.getText()); - serverParams.setAgentPassword(txtAgentPasswors.getText()); - serverParams.setCredentials(credentialsClustersCashe); - - // LOGGER.info("Set new properties for server <{}>", serverParams.getServerKey()); // - //$NON-NLS-1$ - - return true; - - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - } - - /** - * Create contents of the button bar. - * - * @param parent - parent composite - */ - @Override - protected void createButtonsForButtonBar(Composite parent) { - Button button = - createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - if (saveNewServerProperties()) { - close(); - } - } - }); - createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - } - - private void checkRasOnSameHost() { - rasOnSameHost = txtAgentHost.getText().equals(txtRasHost.getText()); - } - - private void setEnabledRasGroupParameters() { - txtRasHost.setEnabled(radioUseRemoteRas.getSelection()); - txtRasPort.setEnabled(radioUseRemoteRas.getSelection()); - comboV8Version.setEnabled(!radioUseRemoteRas.getSelection()); - txtLocalRasPort.setEnabled(!radioUseRemoteRas.getSelection()); - } -} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java index fe8b3e3..f5d556d 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateInfobaseDialog.java @@ -12,7 +12,6 @@ import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -20,44 +19,41 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import org.eclipse.wb.swt.SWTResourceManager; +import ru.yanygin.clusterAdminLibrary.Helper; import ru.yanygin.clusterAdminLibrary.Server; -/** Dialog for create infobase. */ +/** Диалог создания информационной базы. */ public class CreateInfobaseDialog extends Dialog { - private UUID clusterId; + private static final String DBMS_TYPE_MSSQLSERVER = "MSSQLServer"; //$NON-NLS-1$ + private static final String DBMS_TYPE_POSTGRESQL = "PostgreSQL"; //$NON-NLS-1$ + private static final String DBMS_TYPE_IBMDB2 = "IBMDB2"; //$NON-NLS-1$ + private static final String DBMS_TYPE_ORACLEDATABASE = "OracleDatabase"; //$NON-NLS-1$ + private static final String ZERO_OFFSET = "0"; //$NON-NLS-1$ + private static final String MSSQL_OFFSET = "2000"; //$NON-NLS-1$ private Server server; - private Button btnSheduledJobsDenied; - private Button btnAllowDistributeLicense; - private Button btnInfobaseCreationMode; + private UUID clusterId; + private UUID newInfobaseUuid; + private UUID sampleInfobaseId; + private Text txtInfobaseName; private Text txtServerDbName; private Text txtDatabaseDbName; private Text txtDatabaseDbUser; private Text txtDatabaseDbPassword; private Text txtInfobaseDescription; + private Combo comboSecurityLevel; private Combo comboServerDbType; private Combo comboLocale; // Откуда то загрузить все возможные локали private Combo comboDateOffset; - private UUID newInfobaseUuid; - - /** - * Return infobase ID for create new infobase from sample. - * - * @return infobase ID - */ - public UUID getNewInfobaseUuid() { - return newInfobaseUuid; - } - - private UUID sampleInfobaseId; + private Button btnSheduledJobsDenied; + private Button btnAllowDistributeLicense; + private Button btnInfobaseCreationMode; /** * Create the dialog. @@ -72,14 +68,17 @@ public CreateInfobaseDialog( super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - this.server = server; this.clusterId = clusterId; this.sampleInfobaseId = sampleInfobaseId; } + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + /** * Create contents of the dialog. * @@ -94,7 +93,7 @@ protected Control createDialogArea(Composite parent) { Label lblInfobaseName = new Label(container, SWT.NONE); lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseName.setText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ + lblInfobaseName.setText(Strings.INFOBASE_NAME); txtInfobaseName = new Text(container, SWT.BORDER); txtInfobaseName.addModifyListener( @@ -104,145 +103,119 @@ public void modifyText(ModifyEvent e) { txtDatabaseDbName.setText(((Text) e.widget).getText()); } }); - txtInfobaseName.setToolTipText( - Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblInfobaseDescription = new Label(container, SWT.NONE); lblInfobaseDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseDescription.setText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ + lblInfobaseDescription.setText(Strings.INFOBASE_DESCRIPTION); txtInfobaseDescription = new Text(container, SWT.BORDER); - txtInfobaseDescription.setToolTipText( - Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ txtInfobaseDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblSecurityLevel = new Label(container, SWT.NONE); lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + lblSecurityLevel.setText(Strings.SECURITY_LEVEL); comboSecurityLevel = new Combo(container, SWT.READ_ONLY); - comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ comboSecurityLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ + comboSecurityLevel.add(Strings.SECURITY_LEVEL_DISABLE); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_DISABLE, 0); + comboSecurityLevel.add(Strings.SECURITY_LEVEL_CONNECTIONONLY); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_CONNECTIONONLY, 1); + comboSecurityLevel.add(Strings.SECURITY_LEVEL_CONSTANTLY); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_CONSTANTLY, 2); comboSecurityLevel.select(0); Label lblServerDbName = new Label(container, SWT.NONE); lblServerDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDbName.setText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ + lblServerDbName.setText(Strings.SERVER_DB_NAME); txtServerDbName = new Text(container, SWT.BORDER); - txtServerDbName.setToolTipText( - Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ txtServerDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblServerDbType = new Label(container, SWT.NONE); lblServerDbType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDbType.setText(Messages.getString("InfobaseDialog.DBMSType")); //$NON-NLS-1$ + lblServerDbType.setText(Strings.DBMS_TYPE); comboServerDbType = new Combo(container, SWT.READ_ONLY); comboServerDbType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboServerDbType.add(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ - comboServerDbType.add(Messages.getString("InfobaseDialog.PostgreSQL")); //$NON-NLS-1$ - comboServerDbType.add(Messages.getString("InfobaseDialog.IBMDB2")); //$NON-NLS-1$ - comboServerDbType.add(Messages.getString("InfobaseDialog.OracleDatabase")); //$NON-NLS-1$ + comboServerDbType.add(DBMS_TYPE_MSSQLSERVER); + comboServerDbType.add(DBMS_TYPE_POSTGRESQL); + comboServerDbType.add(DBMS_TYPE_IBMDB2); + comboServerDbType.add(DBMS_TYPE_ORACLEDATABASE); comboServerDbType.select(0); comboServerDbType.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - boolean dateOffsetEnabled = - comboServerDbType - .getText() - .equals(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ - comboDateOffset.setEnabled(dateOffsetEnabled); - comboDateOffset.setText(dateOffsetEnabled ? "2000" : "0"); //$NON-NLS-1$ //$NON-NLS-2$ + boolean dbmsTypeIsMsSql = comboServerDbType.getText().equals(DBMS_TYPE_MSSQLSERVER); + comboDateOffset.setEnabled(dbmsTypeIsMsSql); + comboDateOffset.setText(dbmsTypeIsMsSql ? MSSQL_OFFSET : ZERO_OFFSET); } }); Label lblDatabaseDbName = new Label(container, SWT.NONE); lblDatabaseDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbName.setText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ + lblDatabaseDbName.setText(Strings.DATABASE_DB_NAME); txtDatabaseDbName = new Text(container, SWT.BORDER); - txtDatabaseDbName.setToolTipText( - Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ txtDatabaseDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblDatabaseDbUser = new Label(container, SWT.NONE); lblDatabaseDbUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbUser.setText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ + lblDatabaseDbUser.setText(Strings.DATABASE_DB_USER); txtDatabaseDbUser = new Text(container, SWT.BORDER); - txtDatabaseDbUser.setToolTipText( - Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ txtDatabaseDbUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblDatabaseDbPassword = new Label(container, SWT.NONE); lblDatabaseDbPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblDatabaseDbPassword.setAlignment(SWT.RIGHT); - lblDatabaseDbPassword.setText( - Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ + lblDatabaseDbPassword.setText(Strings.DATABASE_DB_PASSWORD); txtDatabaseDbPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); - txtDatabaseDbPassword.setToolTipText( - Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ txtDatabaseDbPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnAllowDistributeLicense = new Button(container, SWT.CHECK); btnAllowDistributeLicense.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnAllowDistributeLicense.setText( - Messages.getString("InfobaseDialog.AllowDistributeLicense")); //$NON-NLS-1$ + btnAllowDistributeLicense.setText(Strings.ALLOW_DISTRIBUTE_LICENSE); Label lblLocale = new Label(container, SWT.NONE); lblLocale.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLocale.setText(Messages.getString("InfobaseDialog.Locale")); //$NON-NLS-1$ + lblLocale.setText(Strings.LOCALE); comboLocale = new Combo(container, SWT.READ_ONLY); - comboLocale.setItems( - new String[] { - Messages.getString("InfobaseDialog.ru_RU"), - Messages.getString("InfobaseDialog.en_US"), - "xx_XX", - "yy_YY" - }); + comboLocale.setItems(getLocales()); comboLocale.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); comboLocale.select(0); Label lblDateOffset = new Label(container, SWT.NONE); lblDateOffset.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDateOffset.setText(Messages.getString("InfobaseDialog.DateOffset")); //$NON-NLS-1$ + lblDateOffset.setText(Strings.DATE_OFFSET); comboDateOffset = new Combo(container, SWT.READ_ONLY); - comboDateOffset.setItems("0", "2000"); //$NON-NLS-1$ //$NON-NLS-2$ + comboDateOffset.setItems(ZERO_OFFSET, MSSQL_OFFSET); comboDateOffset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboDateOffset.setText("2000"); //$NON-NLS-1$ + comboDateOffset.setText(MSSQL_OFFSET); btnInfobaseCreationMode = new Button(container, SWT.CHECK); btnInfobaseCreationMode.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnInfobaseCreationMode.setText( - Messages.getString("InfobaseDialog.CreateDatabaseIfNotAvailable")); //$NON-NLS-1$ + btnInfobaseCreationMode.setText(Strings.CREATE_DATABASE_IF_NOTAVAILABLE); btnSheduledJobsDenied = new Button(container, SWT.CHECK); btnSheduledJobsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnSheduledJobsDenied.setText( - Messages.getString("InfobaseDialog.SheduledJobsDenied")); //$NON-NLS-1$ + btnSheduledJobsDenied.setText(Strings.SHEDULED_JOBS_DENIED); new Label(container, SWT.NONE); - initInfobaseProperties(); + initProperties(); return container; } - private void initInfobaseProperties() { + private void initProperties() { if (sampleInfobaseId == null) { txtInfobaseName.setText(""); //$NON-NLS-1$ @@ -257,8 +230,7 @@ private void initInfobaseProperties() { txtDatabaseDbName.setText(""); //$NON-NLS-1$ txtDatabaseDbUser.setText(""); //$NON-NLS-1$ txtDatabaseDbPassword.setText(""); //$NON-NLS-1$ - txtDatabaseDbPassword.setToolTipText( - Messages.getString("InfobaseDialog.YouNeedToEnter")); //$NON-NLS-1$ + txtDatabaseDbPassword.setToolTipText(Strings.NEED_TO_ENTER); } else { @@ -281,13 +253,12 @@ private void initInfobaseProperties() { txtDatabaseDbName.setText(infoBaseInfo.getDbName()); txtDatabaseDbUser.setText(infoBaseInfo.getDbUser()); txtDatabaseDbPassword.setText(""); //$NON-NLS-1$ - txtDatabaseDbPassword.setToolTipText( - Messages.getString("InfobaseDialog.YouNeedToEnter")); //$NON-NLS-1$ + txtDatabaseDbPassword.setToolTipText(Strings.NEED_TO_ENTER); - txtInfobaseName.setForeground(new Color(255, 0, 0)); - txtDatabaseDbName.setForeground(new Color(255, 0, 0)); - btnInfobaseCreationMode.setForeground(new Color(255, 0, 0)); - txtDatabaseDbPassword.setForeground(new Color(255, 0, 0)); + txtInfobaseName.setForeground(Helper.getRedColor()); + txtDatabaseDbName.setForeground(Helper.getRedColor()); + btnInfobaseCreationMode.setForeground(Helper.getRedColor()); + txtDatabaseDbPassword.setForeground(Helper.getRedColor()); } } @@ -303,10 +274,10 @@ private boolean checkVariablesFromControls() { for (Text control : checksTextControls) { if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + control.setBackground(Helper.getPinkColor()); existsError = true; } else { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + control.setBackground(Helper.getWhiteColor()); } } @@ -335,23 +306,29 @@ private boolean saveInfobaseProperties() { infoBaseInfo.setDbUser(txtDatabaseDbUser.getText()); infoBaseInfo.setDbPassword(txtDatabaseDbPassword.getText()); infoBaseInfo.setLocale(comboLocale.getText()); - if (comboServerDbType - .getText() - .equals(Messages.getString("InfobaseDialog.MSSQLServer"))) { //$NON-NLS-1$ + if (comboServerDbType.getText().equals(DBMS_TYPE_MSSQLSERVER)) { infoBaseInfo.setDateOffset(Integer.parseInt(comboDateOffset.getText())); } - try { - newInfobaseUuid = - server.createInfoBase( - clusterId, infoBaseInfo, (btnInfobaseCreationMode.getSelection() ? 1 : 0)); - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); - return false; - } - return true; + newInfobaseUuid = + server.createInfoBase( + clusterId, infoBaseInfo, (btnInfobaseCreationMode.getSelection() ? 1 : 0)); + + return newInfobaseUuid != Helper.EMPTY_UUID; + } + + /** + * Возвращает ID созданной инфобазы (при создании из образца). + * + * @return ID инфобазы + */ + public UUID getNewInfobaseUuid() { + return newInfobaseUuid; + } + + private String[] getLocales() { + // return Locale.getAvailableLocales(); + return new String[] {"ru_RU", "en_US", "xx_XX", "yy_YY"}; } /** @@ -361,9 +338,9 @@ private boolean saveInfobaseProperties() { */ @Override protected void createButtonsForButtonBar(Composite parent) { - Button button = + Button buttonOk = createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); - button.addSelectionListener( + buttonOk.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { @@ -375,4 +352,31 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + static final String INFOBASE_NAME = getString("InfobaseName"); + static final String INFOBASE_DESCRIPTION = getString("Description"); + static final String SECURITY_LEVEL = Messages.getString("Dialogs.SecurityLevel"); + static final String SECURITY_LEVEL_DISABLE = Messages.getString("Dialogs.Disable"); + static final String SECURITY_LEVEL_CONNECTIONONLY = + Messages.getString("Dialogs.ConnectionOnly"); + static final String SECURITY_LEVEL_CONSTANTLY = Messages.getString("Dialogs.Constantly"); + static final String SERVER_DB_NAME = getString("ServerDBName"); + static final String DBMS_TYPE = getString("DBMSType"); + static final String DATABASE_DB_NAME = getString("DatabaseDBName"); + static final String DATABASE_DB_USER = getString("DatabaseDBUser"); + static final String DATABASE_DB_PASSWORD = getString("DatabaseDBPassword"); + static final String ALLOW_DISTRIBUTE_LICENSE = getString("AllowDistributeLicense"); + static final String LOCALE = getString("Locale"); + static final String DATE_OFFSET = getString("DateOffset"); + static final String CREATE_DATABASE_IF_NOTAVAILABLE = getString("CreateDatabaseIfNotAvailable"); + static final String SHEDULED_JOBS_DENIED = getString("SheduledJobsDenied"); + static final String NEED_TO_ENTER = getString("YouNeedToEnter"); + + static String getString(String key) { + return Messages.getString("InfobaseDialog." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java index abf74c8..c344cb6 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/DropInfobaseDialog.java @@ -6,6 +6,7 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -15,14 +16,13 @@ import org.eclipse.swt.widgets.Shell; import ru.yanygin.clusterAdminLibrary.Server; -/** Dialog for drop infobase. */ +/** Диалог удаления информационной базы. */ public class DropInfobaseDialog extends Dialog { - private UUID clusterId; private Server server; - - private int databaseDropMode; + private UUID clusterId; private UUID infobaseId; + private int databaseDropMode; /** * Create the dialog. @@ -36,12 +36,15 @@ public DropInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.infobaseId = infobaseId; - this.clusterId = clusterId; this.server = server; + this.clusterId = clusterId; + this.infobaseId = infobaseId; + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); } /** @@ -60,11 +63,11 @@ protected Control createDialogArea(Composite parent) { GridData gdlblInfo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1); gdlblInfo.heightHint = 34; lblInfo.setLayoutData(gdlblInfo); - lblInfo.setText(Messages.getString("Dialogs.DropInfobaseDescription")); //$NON-NLS-1$ + lblInfo.setText(Strings.DROP_INFOBASE_DESCRIPTION); new Label(container, SWT.NONE); Button btnNotDelete = new Button(container, SWT.RADIO); - btnNotDelete.setText(Messages.getString("Dialogs.LeaveDatabaseUnchanged")); //$NON-NLS-1$ + btnNotDelete.setText(Strings.LEAVE_DATABASE_UNCHANGED); btnNotDelete.addSelectionListener( new SelectionAdapter() { @Override @@ -75,8 +78,7 @@ public void widgetSelected(SelectionEvent e) { new Label(container, SWT.NONE); Button btnDeleteTheDatabase = new Button(container, SWT.RADIO); - btnDeleteTheDatabase.setText( - Messages.getString("Dialogs.DeleteTheEntireDatabase")); //$NON-NLS-1$ + btnDeleteTheDatabase.setText(Strings.DELETE_THE_ENTIRE_DATABASE); btnDeleteTheDatabase.addSelectionListener( new SelectionAdapter() { @Override @@ -87,7 +89,7 @@ public void widgetSelected(SelectionEvent e) { new Label(container, SWT.NONE); Button btnClearTheDatabase = new Button(container, SWT.RADIO); - btnClearTheDatabase.setText(Messages.getString("Dialogs.ClearTheDatabase")); //$NON-NLS-1$ + btnClearTheDatabase.setText(Strings.CLEAR_THE_DATABASE); btnClearTheDatabase.addSelectionListener( new SelectionAdapter() { @Override @@ -125,4 +127,22 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDropInfobaseParameters"); + static final String DROP_INFOBASE_DESCRIPTION = getString("DropInfobaseDescription"); + static final String LEAVE_DATABASE_UNCHANGED = getString("LeaveDatabaseUnchanged"); + static final String DELETE_THE_ENTIRE_DATABASE = getString("DeleteTheEntireDatabase"); + static final String CLEAR_THE_DATABASE = getString("ClearTheDatabase"); + + static String getString(String key) { + return Messages.getString("InfobaseDialog." + key); //$NON-NLS-1$ + } + } + + @Override + protected Point getInitialSize() { + return new Point(500, 230); + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/InfobaseDialog.java similarity index 70% rename from clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java rename to clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/InfobaseDialog.java index 1302138..676193f 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/EditInfobaseDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/InfobaseDialog.java @@ -23,38 +23,50 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import org.eclipse.wb.swt.SWTResourceManager; +import ru.yanygin.clusterAdminLibrary.Helper; import ru.yanygin.clusterAdminLibrary.Server; -/** Dialog for edit infobase parameters. */ -public class EditInfobaseDialog extends Dialog { +/** Диалог редактирования параметров информационной базы. */ +public class InfobaseDialog extends Dialog { + + private static final String DBMS_TYPE_MSSQLSERVER = "MSSQLServer"; //$NON-NLS-1$ + private static final String DBMS_TYPE_POSTGRESQL = "PostgreSQL"; //$NON-NLS-1$ + private static final String DBMS_TYPE_IBMDB2 = "IBMDB2"; //$NON-NLS-1$ + private static final String DBMS_TYPE_ORACLEDATABASE = "OracleDatabase"; //$NON-NLS-1$ + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ + + private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //$NON-NLS-1$ + private final Date emptyDate = new Date(0); - private UUID infoBaseId; - private UUID clusterId; private Server server; + private UUID clusterId; + private UUID infoBaseId; + private boolean creationMode = false; // Controls - private Button btnSessionsDenied; - private Button btnSheduledJobsDenied; - private Button btnAllowDistributeLicense; - private Button btnExternalSessionManagerRequired; private Text txtInfobaseName; private Text txtServerDbName; private Text txtDatabaseDbName; private Text txtDatabaseDbUser; private Text txtDatabaseDbPassword; private Text txtInfobaseDescription; - private Combo comboSecurityLevel; private Text txtPermissionCode; private Text txtDeniedParameter; private Text txtExternalSessionManagerConnectionString; private Text txtSecurityProfile; private Text txtSafeModeSecurityProfile; private Text txtDeniedMessage; - private Combo comboServerDbType; private Text deniedFromDate; private Text deniedToDate; + private Combo comboSecurityLevel; + private Combo comboServerDbType; + + private Button btnSessionsDenied; + private Button btnSheduledJobsDenied; + private Button btnAllowDistributeLicense; + private Button btnExternalSessionManagerRequired; + /** * Create the dialog. * @@ -63,16 +75,24 @@ public class EditInfobaseDialog extends Dialog { * @param clusterId - cluster ID * @param infoBaseId - infobase ID */ - public EditInfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID infoBaseId) { + public InfobaseDialog(Shell parentShell, Server server, UUID clusterId, UUID infoBaseId) { super(parentShell); - setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); + setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL); this.server = server; this.clusterId = clusterId; this.infoBaseId = infoBaseId; + + // три варианта открытия окна: + // - существующая база + // - новая база + // - новая база (на основе образца) + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); } /** @@ -89,102 +109,87 @@ protected Control createDialogArea(Composite parent) { Label lblInfobaseName = new Label(container, SWT.NONE); lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseName.setText(Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ + lblInfobaseName.setText(Strings.INFOBASE_NAME); txtInfobaseName = new Text(container, SWT.BORDER); - txtInfobaseName.setToolTipText( - Messages.getString("InfobaseDialog.InfobaseName")); //$NON-NLS-1$ txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblInfobaseDescription = new Label(container, SWT.NONE); lblInfobaseDescription.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseDescription.setText(Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ + lblInfobaseDescription.setText(Strings.INFOBASE_DESCRIPTION); txtInfobaseDescription = new Text(container, SWT.BORDER); - txtInfobaseDescription.setToolTipText( - Messages.getString("InfobaseDialog.Description")); //$NON-NLS-1$ txtInfobaseDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblSecurityLevel = new Label(container, SWT.NONE); lblSecurityLevel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityLevel.setText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ + lblSecurityLevel.setText(Strings.SECURITY_LEVEL); comboSecurityLevel = new Combo(container, SWT.READ_ONLY); comboSecurityLevel.setEnabled(false); - comboSecurityLevel.setToolTipText(Messages.getString("Dialogs.SecurityLevel")); //$NON-NLS-1$ comboSecurityLevel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboSecurityLevel.add(Messages.getString("Dialogs.Disable")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Disable"), 0); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.ConnectionOnly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.ConnectionOnly"), 1); //$NON-NLS-1$ - comboSecurityLevel.add(Messages.getString("Dialogs.Constantly")); //$NON-NLS-1$ - comboSecurityLevel.setData(Messages.getString("Dialogs.Constantly"), 2); //$NON-NLS-1$ + comboSecurityLevel.add(Strings.SECURITY_LEVEL_DISABLE); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_DISABLE, 0); + comboSecurityLevel.add(Strings.SECURITY_LEVEL_CONNECTIONONLY); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_CONNECTIONONLY, 1); + comboSecurityLevel.add(Strings.SECURITY_LEVEL_CONSTANTLY); + comboSecurityLevel.setData(Strings.SECURITY_LEVEL_CONSTANTLY, 2); comboSecurityLevel.select(0); Label lblServerDbName = new Label(container, SWT.NONE); lblServerDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDbName.setText(Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ + lblServerDbName.setText(Strings.SERVER_DB_NAME); txtServerDbName = new Text(container, SWT.BORDER); - txtServerDbName.setToolTipText( - Messages.getString("InfobaseDialog.ServerDBName")); //$NON-NLS-1$ txtServerDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblServerDbType = new Label(container, SWT.NONE); lblServerDbType.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerDbType.setText(Messages.getString("InfobaseDialog.DBMSType")); //$NON-NLS-1$ + lblServerDbType.setText(Strings.DBMS_TYPE); comboServerDbType = new Combo(container, SWT.READ_ONLY); comboServerDbType.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - comboServerDbType.add(Messages.getString("InfobaseDialog.MSSQLServer")); //$NON-NLS-1$ - comboServerDbType.add(Messages.getString("InfobaseDialog.PostgreSQL")); //$NON-NLS-1$ - comboServerDbType.add(Messages.getString("InfobaseDialog.IBMDB2")); //$NON-NLS-1$ - comboServerDbType.add(Messages.getString("InfobaseDialog.OracleDatabase")); //$NON-NLS-1$ + comboServerDbType.add(DBMS_TYPE_MSSQLSERVER); + comboServerDbType.add(DBMS_TYPE_POSTGRESQL); + comboServerDbType.add(DBMS_TYPE_IBMDB2); + comboServerDbType.add(DBMS_TYPE_ORACLEDATABASE); comboServerDbType.select(0); Label lblDatabaseDbName = new Label(container, SWT.NONE); lblDatabaseDbName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbName.setText(Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ + lblDatabaseDbName.setText(Strings.DATABASE_DB_NAME); txtDatabaseDbName = new Text(container, SWT.BORDER); - txtDatabaseDbName.setToolTipText( - Messages.getString("InfobaseDialog.DatabaseDBName")); //$NON-NLS-1$ txtDatabaseDbName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblDatabaseDbUser = new Label(container, SWT.NONE); lblDatabaseDbUser.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDatabaseDbUser.setText(Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ + lblDatabaseDbUser.setText(Strings.DATABASE_DB_USER); txtDatabaseDbUser = new Text(container, SWT.BORDER); - txtDatabaseDbUser.setToolTipText( - Messages.getString("InfobaseDialog.DatabaseDBUser")); //$NON-NLS-1$ txtDatabaseDbUser.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblDatabaseDbPassword = new Label(container, SWT.NONE); lblDatabaseDbPassword.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblDatabaseDbPassword.setAlignment(SWT.RIGHT); - lblDatabaseDbPassword.setText( - Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ + lblDatabaseDbPassword.setText(Strings.DATABASE_DB_PASSWORD); txtDatabaseDbPassword = new Text(container, SWT.BORDER | SWT.PASSWORD); - txtDatabaseDbPassword.setToolTipText( - Messages.getString("InfobaseDialog.DatabaseDBPassword")); //$NON-NLS-1$ txtDatabaseDbPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnAllowDistributeLicense = new Button(container, SWT.CHECK); btnAllowDistributeLicense.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnAllowDistributeLicense.setText( - Messages.getString("InfobaseDialog.AllowDistributeLicense")); //$NON-NLS-1$ + btnAllowDistributeLicense.setText(Strings.ALLOW_DISTRIBUTE_LICENSE); btnSessionsDenied = new Button(container, SWT.CHECK); btnSessionsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnSessionsDenied.setText(Messages.getString("InfobaseDialog.SessionsDenied")); //$NON-NLS-1$ + btnSessionsDenied.setText(Strings.SESSIONS_DENIED); Label lblDeniedFrom = new Label(container, SWT.NONE); lblDeniedFrom.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDeniedFrom.setText(Messages.getString("InfobaseDialog.DeniedFrom")); //$NON-NLS-1$ + lblDeniedFrom.setText(Strings.SESSIONS_DENIED_FROM); Composite compositeDeniedFrom = new Composite(container, SWT.NONE); compositeDeniedFrom.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); @@ -194,7 +199,7 @@ protected Control createDialogArea(Composite parent) { Label lblDeniedTo = new Label(container, SWT.NONE); lblDeniedTo.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDeniedTo.setText(Messages.getString("InfobaseDialog.DeniedTo")); //$NON-NLS-1$ + lblDeniedTo.setText(Strings.SESSIONS_DENIED_TO); Composite compositeDeniedTo = new Composite(container, SWT.NONE); compositeDeniedTo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); @@ -203,82 +208,66 @@ protected Control createDialogArea(Composite parent) { deniedToDate = new Text(compositeDeniedTo, SWT.BORDER); Label lblDeniedMessage = new Label(container, SWT.NONE); - lblDeniedMessage.setText(Messages.getString("InfobaseDialog.DeniedMessage")); //$NON-NLS-1$ + lblDeniedMessage.setText(Strings.SESSIONS_DENIED_MESSAGE); - txtDeniedMessage = new Text(container, SWT.BORDER); - txtDeniedMessage.setToolTipText( - Messages.getString("InfobaseDialog.DeniedMessage")); //$NON-NLS-1$ + txtDeniedMessage = new Text(container, SWT.BORDER | SWT.MULTI); GridData gdtxtDeniedMessage = new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1); gdtxtDeniedMessage.heightHint = 63; txtDeniedMessage.setLayoutData(gdtxtDeniedMessage); Label lblPermissionCode = new Label(container, SWT.NONE); lblPermissionCode.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPermissionCode.setText(Messages.getString("InfobaseDialog.PermissionCode")); //$NON-NLS-1$ + lblPermissionCode.setText(Strings.SESSIONS_PERMISSION_CODE); txtPermissionCode = new Text(container, SWT.BORDER); - txtPermissionCode.setToolTipText( - Messages.getString("InfobaseDialog.PermissionCode")); //$NON-NLS-1$ txtPermissionCode.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblDeniedParameter = new Label(container, SWT.NONE); lblDeniedParameter.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblDeniedParameter.setText(Messages.getString("InfobaseDialog.DeniedParameter")); //$NON-NLS-1$ + lblDeniedParameter.setText(Strings.SESSIONS_DENIED_PARAMETER); txtDeniedParameter = new Text(container, SWT.BORDER); - txtDeniedParameter.setToolTipText( - Messages.getString("InfobaseDialog.DeniedParameter")); //$NON-NLS-1$ txtDeniedParameter.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnSheduledJobsDenied = new Button(container, SWT.CHECK); btnSheduledJobsDenied.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnSheduledJobsDenied.setText( - Messages.getString("InfobaseDialog.SheduledJobsDenied")); //$NON-NLS-1$ + btnSheduledJobsDenied.setText(Strings.SHEDULED_JOBS_DENIED); Label lblExternalSessionManagerConnectionString = new Label(container, SWT.NONE); lblExternalSessionManagerConnectionString.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblExternalSessionManagerConnectionString.setText( - Messages.getString("InfobaseDialog.ExternalSessionManagement")); //$NON-NLS-1$ + lblExternalSessionManagerConnectionString.setText(Strings.EXTERNAL_SESSION_MANAGEMENT); txtExternalSessionManagerConnectionString = new Text(container, SWT.BORDER); - txtExternalSessionManagerConnectionString.setToolTipText( - Messages.getString("InfobaseDialog.ExternalSessionManagement")); //$NON-NLS-1$ txtExternalSessionManagerConnectionString.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); btnExternalSessionManagerRequired = new Button(container, SWT.CHECK); btnExternalSessionManagerRequired.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1)); - btnExternalSessionManagerRequired.setText( - Messages.getString("InfobaseDialog.RequiredUseOfExternalManagement")); //$NON-NLS-1$ + btnExternalSessionManagerRequired.setText(Strings.REQUIRED_USE_OF_EXTERNAL_MANAGEMENT); Label lblSecurityProfile = new Label(container, SWT.NONE); lblSecurityProfile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSecurityProfile.setText(Messages.getString("InfobaseDialog.SecurityProfile")); //$NON-NLS-1$ + lblSecurityProfile.setText(Strings.SECURITY_PROFILE); txtSecurityProfile = new Text(container, SWT.BORDER); - txtSecurityProfile.setToolTipText( - Messages.getString("InfobaseDialog.SecurityProfile")); //$NON-NLS-1$ txtSecurityProfile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblSafeModeSecurityProfile = new Label(container, SWT.NONE); lblSafeModeSecurityProfile.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSafeModeSecurityProfile.setText( - Messages.getString("InfobaseDialog.SafeModeSecurityProfile")); //$NON-NLS-1$ + lblSafeModeSecurityProfile.setText(Strings.SAFE_MODE_SECURITY_PROFILE); txtSafeModeSecurityProfile = new Text(container, SWT.BORDER); - txtSafeModeSecurityProfile.setToolTipText( - Messages.getString("InfobaseDialog.SafeModeSecurityProfile")); //$NON-NLS-1$ txtSafeModeSecurityProfile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - initInfobaseProperties(); + initProperties(); return container; } - private void initInfobaseProperties() { + private void initProperties() { if (infoBaseId != null) { IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infoBaseId); @@ -319,6 +308,8 @@ private void initInfobaseProperties() { // SecurityProfile properties txtSecurityProfile.setText(infoBaseInfo.getSecurityProfileName()); txtSafeModeSecurityProfile.setText(infoBaseInfo.getSafeModeSecurityProfileName()); + } else { + int a = 0; } } @@ -334,10 +325,10 @@ private boolean checkVariablesFromControls() { for (Text control : checksTextControls) { if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + control.setBackground(Helper.getPinkColor()); existsError = true; } else { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + control.setBackground(Helper.getWhiteColor()); } } @@ -347,10 +338,10 @@ private boolean checkVariablesFromControls() { for (Text control : checksDateControls) { if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getColor(255, 255, 255)); + control.setBackground(Helper.getWhiteColor()); } else { - if (convertStringToDate(control.getText()).equals(new Date(0))) { - control.setBackground(SWTResourceManager.getColor(255, 204, 204)); + if (convertStringToDate(control.getText()).equals(emptyDate)) { + control.setBackground(Helper.getPinkColor()); existsError = true; } } @@ -407,14 +398,12 @@ private boolean saveInfobaseProperties() { private Date convertStringToDate(String date) { - Date emptyDate = new Date(0); - if (date.isBlank()) { return emptyDate; } Date convertDate; - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + try { convertDate = dateFormat.parse(date); } catch (ParseException excp) { @@ -427,10 +416,7 @@ private Date convertStringToDate(String date) { private String convertDateToString(Date date) { - DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - Date emptyDate = new Date(0); - - return date.equals(emptyDate) ? "" : dateFormat.format(date); + return date.equals(emptyDate) ? EMPTY_STRING : dateFormat.format(date); } /** @@ -454,12 +440,7 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - Button buttonApply = - createButton( - parent, - IDialogConstants.PROCEED_ID, - Messages.getString("Dialogs.Apply"), //$NON-NLS-1$ - false); + Button buttonApply = createButton(parent, IDialogConstants.PROCEED_ID, Strings.APPLY, false); buttonApply.addSelectionListener( new SelectionAdapter() { @Override @@ -468,4 +449,40 @@ public void widgetSelected(SelectionEvent e) { } }); } + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + static final String INFOBASE_NAME = getString("InfobaseName"); + static final String INFOBASE_DESCRIPTION = getString("Description"); + static final String SECURITY_LEVEL = Messages.getString("Dialogs.SecurityLevel"); + static final String SECURITY_LEVEL_DISABLE = Messages.getString("Dialogs.Disable"); + static final String SECURITY_LEVEL_CONNECTIONONLY = + Messages.getString("Dialogs.ConnectionOnly"); + static final String SECURITY_LEVEL_CONSTANTLY = Messages.getString("Dialogs.Constantly"); + static final String SERVER_DB_NAME = getString("ServerDBName"); + static final String DBMS_TYPE = getString("DBMSType"); + static final String DATABASE_DB_NAME = getString("DatabaseDBName"); + static final String DATABASE_DB_USER = getString("DatabaseDBUser"); + static final String DATABASE_DB_PASSWORD = getString("DatabaseDBPassword"); + static final String ALLOW_DISTRIBUTE_LICENSE = getString("AllowDistributeLicense"); + static final String SESSIONS_DENIED = getString("SessionsDenied"); + static final String SESSIONS_DENIED_FROM = getString("SessionsDeniedFrom"); + static final String SESSIONS_DENIED_TO = getString("SessionsDeniedTo"); + static final String SESSIONS_DENIED_MESSAGE = getString("SessionsDeniedMessage"); + static final String SESSIONS_PERMISSION_CODE = getString("SessionsPermissionCode"); + static final String SESSIONS_DENIED_PARAMETER = getString("SessionsDeniedParameter"); + static final String SHEDULED_JOBS_DENIED = getString("SheduledJobsDenied"); + static final String EXTERNAL_SESSION_MANAGEMENT = getString("ExternalSessionManagement"); + static final String REQUIRED_USE_OF_EXTERNAL_MANAGEMENT = + getString("RequiredUseOfExternalManagement"); + static final String SECURITY_PROFILE = getString("SecurityProfile"); + static final String SAFE_MODE_SECURITY_PROFILE = getString("SafeModeSecurityProfile"); + + static final String APPLY = Messages.getString("Dialogs.Apply"); + + static String getString(String key) { + return Messages.getString("InfobaseDialog." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ServerDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ServerDialog.java new file mode 100644 index 0000000..3de6a0e --- /dev/null +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ServerDialog.java @@ -0,0 +1,650 @@ +package ru.yanygin.clusterAdminLibraryUI; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyAdapter; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Link; +import org.eclipse.swt.widgets.MessageBox; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.TabFolder; +import org.eclipse.swt.widgets.TabItem; +import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.TableColumn; +import org.eclipse.swt.widgets.TableItem; +import org.eclipse.swt.widgets.Text; +import ru.yanygin.clusterAdminLibrary.Helper; +import ru.yanygin.clusterAdminLibrary.Server; +import ru.yanygin.clusterAdminLibrary.Server.SaveCredentialsVariant; +import ru.yanygin.clusterAdminLibrary.UserPassPair; + +/** Диалог редактирования параметров сервера. */ +public class ServerDialog extends Dialog { + + private static final String UUID_DATA_KEY = "UUID"; //$NON-NLS-1$ + private static final String USER_PASS_DATA_KEY = "UserPass"; //$NON-NLS-1$ + private static final String AGENT_CREDENTIAL_PATTERN = "%s: %s %s: %s"; //$NON-NLS-1$ + + private final Image hiddenPassImage = Helper.getImage("hiddenPass.png"); //$NON-NLS-1$ + private final Image visiblePassImage = Helper.getImage("visiblePass.png"); //$NON-NLS-1$ + + private Server server; + private SaveCredentialsVariant saveCredentialsVariant; + private UserPassPair agentCredentialTemp; + private boolean rasOnSameHost; + private boolean showPasswordMode = false; + + // Controls + private Text txtDescription; + private Text txtRasHost; + private Text txtRasPort; + private Text txtAgentHost; + private Text txtAgentPort; + private Text txtLocalRasPort; + + private Combo comboV8Version; + + private Link txtAgentCredential; + + private Table tableClusterCredentials; + private Table tableInfobasesCredentials; + + private Button btnAutoconnect; + private Button radioUseRemoteRas; + private Button radioUseLocalRas; + private Button btnSaveCredentialsDisable; + private Button btnSaveCredentialsName; + private Button btnSaveCredentialsNamePass; + + /** + * Create the dialog. + * + * @param parentShell - parent shell + * @param server - server params + */ + public ServerDialog(Shell parentShell, Server server) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM); + + this.server = server; + this.agentCredentialTemp = server.getAgentCredential(); + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + + /** + * Create contents of the dialog. + * + * @param parent - parent composite + */ + @Override + protected Control createDialogArea(Composite parent) { + + Composite container = (Composite) super.createDialogArea(parent); + GridLayout gridLayout = (GridLayout) container.getLayout(); + gridLayout.marginHeight = 0; + gridLayout.marginWidth = 0; + + TabFolder tabFolder = new TabFolder(container, SWT.NONE); + + TabItem tabConnect = new TabItem(tabFolder, SWT.NONE); + tabConnect.setText(Strings.CONNECT_PARAMETERS); + + Composite connectContainer = new Composite(tabFolder, SWT.NONE); + tabConnect.setControl(connectContainer); + GridLayout glConnectContainer = new GridLayout(2, false); + connectContainer.setLayout(glConnectContainer); + + Composite composite = new Composite(connectContainer, SWT.NONE); + composite.setLayout(new GridLayout(2, false)); + composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); + + Label lblDescription = new Label(composite, SWT.NONE); + lblDescription.setText(Strings.SERVER_DESCRIPTION); + + txtDescription = new Text(composite, SWT.BORDER); + txtDescription.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); + + btnAutoconnect = new Button(connectContainer, SWT.CHECK); + GridData gdbtnAutoconnect = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdbtnAutoconnect.horizontalIndent = 5; + btnAutoconnect.setLayoutData(gdbtnAutoconnect); + btnAutoconnect.setText(Strings.AUTOCONNECT_AT_STARTUP); + new Label(connectContainer, SWT.NONE); + + radioUseRemoteRas = new Button(connectContainer, SWT.RADIO); + GridData gdradioUseRemoteRas = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdradioUseRemoteRas.horizontalIndent = 5; + radioUseRemoteRas.setLayoutData(gdradioUseRemoteRas); + radioUseRemoteRas.setSelection(true); + radioUseRemoteRas.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + setEnabledRasGroupParameters(); + } + }); + radioUseRemoteRas.setBounds(0, 0, 90, 16); + radioUseRemoteRas.setText(Strings.USE_REMOTE_RAS); + + radioUseLocalRas = new Button(connectContainer, SWT.RADIO); + GridData gdradioUseLocalRas = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdradioUseLocalRas.horizontalIndent = 5; + radioUseLocalRas.setLayoutData(gdradioUseLocalRas); + radioUseLocalRas.setBounds(0, 0, 90, 16); + radioUseLocalRas.setText(Strings.USE_LOCAL_RAS); + + Group grpRemoteRasParameters = new Group(connectContainer, SWT.NONE); + grpRemoteRasParameters.setText(Strings.REMOTE_RAS_PARAMETERS); + grpRemoteRasParameters.setLayout(new GridLayout(2, false)); + + Label lblRasHost = new Label(grpRemoteRasParameters, SWT.NONE); + lblRasHost.setText(Strings.HOST); + + Label lblRasPort = new Label(grpRemoteRasParameters, SWT.NONE); + lblRasPort.setSize(46, 15); + lblRasPort.setText(Strings.PORT); + + txtRasHost = new Text(grpRemoteRasParameters, SWT.BORDER); + txtRasHost.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + if (rasOnSameHost) { + txtAgentHost.setText(((Text) e.widget).getText()); + } + checkRasOnSameHost(); + } + }); + GridData gdtxtRasHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdtxtRasHost.widthHint = 200; + txtRasHost.setLayoutData(gdtxtRasHost); + + txtRasPort = new Text(grpRemoteRasParameters, SWT.BORDER); + GridData gdtxtRasPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtRasPort.widthHint = 50; + txtRasPort.setLayoutData(gdtxtRasPort); + + Group grpLocalRasParameters = new Group(connectContainer, SWT.NONE); + grpLocalRasParameters.setSize(417, 90); + grpLocalRasParameters.setText(Strings.LOCAL_RAS_PARAMETERS); + grpLocalRasParameters.setLayout(new GridLayout(2, false)); + + Label lblV8Version = new Label(grpLocalRasParameters, SWT.NONE); + lblV8Version.setSize(124, 15); + lblV8Version.setText(Strings.V8_VERSION); + + Label lblLocalRasPort = new Label(grpLocalRasParameters, SWT.NONE); + lblLocalRasPort.setSize(77, 15); + lblLocalRasPort.setText(Strings.PORT); + + comboV8Version = new Combo(grpLocalRasParameters, SWT.READ_ONLY); + GridData gdcomboV8Version = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdcomboV8Version.widthHint = 140; + comboV8Version.setLayoutData(gdcomboV8Version); + comboV8Version.setSize(389, 21); + + txtLocalRasPort = new Text(grpLocalRasParameters, SWT.BORDER); + GridData gdtxtLocalRasPort = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); + gdtxtLocalRasPort.widthHint = 50; + txtLocalRasPort.setLayoutData(gdtxtLocalRasPort); + + Group grpRagentParameters = new Group(connectContainer, SWT.NONE); + grpRagentParameters.setText(Strings.AGENT_PARAMETERS); + grpRagentParameters.setLayout(new GridLayout(2, false)); + + Label lblAgentHost = new Label(grpRagentParameters, SWT.NONE); + lblAgentHost.setText(Strings.HOST); + + Label lblAgentPort = new Label(grpRagentParameters, SWT.NONE); + lblAgentPort.setText(Strings.PORT); + + txtAgentHost = new Text(grpRagentParameters, SWT.BORDER); + txtAgentHost.addModifyListener( + new ModifyListener() { + @Override + public void modifyText(ModifyEvent e) { + checkRasOnSameHost(); + } + }); + GridData gdtxtAgentHost = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdtxtAgentHost.widthHint = 200; + txtAgentHost.setLayoutData(gdtxtAgentHost); + + txtAgentPort = new Text(grpRagentParameters, SWT.BORDER); + GridData gdtxtAgentPort = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); + gdtxtAgentPort.widthHint = 50; + txtAgentPort.setLayoutData(gdtxtAgentPort); + new Label(connectContainer, SWT.NONE); + + TabItem tabCredentials = new TabItem(tabFolder, SWT.NONE); + tabCredentials.setText(Strings.CREDENTIALS); + + Composite credentialsContainer = new Composite(tabFolder, SWT.NONE); + tabCredentials.setControl(credentialsContainer); + credentialsContainer.setLayout(new GridLayout(1, false)); + + Group grpSaveCredentialsVariant = new Group(credentialsContainer, SWT.NONE); + grpSaveCredentialsVariant.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + grpSaveCredentialsVariant.setText(Strings.SAVE_CREDENTIALS_VARIANT); + grpSaveCredentialsVariant.setLayout(new GridLayout(4, false)); + + btnSaveCredentialsDisable = new Button(grpSaveCredentialsVariant, SWT.RADIO); + btnSaveCredentialsDisable.setSize(549, 16); + btnSaveCredentialsDisable.setText(Strings.SAVE_CREDENTIALS_NONE); + + btnSaveCredentialsName = new Button(grpSaveCredentialsVariant, SWT.RADIO); + btnSaveCredentialsName.setSize(549, 16); + btnSaveCredentialsName.setText(Strings.SAVE_CREDENTIALS_NAME); + + btnSaveCredentialsNamePass = new Button(grpSaveCredentialsVariant, SWT.RADIO); + btnSaveCredentialsNamePass.setSize(549, 16); + btnSaveCredentialsNamePass.setText(Strings.SAVE_CREDENTIALS_NAMEPASS); + + Button btnShowPasswordMode = new Button(grpSaveCredentialsVariant, SWT.TOGGLE | SWT.CENTER); + btnShowPasswordMode.setToolTipText(Strings.SHOW_PASSWORD_MODE_TOOLTIP); + btnShowPasswordMode.setImage(hiddenPassImage); + btnShowPasswordMode.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + showPasswordMode = !showPasswordMode; + btnShowPasswordMode.setImage(showPasswordMode ? visiblePassImage : hiddenPassImage); + fillCredentials(); + } + }); + + Group grpCentralServerCredential = new Group(credentialsContainer, SWT.NONE); + grpCentralServerCredential.setLayoutData( + new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + grpCentralServerCredential.setText(Strings.CENTRAL_SERVER_ADMINISTRATOR); + grpCentralServerCredential.setLayout(null); + + txtAgentCredential = new Link(grpCentralServerCredential, SWT.NONE); + txtAgentCredential.setBounds(8, 20, 0, 15); + txtAgentCredential.addSelectionListener(agentCredentialClickListener); + + Group grpClustersCredentials = new Group(credentialsContainer, SWT.NONE); + grpClustersCredentials.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + grpClustersCredentials.setText(Strings.CLUSTERS_CREDENTIALS_GROUP); + grpClustersCredentials.setLayout(new GridLayout(1, false)); + + tableClusterCredentials = + new Table(grpClustersCredentials, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); + GridData gdTableClusterCredentials = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdTableClusterCredentials.heightHint = 60; + tableClusterCredentials.setLayoutData(gdTableClusterCredentials); + tableClusterCredentials.setHeaderVisible(true); + tableClusterCredentials.setLinesVisible(true); + tableClusterCredentials.addKeyListener(credentialsKeyListener); + tableClusterCredentials.addMouseListener(credentialsDoubleClickListener); + + TableColumn tblclmnClusterName = new TableColumn(tableClusterCredentials, SWT.NONE); + tblclmnClusterName.setWidth(180); + tblclmnClusterName.setText(Strings.CLUSTER_NAME); + + TableColumn tblclmnClusterId = new TableColumn(tableClusterCredentials, SWT.NONE); + tblclmnClusterId.setWidth(40); + tblclmnClusterId.setText(Strings.CLUSTER_ID); + + TableColumn tblclmnUsername = new TableColumn(tableClusterCredentials, SWT.NONE); + tblclmnUsername.setWidth(200); + tblclmnUsername.setText(Strings.USERNAME); + + TableColumn tblclmnPassword = new TableColumn(tableClusterCredentials, SWT.NONE); + tblclmnPassword.setWidth(100); + tblclmnPassword.setText(Strings.PASSWORD); + + Group grpInfobasesCredentials = new Group(credentialsContainer, SWT.NONE); + grpInfobasesCredentials.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); + grpInfobasesCredentials.setText(Strings.INFOBASES_CREDENTIALS_GROUP); + grpInfobasesCredentials.setLayout(new GridLayout(1, false)); + + tableInfobasesCredentials = + new Table(grpInfobasesCredentials, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); + GridData gdTableInfobasesCredentials = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); + gdTableInfobasesCredentials.heightHint = 100; + tableInfobasesCredentials.setLayoutData(gdTableInfobasesCredentials); + tableInfobasesCredentials.setHeaderVisible(true); + tableInfobasesCredentials.setLinesVisible(true); + tableInfobasesCredentials.addKeyListener(credentialsKeyListener); + tableInfobasesCredentials.addMouseListener(credentialsDoubleClickListener); + + TableColumn tblclmnUsername1 = new TableColumn(tableInfobasesCredentials, SWT.NONE); + tblclmnUsername1.setWidth(200); + tblclmnUsername1.setText(Strings.USERNAME); + + TableColumn tblclmnPassword1 = new TableColumn(tableInfobasesCredentials, SWT.NONE); + tblclmnPassword1.setWidth(100); + tblclmnPassword1.setText(Strings.PASSWORD); + + initProperties(); + checkRasOnSameHost(); + setEnabledRasGroupParameters(); + + // parent.pack(); + + return container; + } + + private void initProperties() { + if (server != null) { + txtDescription.setText(server.getDescription()); + + txtRasHost.setText(server.getRasHost()); + txtRasPort.setText(server.getRasPortAsString()); + + txtAgentHost.setText(server.getAgentHost()); + txtAgentPort.setText(server.getAgentPortAsString()); + + radioUseRemoteRas.setSelection(!server.getUseLocalRas()); + radioUseLocalRas.setSelection(server.getUseLocalRas()); + + comboV8Version.setItems(getInstalledV8Versions()); + comboV8Version.setText(server.getLocalRasV8version()); + + txtLocalRasPort.setText(server.getLocalRasPortAsString()); + + btnAutoconnect.setSelection(server.getAutoconnect()); + + saveCredentialsVariant = server.getSaveCredentialsVariant(); + btnSaveCredentialsDisable.setSelection( + saveCredentialsVariant.equals(SaveCredentialsVariant.DISABLE)); + btnSaveCredentialsName.setSelection( + saveCredentialsVariant.equals(SaveCredentialsVariant.NAME)); + btnSaveCredentialsNamePass.setSelection( + saveCredentialsVariant.equals(SaveCredentialsVariant.NAMEPASS)); + + fillCredentials(); + } + } + + private void fillCredentials() { + fillAgentCredential(); + + tableClusterCredentials.removeAll(); + server + .getAllClustersCredentials() + .forEach( + (clusterId, userPass) -> { + TableItem credentialItem = new TableItem(tableClusterCredentials, SWT.NONE); + + credentialItem.setText(getClusterCredentialItemText(clusterId, userPass)); + credentialItem.setData(UUID_DATA_KEY, clusterId); + credentialItem.setData(USER_PASS_DATA_KEY, userPass); + }); + + tableInfobasesCredentials.removeAll(); + server + .getInfobasesCredentials() + .forEach( + userPass -> { + TableItem credentialItem = new TableItem(tableInfobasesCredentials, SWT.NONE); + + credentialItem.setText(getInfobaseCredentialItemText(userPass)); + credentialItem.setData(USER_PASS_DATA_KEY, userPass); + }); + } + + private void fillAgentCredential() { + + txtAgentCredential.setText( + String.format( + AGENT_CREDENTIAL_PATTERN, + Strings.USERNAME, + morphToLink(agentCredentialTemp.getUsername()), + Strings.PASSWORD, + morphToLink(agentCredentialTemp.getPassword(showPasswordMode)))); + txtAgentCredential.pack(); + } + + private String morphToLink(String text) { + return "" + text + ""; + } + + private String[] getInstalledV8Versions() { + List installedV8Versions = new ArrayList<>(); + Helper.getInstalledV8Versions().forEach((desc, path) -> installedV8Versions.add(desc)); + installedV8Versions.sort(String.CASE_INSENSITIVE_ORDER); + return installedV8Versions.toArray(new String[0]); + } + + private String[] getClusterCredentialItemText(UUID clusterId, UserPassPair userPass) { + return new String[] { + userPass.getDescription(), + clusterId.toString(), + userPass.getUsername(), + userPass.getPassword(showPasswordMode) + }; + } + + private String[] getInfobaseCredentialItemText(UserPassPair userPass) { + return new String[] {userPass.getUsername(), userPass.getPassword(showPasswordMode)}; + } + + private void checkRasOnSameHost() { + rasOnSameHost = txtAgentHost.getText().equals(txtRasHost.getText()); + } + + private void setEnabledRasGroupParameters() { + txtRasHost.setEnabled(radioUseRemoteRas.getSelection()); + txtRasPort.setEnabled(radioUseRemoteRas.getSelection()); + comboV8Version.setEnabled(!radioUseRemoteRas.getSelection()); + txtLocalRasPort.setEnabled(!radioUseRemoteRas.getSelection()); + } + + private boolean saveNewServerProperties() { + try { + server.setDescription(txtDescription.getText()); + + server.setAgentHost(txtAgentHost.getText()); + server.setAgentPort(Integer.parseInt(txtAgentPort.getText())); + server.setRasHost(txtRasHost.getText()); + server.setRasPort(Integer.parseInt(txtRasPort.getText())); + server.setUseLocalRas(!radioUseRemoteRas.getSelection()); + server.setLocalRasPort(Integer.parseInt(txtLocalRasPort.getText())); + + server.setLocalRasV8version(comboV8Version.getText()); + server.setAutoconnect(btnAutoconnect.getSelection()); + + extractSaveCredentialsVariant(); + server.setSaveCredentialsVariant(saveCredentialsVariant); + + server.setAgentCredential(agentCredentialTemp); + server.setAllClustersCredentials(extractClustersCredentials()); + server.setAllInfobasesCredentials(extractInfobasesCredentials()); + + return true; + + } catch (Exception excp) { + var messageBox = new MessageBox(getParentShell()); + messageBox.setMessage(excp.getLocalizedMessage()); + messageBox.open(); + return false; + } + } + + private void extractSaveCredentialsVariant() { + + if (btnSaveCredentialsName.getSelection()) { + saveCredentialsVariant = SaveCredentialsVariant.NAME; + } else if (btnSaveCredentialsNamePass.getSelection()) { + saveCredentialsVariant = SaveCredentialsVariant.NAMEPASS; + } else { + saveCredentialsVariant = SaveCredentialsVariant.DISABLE; + } + } + + private Map extractClustersCredentials() { + + Map clustersCredentials = new HashMap<>(); + if (saveCredentialsVariant != SaveCredentialsVariant.DISABLE) { + TableItem[] credentials = tableClusterCredentials.getItems(); + for (TableItem credential : credentials) { + UUID clusterId = (UUID) credential.getData(UUID_DATA_KEY); + UserPassPair userPass = (UserPassPair) credential.getData(USER_PASS_DATA_KEY); + userPass.clear(saveCredentialsVariant); + clustersCredentials.put(clusterId, userPass); + } + } + return clustersCredentials; + } + + private List extractInfobasesCredentials() { + + List infobasesCredentials = new ArrayList<>(); + if (saveCredentialsVariant != SaveCredentialsVariant.DISABLE) { + TableItem[] credentials = tableInfobasesCredentials.getItems(); + for (TableItem credential : credentials) { + UserPassPair userPass = (UserPassPair) credential.getData(USER_PASS_DATA_KEY); + userPass.clear(saveCredentialsVariant); + infobasesCredentials.add(userPass); + } + } + return infobasesCredentials; + } + + /** + * Create contents of the button bar. + * + * @param parent - parent composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + Button button = + createButton(parent, IDialogConstants.FINISH_ID, IDialogConstants.OK_LABEL, true); + button.addSelectionListener( + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (saveNewServerProperties()) { + close(); + } + } + }); + createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); + } + + private SelectionAdapter agentCredentialClickListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + AuthenticateDialog authenticateDialog = + new AuthenticateDialog( + Display.getDefault().getActiveShell(), + agentCredentialTemp, + Strings.SET_NEW_USERPASS, + ""); + + if (authenticateDialog.open() == 0) { + agentCredentialTemp = authenticateDialog.getUserPass(); + fillAgentCredential(); + } + } + }; + + private KeyAdapter credentialsKeyListener = + new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.keyCode == SWT.DEL) { + TableItem[] credentials = ((Table) e.widget).getSelection(); + for (TableItem credential : credentials) { + credential.dispose(); + } + } + } + }; + + private MouseAdapter credentialsDoubleClickListener = + new MouseAdapter() { + @Override + public void mouseDoubleClick(MouseEvent e) { + TableItem[] credentials = ((Table) e.widget).getSelection(); + if (credentials.length == 0) { + return; + } + + TableItem credential = credentials[0]; + + UUID clusterId = (UUID) credential.getData(UUID_DATA_KEY); + UserPassPair userPass = (UserPassPair) credential.getData(USER_PASS_DATA_KEY); + + AuthenticateDialog authenticateDialog = + new AuthenticateDialog( + Display.getDefault().getActiveShell(), userPass, Strings.SET_NEW_USERPASS, ""); + + if (authenticateDialog.open() == 0) { + userPass = authenticateDialog.getUserPass(); + credential.setData(USER_PASS_DATA_KEY, userPass); + + if (clusterId == null) { + credential.setText(getInfobaseCredentialItemText(userPass)); + } else { + credential.setText(getClusterCredentialItemText(clusterId, userPass)); + } + } + } + }; + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + static final String CONNECT_PARAMETERS = getString("ConnectParameters"); + static final String SERVER_DESCRIPTION = getString("Description"); + static final String AUTOCONNECT_AT_STARTUP = getString("AutoconnectAtStartup"); + static final String USE_REMOTE_RAS = getString("UseRemoteRAS"); + static final String USE_LOCAL_RAS = getString("UseLocalRAS"); + static final String REMOTE_RAS_PARAMETERS = getString("RemoteRASParameters"); + static final String HOST = getString("Host"); + static final String PORT = getString("Port"); + static final String LOCAL_RAS_PARAMETERS = getString("LocalRASParameters"); + static final String V8_VERSION = getString("V8Version"); + static final String AGENT_PARAMETERS = getString("AgentParameters"); + static final String CREDENTIALS = getString("Credentials"); + static final String SAVE_CREDENTIALS_VARIANT = getString("SaveCredentialsVariant"); + static final String SAVE_CREDENTIALS_NONE = getString("SaveCredentialsNone"); + static final String SAVE_CREDENTIALS_NAME = getString("SaveCredentialsName"); + static final String SAVE_CREDENTIALS_NAMEPASS = getString("SaveCredentialsNamePass"); + static final String SHOW_PASSWORD_MODE_TOOLTIP = getString("ShowPasswordModeToolTipText"); + static final String CENTRAL_SERVER_ADMINISTRATOR = getString("CentralServerAdminstrator"); + static final String CLUSTERS_CREDENTIALS_GROUP = getString("ClustersCredentialsGroup"); + static final String CLUSTER_NAME = getString("ClusterName"); + static final String CLUSTER_ID = getString("ID"); + static final String INFOBASES_CREDENTIALS_GROUP = getString("InfobasesCredentialsGroup"); + static final String USERNAME = getString("Username"); //$NON-NLS-1$ // TODO дубль + static final String PASSWORD = getString("Password"); //$NON-NLS-1$ // TODO дубль + static final String SET_NEW_USERPASS = getString("SetNewUserPassword"); //$NON-NLS-1$ + + static String getString(String key) { + return Messages.getString("ServerDialog." + key); //$NON-NLS-1$ + } + } +} diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java index 7b10ce5..df31052 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SessionInfoDialog.java @@ -1,12 +1,9 @@ package ru.yanygin.clusterAdminLibraryUI; -import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; import com._1c.v8.ibis.admin.ISessionInfo; -import com._1c.v8.ibis.admin.IWorkingProcessInfo; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; -import java.util.UUID; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -21,16 +18,13 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import ru.yanygin.clusterAdminLibrary.Messages; -import ru.yanygin.clusterAdminLibrary.Server; +import ru.yanygin.clusterAdminLibrary.SessionInfoExtended; -/** The dialog box shows the session information. */ +/** Диалоговое окно с подробной информацией о сессии. */ public class SessionInfoDialog extends Dialog { - private UUID clusterId; - private UUID sessionId; - private ISessionInfo sessionInfo; + private SessionInfoExtended sessionExtInfo; - private Server server; private Text txtInfobaseName; private Text txtLastActiveAt; private Text txtClientIpAddress; @@ -38,7 +32,6 @@ public class SessionInfoDialog extends Dialog { private Text txtApplication; private Text txtStartedAt; private Text txtComputer; - private Text txtServer; private Text txtPort; private Text txtPid; @@ -50,25 +43,21 @@ public class SessionInfoDialog extends Dialog { * Create the dialog. * * @param parentShell - parent shell - * @param server - server parameters - * @param clusterId - cluster ID - * @param sessionId - session ID - * @param sessionInfo - session info + * @param sessionExtInfo - session extension info */ - public SessionInfoDialog( - Shell parentShell, Server server, UUID clusterId, UUID sessionId, ISessionInfo sessionInfo) { + public SessionInfoDialog(Shell parentShell, SessionInfoExtended sessionExtInfo) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.server = server; - this.clusterId = clusterId; - this.sessionId = sessionId; - this.sessionInfo = sessionInfo; + this.sessionExtInfo = sessionExtInfo; } + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + /** * Create contents of the dialog. * @@ -84,49 +73,49 @@ protected Control createDialogArea(Composite parent) { Label lblInfobaseName = new Label(container, SWT.NONE); lblInfobaseName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfobaseName.setText(Messages.getString("SessionInfo.Infobase")); //$NON-NLS-1$ + lblInfobaseName.setText(Strings.INFOBASE); txtInfobaseName = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtInfobaseName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lbSessionNumber = new Label(container, SWT.NONE); lbSessionNumber.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lbSessionNumber.setText(Messages.getString("SessionInfo.SessionN")); //$NON-NLS-1$ + lbSessionNumber.setText(Strings.SESSION_N); txtSessionNumber = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtSessionNumber.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblStartedAt = new Label(container, SWT.NONE); lblStartedAt.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblStartedAt.setText(Messages.getString("SessionInfo.StartedAt")); //$NON-NLS-1$ + lblStartedAt.setText(Strings.STARTED_AT); txtStartedAt = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtStartedAt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblLastActiveAt = new Label(container, SWT.NONE); lblLastActiveAt.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblLastActiveAt.setText(Messages.getString("SessionInfo.LastActiveAt")); //$NON-NLS-1$ + lblLastActiveAt.setText(Strings.LAST_ACTIVE_AT); txtLastActiveAt = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtLastActiveAt.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblComputer = new Label(container, SWT.NONE); lblComputer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblComputer.setText(Messages.getString("SessionInfo.Computer")); //$NON-NLS-1$ + lblComputer.setText(Strings.COMPUTER); txtComputer = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtComputer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblClientIpAddress = new Label(container, SWT.NONE); lblClientIpAddress.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblClientIpAddress.setText(Messages.getString("SessionInfo.ClientIPAddress")); //$NON-NLS-1$ + lblClientIpAddress.setText(Strings.CLIENT_IP_ADDRESS); txtClientIpAddress = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtClientIpAddress.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblUsername = new Label(container, SWT.NONE); lblUsername.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblUsername.setText(Messages.getString("SessionInfo.Username")); //$NON-NLS-1$ + lblUsername.setText(Strings.USERNAME); txtUsername = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); @@ -134,14 +123,14 @@ protected Control createDialogArea(Composite parent) { Label lblApplication = new Label(container, SWT.NONE); lblApplication.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblApplication.setAlignment(SWT.RIGHT); - lblApplication.setText(Messages.getString("SessionInfo.Application")); //$NON-NLS-1$ + lblApplication.setText(Strings.APPLICATION); txtApplication = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtApplication.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblServer = new Label(container, SWT.NONE); lblServer.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServer.setText(Messages.getString("SessionInfo.Server")); //$NON-NLS-1$ + lblServer.setText(Strings.SERVER); lblServer.setAlignment(SWT.RIGHT); txtServer = new Text(container, SWT.BORDER | SWT.READ_ONLY); @@ -149,7 +138,7 @@ protected Control createDialogArea(Composite parent) { Label lblPort = new Label(container, SWT.NONE); lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPort.setText(Messages.getString("SessionInfo.Port")); //$NON-NLS-1$ + lblPort.setText(Strings.PORT); lblPort.setAlignment(SWT.RIGHT); txtPort = new Text(container, SWT.BORDER | SWT.READ_ONLY); @@ -157,7 +146,7 @@ protected Control createDialogArea(Composite parent) { Label lblPid = new Label(container, SWT.NONE); lblPid.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPid.setText(Messages.getString("SessionInfo.PID")); //$NON-NLS-1$ + lblPid.setText(Strings.PID); lblPid.setAlignment(SWT.RIGHT); txtPid = new Text(container, SWT.BORDER | SWT.READ_ONLY); @@ -165,84 +154,45 @@ protected Control createDialogArea(Composite parent) { Label lblConnectionNumber = new Label(container, SWT.NONE); lblConnectionNumber.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblConnectionNumber.setText(Messages.getString("SessionInfo.ConnectionN")); //$NON-NLS-1$ + lblConnectionNumber.setText(Strings.CONNECTION_N); lblConnectionNumber.setAlignment(SWT.RIGHT); txtConnectionNumber = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtConnectionNumber.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Label lblLicense = new Label(container, SWT.NONE); - lblLicense.setText(Messages.getString("SessionInfo.License")); //$NON-NLS-1$ + lblLicense.setText(Strings.LICENSE); lblLicense.setAlignment(SWT.RIGHT); new Label(container, SWT.NONE); txtLicense = new Text(container, SWT.BORDER | SWT.READ_ONLY); txtLicense.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 2)); - initInfobaseProperties(); + initProperties(); return container; } - private void initInfobaseProperties() { - if (sessionInfo == null) { - sessionInfo = server.getSessionInfo(clusterId, sessionId); - } - - if (sessionInfo == null) { - return; - } - - UUID infobaseId = sessionInfo.getInfoBaseId(); - String infobaseName = server.getInfoBaseName(clusterId, infobaseId); - - UUID emptyUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); //$NON-NLS-1$ + private void initProperties() { + ISessionInfo sessionInfo = sessionExtInfo.getSessionInfo(); - // connection - var connectionNumber = ""; //$NON-NLS-1$ - if (!sessionInfo.getConnectionId().equals(emptyUuid)) { - IInfoBaseConnectionShort connectionInfoShort = - server.getConnectionInfoShort(clusterId, sessionInfo.getConnectionId()); - connectionNumber = String.valueOf(connectionInfoShort.getConnId()); - } - - // Working Process - var wpHostName = ""; //$NON-NLS-1$ - var wpMainPort = ""; //$NON-NLS-1$ - var wpPid = ""; //$NON-NLS-1$ - if (!sessionInfo.getWorkingProcessId().equals(emptyUuid)) { - IWorkingProcessInfo wpInfo = - server.getWorkingProcessInfo(clusterId, sessionInfo.getWorkingProcessId()); - wpHostName = wpInfo.getHostName(); - wpMainPort = Integer.toString(wpInfo.getMainPort()); - wpPid = wpInfo.getPid(); - } - - txtInfobaseName.setText(infobaseName); + txtInfobaseName.setText(sessionExtInfo.getInfobaseName()); txtSessionNumber.setText(Integer.toString(sessionInfo.getSessionId())); txtStartedAt.setText(dateToString(sessionInfo.getStartedAt())); txtLastActiveAt.setText(dateToString(sessionInfo.getLastActiveAt())); txtComputer.setText(sessionInfo.getHost()); - var clientIpAddress = - sessionInfo.getClientIPAddress() == null - ? "" //$NON-NLS-1$ - : sessionInfo.getClientIPAddress(); // 8.3.17+ - txtClientIpAddress.setText(clientIpAddress); + txtClientIpAddress.setText(sessionExtInfo.getClientIpAddress()); txtUsername.setText(sessionInfo.getUserName()); - txtApplication.setText(server.getApplicationName(sessionInfo.getAppId())); - - txtServer.setText(wpHostName); - txtPort.setText(wpMainPort); - txtPid.setText(wpPid); - txtConnectionNumber.setText(connectionNumber); - - var license = - sessionInfo.getLicenses().isEmpty() - ? "" //$NON-NLS-1$ - : sessionInfo.getLicenses().get(0).getFullPresentation(); - txtLicense.setText(license); + txtApplication.setText(sessionExtInfo.getApplicationName()); + + txtServer.setText(sessionExtInfo.getWorkingProcessHostName()); + txtPort.setText(sessionExtInfo.getWorkingProcessPort()); + txtPid.setText(sessionExtInfo.getWorkingProcessPid()); + txtConnectionNumber.setText(sessionExtInfo.getConnectionNumber()); + + txtLicense.setText(sessionExtInfo.getLicense()); } /** @@ -270,4 +220,27 @@ private String dateToString(Date date) { return date.equals(emptyDate) ? "" : dateFormat.format(date); //$NON-NLS-1$ } + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + + static final String INFOBASE = getString("Infobase"); + static final String SESSION_N = getString("SessionN"); + static final String STARTED_AT = getString("StartedAt"); + static final String LAST_ACTIVE_AT = getString("LastActiveAt"); + static final String COMPUTER = getString("Computer"); + static final String CLIENT_IP_ADDRESS = getString("ClientIPAddress"); + static final String USERNAME = getString("Username"); + static final String APPLICATION = getString("Application"); + static final String SERVER = getString("Server"); + static final String PORT = getString("Port"); + static final String PID = getString("PID"); + static final String CONNECTION_N = getString("ConnectionN"); + static final String LICENSE = getString("License"); + + static String getString(String key) { + return Messages.getString("SessionInfo." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java index d52c28b..1cfa7ed 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/SettingsDialog.java @@ -6,6 +6,7 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; @@ -15,13 +16,16 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import ru.yanygin.clusterAdminLibrary.ClusterProvider; +import ru.yanygin.clusterAdminLibrary.ColumnProperties.RowSortDirection; import ru.yanygin.clusterAdminLibrary.Config; -/** Dialog for edit server settings. */ +/** Диалог редактирования настроек сервера. */ public class SettingsDialog extends Dialog { private Config config; + + private Text txtHighlightDuration; + private Button btnShowWorkingServers; private Button btnShowWorkingProcesses; private Button btnExpandServers; @@ -36,13 +40,18 @@ public class SettingsDialog extends Dialog { private Button btnLocaleSystem; private Button btnLocaleEnglish; private Button btnLocaleRussian; - private Text txtHighlightDuration; private Button btnHighlightNewItems; private Button btnShadowSleepSessions; private Button btnReadClipboard; + private Button btnCheckUpdate; + private Button btnRowSortAsPrevious; + private Button btnRowSortAsc; + private Button btnRowSortDesc; + + private static final String LOCALE_RU = "ru-RU"; //$NON-NLS-1$ /** - * Create the dialog. + * Создание диалога настроек сервера. * * @param parentShell - parent shell */ @@ -50,12 +59,15 @@ public SettingsDialog(Shell parentShell) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - - this.config = ClusterProvider.getCommonConfig(); + this.config = Config.currentConfig; } + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + /** * Create contents of the dialog. * @@ -70,86 +82,83 @@ protected Control createDialogArea(Composite parent) { Group grpShowNodesIn = new Group(container, SWT.NONE); grpShowNodesIn.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpShowNodesIn.setText(Messages.getString("SettingsDialog.ShowNodesInTree")); //$NON-NLS-1$ + grpShowNodesIn.setText(Strings.SHOW_NODES_IN_TREE); grpShowNodesIn.setLayout(new GridLayout(1, false)); btnShowWorkingServers = new Button(grpShowNodesIn, SWT.CHECK); - btnShowWorkingServers.setText( - Messages.getString("SettingsDialog.ShowWorkingServers")); //$NON-NLS-1$ + btnShowWorkingServers.setText(Strings.SHOW_WORKING_SERVERS); btnShowWorkingProcesses = new Button(grpShowNodesIn, SWT.CHECK); - btnShowWorkingProcesses.setText( - Messages.getString("SettingsDialog.ShowWorkingProcesses")); //$NON-NLS-1$ + btnShowWorkingProcesses.setText(Strings.SHOW_WORKING_PROCESSES); Group grpExpandNodes = new Group(container, SWT.NONE); grpExpandNodes.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpExpandNodes.setText(Messages.getString("SettingsDialog.ExpandNodesInTree")); //$NON-NLS-1$ + grpExpandNodes.setText(Strings.EXPAND_NODES_IN_TREE); grpExpandNodes.setLayout(new GridLayout(1, false)); btnExpandServers = new Button(grpExpandNodes, SWT.CHECK); - btnExpandServers.setText(Messages.getString("SettingsDialog.ExpandServers")); //$NON-NLS-1$ + btnExpandServers.setText(Strings.EXPAND_SERVERS); btnExpandClusters = new Button(grpExpandNodes, SWT.CHECK); - btnExpandClusters.setText(Messages.getString("SettingsDialog.ExpandClusters")); //$NON-NLS-1$ + btnExpandClusters.setText(Strings.EXPAND_CLUSTERS); btnExpandInfobases = new Button(grpExpandNodes, SWT.CHECK); - btnExpandInfobases.setText(Messages.getString("SettingsDialog.ExpandInfobases")); //$NON-NLS-1$ + btnExpandInfobases.setText(Strings.EXPAND_INFOBASES); btnExpandWorkingServers = new Button(grpExpandNodes, SWT.CHECK); - btnExpandWorkingServers.setText( - Messages.getString("SettingsDialog.ExpandWorkingServers")); //$NON-NLS-1$ + btnExpandWorkingServers.setText(Strings.EXPAND_WORKING_SERVERS); btnExpandWorkingProcesses = new Button(grpExpandNodes, SWT.CHECK); - btnExpandWorkingProcesses.setText( - Messages.getString("SettingsDialog.ExpandWorkingProcesses")); //$NON-NLS-1$ + btnExpandWorkingProcesses.setText(Strings.EXPAND_WORKING_PROCESSES); Group grpShowInfo = new Group(container, SWT.NONE); - grpShowInfo.setText(Messages.getString("SettingsDialog.ShowInfo")); //$NON-NLS-1$ + grpShowInfo.setText(Strings.SHOW_INFO); grpShowInfo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); grpShowInfo.setLayout(new GridLayout(1, false)); btnShowServerVersion = new Button(grpShowInfo, SWT.CHECK); - btnShowServerVersion.setText( - Messages.getString("SettingsDialog.ShowServerVersion")); //$NON-NLS-1$ + btnShowServerVersion.setText(Strings.SHOW_SERVER_VERSION); btnShowServerDescription = new Button(grpShowInfo, SWT.CHECK); - btnShowServerDescription.setText( - Messages.getString("SettingsDialog.ShowServerDescription")); //$NON-NLS-1$ + btnShowServerDescription.setText(Strings.SHOW_SERVER_DESCRIPTION); btnShowInfobaseDescription = new Button(grpShowInfo, SWT.CHECK); - btnShowInfobaseDescription.setText( - Messages.getString("SettingsDialog.ShowInfobaseDescription")); //$NON-NLS-1$ + btnShowInfobaseDescription.setText(Strings.SHOW_INFOBASE_DESCRIPTION); btnShowLocalRasConnectInfo = new Button(grpShowInfo, SWT.CHECK); - btnShowLocalRasConnectInfo.setText( - Messages.getString("SettingsDialog.ShowLocalRASConnectInfo")); + btnShowLocalRasConnectInfo.setText(Strings.SHOW_LOCAL_RAS_CONNECTINFO); Group grpLocale = new Group(container, SWT.NONE); grpLocale.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); - grpLocale.setText(Messages.getString("SettingsDialog.Locale")); //$NON-NLS-1$ + grpLocale.setText(Strings.LOCALE); grpLocale.setLayout(new GridLayout(1, false)); btnLocaleSystem = new Button(grpLocale, SWT.RADIO); - btnLocaleSystem.setText(Messages.getString("SettingsDialog.System")); //$NON-NLS-1$ + btnLocaleSystem.setText(Strings.LOCALE_SYSTEM); btnLocaleEnglish = new Button(grpLocale, SWT.RADIO); - btnLocaleEnglish.setText(Messages.getString("SettingsDialog.English")); //$NON-NLS-1$ + btnLocaleEnglish.setText(Strings.LOCALE_ENGLISH); btnLocaleRussian = new Button(grpLocale, SWT.RADIO); - btnLocaleRussian.setText(Messages.getString("SettingsDialog.Russian")); //$NON-NLS-1$ + btnLocaleRussian.setText(Strings.LOCALE_RUSSIAN); Group grpHighlight = new Group(container, SWT.NONE); - grpHighlight.setText(Messages.getString("SettingsDialog.Highlight")); //$NON-NLS-1$ + grpHighlight.setText(Strings.HIGHLIGHT); grpHighlight.setLayout(new GridLayout(2, false)); btnHighlightNewItems = new Button(grpHighlight, SWT.CHECK); - btnHighlightNewItems.setText( - Messages.getString("SettingsDialog.HighlightNewItems")); //$NON-NLS-1$ - new Label(grpHighlight, SWT.NONE); + btnHighlightNewItems.setText(Strings.HIGHLIGHT_NEW_ITEMS); + + Label lblHighlightNewItemsColor = new Label(grpHighlight, SWT.BORDER); + lblHighlightNewItemsColor.setBackground(new Color(0, 200, 0)); + GridData gdLblHighlightNewItemsColor = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdLblHighlightNewItemsColor.heightHint = 14; + gdLblHighlightNewItemsColor.widthHint = 14; + lblHighlightNewItemsColor.setLayoutData(gdLblHighlightNewItemsColor); Label lblHighlightDuration = new Label(grpHighlight, SWT.NONE); lblHighlightDuration.setBounds(0, 0, 55, 15); - lblHighlightDuration.setText(Messages.getString("SettingsDialog.HighlightDuration")); + lblHighlightDuration.setText(Strings.HIGHLIGHT_DURATION); txtHighlightDuration = new Text(grpHighlight, SWT.BORDER); GridData gdtxtHighlightDuration = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); @@ -158,13 +167,47 @@ protected Control createDialogArea(Composite parent) { txtHighlightDuration.setBounds(0, 0, 76, 21); btnShadowSleepSessions = new Button(grpHighlight, SWT.CHECK); - btnShadowSleepSessions.setText( - Messages.getString("SettingsDialog.ShadowSleepSessions")); //$NON-NLS-1$ - new Label(grpHighlight, SWT.NONE); + btnShadowSleepSessions.setText(Strings.SHADOW_SLEEP_SESSIONS); + + Label lblShadowSleepSessionsColor = new Label(grpHighlight, SWT.BORDER); + lblShadowSleepSessionsColor.setBackground(new Color(160, 160, 160)); + GridData gdLblShadowSleepSessionsColor = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdLblShadowSleepSessionsColor.heightHint = 14; + gdLblShadowSleepSessionsColor.widthHint = 14; + lblShadowSleepSessionsColor.setLayoutData(gdLblShadowSleepSessionsColor); + + Label lblWatchSessions = new Label(grpHighlight, SWT.NONE); + lblWatchSessions.setText(Strings.WATCH_SESSIONS); + + Label lblWatchSessionsColor = new Label(grpHighlight, SWT.BORDER); + lblWatchSessionsColor.setBackground(new Color(0, 128, 255)); + GridData gdLblWatchSessionsColor = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1); + gdLblWatchSessionsColor.heightHint = 14; + gdLblWatchSessionsColor.widthHint = 14; + lblWatchSessionsColor.setLayoutData(gdLblWatchSessionsColor); + + Group grpRowSortDirection = new Group(container, SWT.NONE); + grpRowSortDirection.setText(Strings.ROW_SORT_DIRECTION); + grpRowSortDirection.setLayout(new GridLayout(1, false)); + + btnRowSortAsPrevious = new Button(grpRowSortDirection, SWT.RADIO); + btnRowSortAsPrevious.setText(Strings.ROW_SORT_DIRECTION_AS_PREVIOUS); + + btnRowSortAsc = new Button(grpRowSortDirection, SWT.RADIO); + btnRowSortAsc.setText(Strings.ROW_SORT_DIRECTION_ASCENDING); + + btnRowSortDesc = new Button(grpRowSortDirection, SWT.RADIO); + btnRowSortDesc.setText(Strings.ROW_SORT_DIRECTION_DESCENDING); btnReadClipboard = new Button(container, SWT.CHECK); btnReadClipboard.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); - btnReadClipboard.setText(Messages.getString("SettingsDialog.ReadClipboard")); + btnReadClipboard.setText(Strings.READ_CLIPBOARD); + + btnCheckUpdate = new Button(container, SWT.CHECK); + btnCheckUpdate.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1)); + btnCheckUpdate.setText(Strings.CHECK_UPDATE); + + new Label(container, SWT.NONE); initProperties(); @@ -189,15 +232,21 @@ private void initProperties() { btnHighlightNewItems.setSelection(config.isHighlightNewItems()); txtHighlightDuration.setText(Integer.toString(config.getHighlightNewItemsDuration())); - btnShadowSleepSessions.setSelection(config.isShadowSleepSessions()); + btnShadowSleepSessions.setSelection(config.isShadeSleepingSessions()); btnReadClipboard.setSelection(config.isReadClipboard()); + btnCheckUpdate.setSelection(config.checkingUpdate()); if (config.getLocale() == null) { btnLocaleSystem.setSelection(true); } else { btnLocaleEnglish.setSelection(config.getLocale().equals(Locale.ENGLISH.toLanguageTag())); - btnLocaleRussian.setSelection(config.getLocale().equals("ru-RU")); //$NON-NLS-1$ + btnLocaleRussian.setSelection(config.getLocale().equals(LOCALE_RU)); } + + final RowSortDirection rowSortDirection = config.getRowSortDirection(); + btnRowSortAsPrevious.setSelection(rowSortDirection == RowSortDirection.DISABLE); + btnRowSortAsc.setSelection(rowSortDirection == RowSortDirection.ASC); + btnRowSortDesc.setSelection(rowSortDirection == RowSortDirection.DESC); } private void saveProperties() { @@ -220,14 +269,26 @@ private void saveProperties() { config.setHighlightNewItemsDuration(Integer.parseInt(txtHighlightDuration.getText())); config.setShadowSleepSessions(btnShadowSleepSessions.getSelection()); config.setReadClipboard(btnReadClipboard.getSelection()); + config.setCheckingUpdate(btnCheckUpdate.getSelection()); if (btnLocaleSystem.getSelection()) { config.setLocale(null); } else if (btnLocaleEnglish.getSelection()) { config.setLocale(Locale.ENGLISH.toLanguageTag()); } else if (btnLocaleRussian.getSelection()) { - config.setLocale("ru-RU"); //$NON-NLS-1$ + config.setLocale(LOCALE_RU); } + + if (btnRowSortAsPrevious.getSelection()) { + config.setRowSortDirection(RowSortDirection.DISABLE); + } else if (btnRowSortAsc.getSelection()) { + config.setRowSortDirection(RowSortDirection.ASC); + } else if (btnRowSortDesc.getSelection()) { + config.setRowSortDirection(RowSortDirection.DESC); + } else { + config.setRowSortDirection(RowSortDirection.DISABLE); + } + } /** @@ -250,4 +311,49 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } + + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + + static final String SHOW_NODES_IN_TREE = getString("ShowNodesInTree"); + static final String SHOW_WORKING_SERVERS = getString("ShowWorkingServers"); + static final String SHOW_WORKING_PROCESSES = getString("ShowWorkingProcesses"); + + static final String EXPAND_NODES_IN_TREE = getString("ExpandNodesInTree"); + static final String EXPAND_SERVERS = getString("ExpandServers"); + static final String EXPAND_CLUSTERS = getString("ExpandClusters"); + static final String EXPAND_INFOBASES = getString("ExpandInfobases"); + static final String EXPAND_WORKING_SERVERS = getString("ExpandWorkingServers"); + static final String EXPAND_WORKING_PROCESSES = getString("ExpandWorkingProcesses"); + + static final String SHOW_INFO = getString("ShowInfo"); + static final String SHOW_SERVER_VERSION = getString("ShowServerVersion"); + static final String SHOW_SERVER_DESCRIPTION = getString("ShowServerDescription"); + static final String SHOW_INFOBASE_DESCRIPTION = getString("ShowInfobaseDescription"); + static final String SHOW_LOCAL_RAS_CONNECTINFO = getString("ShowLocalRASConnectInfo"); + + static final String LOCALE = getString("Locale"); + static final String LOCALE_SYSTEM = getString("LocaleSystem"); + static final String LOCALE_ENGLISH = getString("LocaleEnglish"); + static final String LOCALE_RUSSIAN = getString("LocaleRussian"); + + static final String HIGHLIGHT = getString("Highlight"); + static final String HIGHLIGHT_NEW_ITEMS = getString("HighlightNewItems"); + static final String HIGHLIGHT_DURATION = getString("HighlightDuration"); + static final String SHADOW_SLEEP_SESSIONS = getString("ShadowSleepSessions"); + static final String WATCH_SESSIONS = getString("WatchSessions"); + + static final String ROW_SORT_DIRECTION = getString("RowSortDirection"); + static final String ROW_SORT_DIRECTION_AS_PREVIOUS = getString("RowSortDirectionAsPrevious"); + static final String ROW_SORT_DIRECTION_ASCENDING = getString("RowSortDirectionAscending"); + static final String ROW_SORT_DIRECTION_DESCENDING = getString("RowSortDirectionDescending"); + + static final String READ_CLIPBOARD = getString("ReadClipboard"); + static final String CHECK_UPDATE = getString("CheckUpdate"); + + static String getString(String key) { + return Messages.getString("SettingsDialog." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java index e211051..1b192ee 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/ViewerArea.java @@ -1,15 +1,12 @@ package ru.yanygin.clusterAdminLibraryUI; import com._1c.v8.ibis.admin.IClusterInfo; -import com._1c.v8.ibis.admin.IInfoBaseConnectionShort; import com._1c.v8.ibis.admin.IInfoBaseInfo; -import com._1c.v8.ibis.admin.IInfoBaseInfoShort; -import com._1c.v8.ibis.admin.IObjectLockInfo; -import com._1c.v8.ibis.admin.ISessionInfo; import com._1c.v8.ibis.admin.IWorkingProcessInfo; import com._1c.v8.ibis.admin.IWorkingServerInfo; -import java.util.ArrayList; -import java.util.LinkedHashMap; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -17,17 +14,21 @@ import java.util.stream.Collectors; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; +import org.eclipse.swt.dnd.Clipboard; +import org.eclipse.swt.dnd.TextTransfer; +import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; @@ -46,35 +47,48 @@ import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.swt.widgets.TreeItem; +import org.eclipse.swt.widgets.Widget; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import ru.yanygin.clusterAdminLibrary.BaseInfoExtended; import ru.yanygin.clusterAdminLibrary.ClusterProvider; import ru.yanygin.clusterAdminLibrary.ColumnProperties; import ru.yanygin.clusterAdminLibrary.Config; import ru.yanygin.clusterAdminLibrary.ConnectionInfoExtended; -import ru.yanygin.clusterAdminLibrary.IInfoExtended; +import ru.yanygin.clusterAdminLibrary.Helper; +import ru.yanygin.clusterAdminLibrary.InfoBaseInfoShortExt; +import ru.yanygin.clusterAdminLibrary.InfoBaseInfoShortExt.InfobasesSortDirection; import ru.yanygin.clusterAdminLibrary.LockInfoExtended; import ru.yanygin.clusterAdminLibrary.Server; import ru.yanygin.clusterAdminLibrary.SessionInfoExtended; import ru.yanygin.clusterAdminLibrary.WorkingProcessInfoExtended; import ru.yanygin.clusterAdminLibrary.WorkingServerInfoExtended; -/** Area for viewing servers. */ +/** Основная рабочая область приложения. */ public class ViewerArea extends Composite { + static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ + + static final String SERVER_INFO = "ServerInfo"; //$NON-NLS-1$ + static final String ID_DATA_KEY = "ID_DATA"; //$NON-NLS-1$ + + public static final String EXTENDED_INFO = "ExtendedInfo"; //$NON-NLS-1$ + + static final Color deletedItemColor = new Color(150, 0, 0); + + // Image serverAdd48Icon; + // Image clusterAdd48Icon; + // Image infobaseAdd48Icon; + Image serverIcon; - Image serverIconUp; - Image serverIconDown; - Image serverIconConnecting; + Image serverConnectedIcon; + Image serverDisconnectIcon; + Image serverConnectingIcon; Image workingServerIcon; Image infobaseIcon; Image infobasesIcon; Image clusterIcon; - Image userIcon; - Image sleepUserIcon; - Image serviceIcon; - Image connectionIcon; - Image locksIcon; + Image workingProcessesIcon; Image workingProcessIcon; Image connectActionIcon; @@ -84,13 +98,17 @@ public class ViewerArea extends Composite { Image deleteIcon; Image lockUsersIcon; Image updateIcon; + Image favoritesIcon; + Image sortIcon; + Image moveUpIcon; + Image moveDownIcon; Tree serversTree; TreeItem currentTreeItem; + TreeItemType currentHighlightingType; + Object currentHighlightingData; + Menu serverMenu; - MenuItem menuItemConnectServer; - MenuItem menuItemDisconnectServer; - MenuItem menuItemShowConnectionError; Menu clusterMenu; Menu workingServerMenu; Menu infobaseNodeMenu; @@ -101,41 +119,26 @@ public class ViewerArea extends Composite { TabItem tabLocks; TabItem tabWorkingProcesses; TabItem tabWorkingServers; - TabItem currentTabitem; + TabItem currentTab; - Table tableSessions; - Table tableConnections; - Table tableLocks; - Table tableWorkingProcesses; - Table tableWorkingServers; - // Menu tableSessionsMenu; - - Map sessionColumnsMap = new LinkedHashMap<>(); - Map connectionColumnsMap = new LinkedHashMap<>(); - Map lockColumnsMap = new LinkedHashMap<>(); - Map wpColumnsMap = new LinkedHashMap<>(); - Map wsColumnsMap = new LinkedHashMap<>(); + ToolItem addToolbarItem; + ToolItem editToolbarItem; + ToolItem deleteToolbarItem; TreeColumn columnServer; - static final Logger LOGGER = LoggerFactory.getLogger("ClusterProvider"); //$NON-NLS-1$ - - static final Color standardColor = new Color(0, 0, 0); - static final Color newItemColor = new Color(0, 200, 0); - static final Color deletedItemColor = new Color(150, 0, 0); - static final Color shadowItemColor = new Color(160, 160, 160); - static final Color watchedSessionColor = new Color(0, 128, 255); - FontData systemFontData = getDisplay().getSystemFont().getFontData()[0]; Font fontNormal = new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.NORMAL); Font fontBold = new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.BOLD); + Font fontItalic = + new Font(getDisplay(), systemFontData.getName(), systemFontData.getHeight(), SWT.ITALIC); + TableItem lastSelectItem = null; int lastSelectColumn; - List watchedSessions = new ArrayList<>(); - enum TreeItemType { + public enum TreeItemType { SERVER, CLUSTER, INFOBASE_NODE, @@ -146,34 +149,52 @@ enum TreeItemType { WORKINGSERVER } - static final String SERVER_INFO = "ServerInfo"; //$NON-NLS-1$ - static final String CLUSTER_ID = "ClusterId"; //$NON-NLS-1$ - static final String INFOBASE_ID = "InfobaseId"; //$NON-NLS-1$ - static final String WORKINGPROCESS_ID = "WorkingProcessId"; //$NON-NLS-1$ - static final String WORKINGSERVER_ID = "WorkingServerId"; //$NON-NLS-1$ - static final String SESSION_ID = "SessionId"; //$NON-NLS-1$ - static final String CONNECTION_ID = "ConnectionId"; //$NON-NLS-1$ - ClusterProvider clusterProvider; + Config config; + + Map toolbarCreateListeners = new EnumMap<>(TreeItemType.class); + Map toolbarEditListeners = new EnumMap<>(TreeItemType.class); + Map toolbarDeleteListeners = new EnumMap<>(TreeItemType.class); + Map tableContextItemEdit = new HashMap<>(); + Map tableContextItemDelete = new HashMap<>(); + Map serversTreeContextMenus = new EnumMap<>(TreeItemType.class); + Map> linksTablesToExtendedClass = new HashMap<>(); // @Slf4j - /** Area for viewing servers. */ + /** + * Конструктор области приложения. + * + * @param parent - parent composite + * @param style - style + * @param menu - menu + * @param toolBar - toolBar + * @param clusterProvider - clusterProvider + * @param configPath - путь к файлу конфигурации + */ public ViewerArea( - Composite parent, int style, Menu menu, ToolBar toolBar, ClusterProvider clusterProvider) { + Composite parent, + int style, + Menu menu, + ToolBar toolBar, + ClusterProvider clusterProvider, + Config config) { super(parent, style); this.clusterProvider = clusterProvider; - this.clusterProvider.readConfig(); - - SashForm sashForm = new SashForm(this, SWT.NONE); + // this.clusterProvider.readConfig(); + // this.config = ClusterProvider.getCommonConfig(); + this.config = config; initIcon(); + BaseInfoExtended.init(); + + SashForm sashForm = new SashForm(this, SWT.NONE); // toolBar = new ToolBar(this, SWT.FLAT | SWT.RIGHT); // Для отладки // toolBar.setBounds(0, 0, 500, 23); // Для отладки - // initToolbar(parent, toolBar); - initMainMenu(sashForm, menu); + initToolbar(toolBar); + initMainMenu(menu); initServersTree(sashForm); @@ -184,273 +205,142 @@ public ViewerArea( @Override public void widgetSelected(SelectionEvent evt) { - currentTabitem = tabFolder.getSelection()[0]; - clickItemInServerTree(1); + currentTab = tabFolder.getSelection()[0]; + fillTabs(); } }); - initSessionTable(tabFolder); - initConnectionsTable(tabFolder); - initLocksTable(tabFolder); - initWorkingProcessesTable(tabFolder); - initWorkingServersTable(tabFolder); + tabSessions = initListTable(tabFolder, SessionInfoExtended.class, true); + tabConnections = initListTable(tabFolder, ConnectionInfoExtended.class, false); + tabLocks = initListTable(tabFolder, LockInfoExtended.class, false); + tabWorkingProcesses = initListTable(tabFolder, WorkingProcessInfoExtended.class, false); + tabWorkingServers = initListTable(tabFolder, WorkingServerInfoExtended.class, false); + //////////////////////////////////////////// + + initMaps(); + + initTableContextMenu(tabSessions, true, false, true, true); + initTableContextMenu(tabConnections, true, false, false, true); + initTableContextMenu(tabLocks, true, false, false, false); + initTableContextMenu(tabWorkingProcesses, true, false, false, false); + initTableContextMenu(tabWorkingServers, true, true, true, true); + ////////////////////////////////////////////// + + clearTabs(); + BaseInfoExtended.resetTabsTextCount(); + setEnableToolbarItems(); this.setLayout(new FillLayout(SWT.HORIZONTAL)); + // Пропорции областей + sashForm.setWeights(3, 10); + // Заполнение списка серверов - clusterProvider + config .getServers() .forEach( (serverKey, server) -> { addServerItemInServersTree(server); }); - // Пропорции областей - sashForm.setWeights(3, 10); - - connectToAllServers(false); - } - - @Override - public void addPaintListener(PaintListener listener) { // не работает - connectToAllServers(false); - - super.addPaintListener(listener); + runAutonnectAllServers(); } - // public void open() { - // connectToAllServers(); - // } - private void initIcon() { LOGGER.info("Start init icon"); //$NON-NLS-1$ - serverIcon = getImage("server_24.png"); //$NON-NLS-1$ - serverIconUp = getImage("server_up_24.png"); //$NON-NLS-1$ - serverIconDown = getImage("server_down_24.png"); //$NON-NLS-1$ - serverIconConnecting = getImage("server_connecting_24.png"); //$NON-NLS-1$ - workingServerIcon = getImage("working_server_24.png"); //$NON-NLS-1$ - infobaseIcon = getImage("infobase_24.png"); //$NON-NLS-1$ - infobasesIcon = getImage("infobases_24.png"); //$NON-NLS-1$ - clusterIcon = getImage("cluster_24.png"); //$NON-NLS-1$ - - userIcon = getImage("user.png"); //$NON-NLS-1$ - sleepUserIcon = getImage("sleepUser.png"); //$NON-NLS-1$ - serviceIcon = getImage("service.png"); //$NON-NLS-1$ - - connectionIcon = getImage("connection.png"); //$NON-NLS-1$ - locksIcon = getImage("lock_16.png"); //$NON-NLS-1$ - - workingProcessesIcon = getImage("wps.png"); //$NON-NLS-1$ - workingProcessIcon = getImage("wp.png"); //$NON-NLS-1$ - - connectActionIcon = getImage("connect_action_24.png"); //$NON-NLS-1$ - disconnectActionIcon = getImage("disconnect_action_24.png"); //$NON-NLS-1$ - - editIcon = getImage("edit_16.png"); //$NON-NLS-1$ - addIcon = getImage("add_16.png"); //$NON-NLS-1$ - deleteIcon = getImage("delete_16.png"); //$NON-NLS-1$ - lockUsersIcon = getImage("lock_users_16.png"); //$NON-NLS-1$ - updateIcon = getImage("update.png"); //$NON-NLS-1$ + // serverAdd48Icon = Helper.getImage("server_add_48.png"); //$NON-NLS-1$ + // clusterAdd48Icon = Helper.getImage("cluster_add_48.png"); //$NON-NLS-1$ + // infobaseAdd48Icon = Helper.getImage("infobase_add_48.png"); //$NON-NLS-1$ + + serverIcon = Helper.getImage("server_24.png"); //$NON-NLS-1$ + serverConnectedIcon = Helper.getImage("server_connected_24.png"); //$NON-NLS-1$ + serverDisconnectIcon = Helper.getImage("server_disconnect_24.png"); //$NON-NLS-1$ + serverConnectingIcon = Helper.getImage("server_connecting_24.png"); //$NON-NLS-1$ + + workingServerIcon = Helper.getImage("working_server_24.png"); //$NON-NLS-1$ + // infobaseIcon = Helper.getImage("infobase_24.png"); //$NON-NLS-1$ + infobasesIcon = Helper.getImage("infobases_24.png"); //$NON-NLS-1$ + clusterIcon = Helper.getImage("cluster_24.png"); //$NON-NLS-1$ + + workingProcessesIcon = Helper.getImage("wps.png"); //$NON-NLS-1$ + workingProcessIcon = Helper.getImage("wp.png"); //$NON-NLS-1$ + + connectActionIcon = Helper.getImage("connect_action_24.png"); //$NON-NLS-1$ + disconnectActionIcon = Helper.getImage("disconnect_action_24.png"); //$NON-NLS-1$ + + editIcon = Helper.getImage("edit_16.png"); //$NON-NLS-1$ + addIcon = Helper.getImage("add_16.png"); //$NON-NLS-1$ + deleteIcon = Helper.getImage("delete_16.png"); //$NON-NLS-1$ + lockUsersIcon = Helper.getImage("lock_users_16.png"); //$NON-NLS-1$ + updateIcon = Helper.getImage("update.png"); //$NON-NLS-1$ + favoritesIcon = Helper.getImage("favorites.png"); //$NON-NLS-1$ + sortIcon = Helper.getImage("sort.png"); //$NON-NLS-1$ + moveUpIcon = Helper.getImage("move_up.png"); //$NON-NLS-1$ + moveDownIcon = Helper.getImage("move_down.png"); //$NON-NLS-1$ LOGGER.info("Icon init succesfully"); //$NON-NLS-1$ } - private void initToolbar(Composite parent, ToolBar toolBar) { + private void initToolbar(ToolBar toolBar) { // ToolBar toolBar = applicationWindow.getToolBarManager().createControl(parent); - // final Cursor handCursor = new Cursor(Display.getCurrent(), SWT.CURSOR_HAND); - // toolBar.setCursor(handCursor); - // // Cursor needs to be explicitly disposed - // toolBar.addDisposeListener(new DisposeListener() { - // public void widgetDisposed(DisposeEvent e) { - // if (handCursor.isDisposed() == false) { - // handCursor.dispose(); - // } - // } - // }); - - ToolItem toolBarItemFindNewServers = new ToolItem(toolBar, SWT.NONE); - toolBarItemFindNewServers.setText( - Messages.getString("ViewerArea.FindNewServers")); //$NON-NLS-1$ - toolBarItemFindNewServers.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - List newServers = clusterProvider.findNewServers(); - if (!newServers.isEmpty()) { - fillServersList(); - } - } - }); + // addItemInToolbar(toolBar, Strings.MENU_FIND_SERVERS, serverIcon, findNewServersListener) + // .setEnabled(false); - ToolItem toolBarItemConnectAllServers = new ToolItem(toolBar, SWT.NONE); - toolBarItemConnectAllServers.setText( - Messages.getString("ViewerArea.ConnectToAllServers")); //$NON-NLS-1$ - toolBarItemConnectAllServers.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - connectToAllServers(false); - } - }); + toolBar.setSize(-1, 48); + + addToolbarItem = + addItemInToolbar(toolBar, Strings.CONTEXT_MENU_CREATE, addIcon, toolbarListener); + editToolbarItem = + addItemInToolbar(toolBar, Strings.CONTEXT_MENU_EDIT, editIcon, toolbarListener); + deleteToolbarItem = + addItemInToolbar(toolBar, Strings.CONTEXT_MENU_DELETE, deleteIcon, toolbarListener); + + new ToolItem(toolBar, SWT.SEPARATOR); + + addItemInToolbar(toolBar, Strings.CONTEXT_MENU_UPDATE, updateIcon, updateTablesListener); } - private void initMainMenu(Composite parent, Menu mainMenu) { + private void initMainMenu(Menu mainMenu) { if (mainMenu == null) { return; } - Menu mainMenuServersParent = new Menu(mainMenu); - MenuItem mainMenuServers = new MenuItem(mainMenu, SWT.CASCADE); - mainMenuServers.setText(Messages.getString("ViewerArea.Servers")); //$NON-NLS-1$ - mainMenuServers.setMenu(mainMenuServersParent); - - MenuItem toolBarItemFindNewServers = new MenuItem(mainMenuServersParent, SWT.NONE); - toolBarItemFindNewServers.setText( - Messages.getString("ViewerArea.FindNewServers")); //$NON-NLS-1$ - toolBarItemFindNewServers.setEnabled(false); - toolBarItemFindNewServers.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - List newServers = clusterProvider.findNewServers(); - if (!newServers.isEmpty()) { - fillServersList(); - } - } - }); - - MenuItem toolBarItemConnectAllServers = new MenuItem(mainMenuServersParent, SWT.NONE); - toolBarItemConnectAllServers.setText( - Messages.getString("ViewerArea.ConnectToAllServers")); //$NON-NLS-1$ - toolBarItemConnectAllServers.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - connectToAllServers(true); - } - }); - MenuItem toolBarItemDisonnectAllServers = new MenuItem(mainMenuServersParent, SWT.NONE); - toolBarItemDisonnectAllServers.setText( - Messages.getString("ViewerArea.DisonnectFromAllServers")); //$NON-NLS-1$ - toolBarItemDisonnectAllServers.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - diconnectFromAllServers(); - } - }); - - Menu mainMenuServiceParent = new Menu(mainMenu); - MenuItem mainMenuService = new MenuItem(mainMenu, SWT.CASCADE); - mainMenuService.setText(Messages.getString("ViewerArea.Service")); //$NON-NLS-1$ - mainMenuService.setMenu(mainMenuServiceParent); - - MenuItem toolBarItemOpenSettings = new MenuItem(mainMenuServiceParent, SWT.NONE); - toolBarItemOpenSettings.setText(Messages.getString("ViewerArea.OpenSettings")); //$NON-NLS-1$ - toolBarItemOpenSettings.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - - SettingsDialog settingsDialog; - try { - settingsDialog = new SettingsDialog(getParent().getDisplay().getActiveShell()); - } catch (Exception excp) { - LOGGER.error("Error init SettingsDialog", excp); //$NON-NLS-1$ - return; - } - int dialogResult = settingsDialog.open(); - if (dialogResult == 0) { - clusterProvider.saveConfig(); - for (TreeItem item : serversTree.getItems()) { - updateClustersInTree(item); - } - } - } - }); - - MenuItem toolBarItemOpenAbout = new MenuItem(mainMenuServiceParent, SWT.NONE); - toolBarItemOpenAbout.setText(Messages.getString("ViewerArea.About")); //$NON-NLS-1$ - toolBarItemOpenAbout.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { + Menu serversGroup = addItemGroupInMenu(mainMenu, Strings.MENU_SERVERS, null); + addItemInMenu(serversGroup, Strings.MENU_FIND_SERVERS, null, findNewServersListener) + .setEnabled(false); + addItemInMenu(serversGroup, Strings.MENU_CONNECT_ALL_SERVERS, null, connectAllServersListener); + addItemInMenu( + serversGroup, Strings.MENU_DISCONNECT_ALL_SERVERS, null, disconnectAllServersListener); - AboutDialog aboutDialog; - try { - aboutDialog = new AboutDialog(getParent().getDisplay().getActiveShell()); - } catch (Exception excp) { - LOGGER.error("Error init AboutDialog", excp); //$NON-NLS-1$ - return; - } - aboutDialog.open(); - } - }); + Menu serviceGroup = addItemGroupInMenu(mainMenu, Strings.MENU_SERVICE, null); + addItemInMenu(serviceGroup, Strings.MENU_OPEN_SETTINGS, null, openSettingsListener); + addItemInMenu(serviceGroup, Strings.MENU_ABOUT, null, showAboutDialogListener); } private void initServersTree(SashForm sashForm) { serversTree = new Tree(sashForm, SWT.BORDER | SWT.FULL_SELECTION); serversTree.setHeaderVisible(true); - serversTree.setSortDirection(SWT.UP); - serversTree.addMouseListener( - new MouseAdapter() { + serversTree.addMouseListener(treeItemMouseClickListener); + serversTree.addListener( + SWT.MeasureItem, + new Listener() { @Override - public void mouseDown(MouseEvent e) { - clickItemInServerTree(e.button); + public void handleEvent(Event event) { + // отключение разворачивания дерева при даблклике } }); initServersTreeContextMenu(); columnServer = new TreeColumn(serversTree, SWT.LEFT); - columnServer.setText(Messages.getString("ViewerArea.Server")); //$NON-NLS-1$ + columnServer.setText(Strings.COLUMN_SERVER); columnServer.setWidth(350); - ///////////////////////// - // сортировка не работает - // columnServer.addListener(SWT.Selection, sortListener); - // columnServer.addSelectionListener( - // new SelectionAdapter() { - // @Override - // public void widgetSelected(SelectionEvent e) { - // serversTree.setSortDirection( - // serversTree.getSortDirection() == SWT.UP ? SWT.DOWN : SWT.UP); - // serversTree.setSortColumn(columnServer); - // } - // }); - // - // Listener sortListener = - // new Listener() { - // public void handleEvent(Event e) { - // TreeItem[] items = serversTree.getItems(); - // Collator collator = Collator.getInstance(Locale.getDefault()); - // TreeColumn column = (TreeColumn) e.widget; - // int index = column == columnServer ? 0 : 1; - // for (int i = 1; i < items.length; i++) { - // String value1 = items[i].getText(index); - // for (int j = 0; j < i; j++) { - // String value2 = items[j].getText(index); - // if (collator.compare(value1, value2) < 0) { - // String[] values = {items[i].getText(0), items[i].getText(1)}; - // items[i].dispose(); - // TreeItem item = new TreeItem(serversTree, SWT.NONE, j); - // item.setText(values); - // items = serversTree.getItems(); - // break; - // } - // } - // } - // serversTree.setSortColumn(column); - // } - // }; - // сортировка не работает - ///////////////////////// - } private void initServersTreeContextMenu() { @@ -458,39 +348,6 @@ private void initServersTreeContextMenu() { // Server Menu serverMenu = new Menu(serversTree); - // установка активности элементов контекстного меню - serverMenu.addListener( - SWT.Show, - new Listener() { - @Override - public void handleEvent(Event event) { - - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } - - TreeItem serverItem = item[0]; - Server server = getCurrentServerConfig(serverItem); - boolean serverIsConnected = server.isConnected(); - boolean serverIsErrorConnected = !server.getConnectionError().isBlank(); - - MenuItem[] menuItems = serverMenu.getItems(); - - for (MenuItem menuItem : menuItems) { - if (menuItem == menuItemConnectServer) { //TODO menuItem.equals(menuItemConnectServer) - menuItem.setEnabled(!serverIsConnected); - } - if (menuItem == menuItemDisconnectServer) { - menuItem.setEnabled(serverIsConnected); - } - if (menuItem == menuItemShowConnectionError) { - menuItem.setEnabled(serverIsErrorConnected); - } - } - } - }); - initServerMenu(); initClusterMenu(); initWorkingServerMenu(); @@ -503,1890 +360,2041 @@ public void handleEvent(Event event) { private void initServerMenu() { - menuItemConnectServer = new MenuItem(serverMenu, SWT.NONE); - menuItemConnectServer.setText(Messages.getString("ViewerArea.ConnectToServer")); //$NON-NLS-1$ - menuItemConnectServer.setImage(connectActionIcon); + // установка активности элементов контекстного меню + serverMenu.addListener(SWT.Show, setActiveConnectActionListener); + + MenuItem menuItemConnectServer = + addItemInMenu( + serverMenu, + Strings.CONTEXT_MENU_CONNECT_TO_SERVER, + connectActionIcon, + connectToServerListener); menuItemConnectServer.setEnabled(false); - menuItemConnectServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { + menuItemConnectServer.setData("connectItem", true); + + MenuItem menuItemDisconnectServer = + addItemInMenu( + serverMenu, + Strings.CONTEXT_MENU_DISCONNECT_OF_SERVER, + disconnectActionIcon, + disconnectFromServerListener); + menuItemDisconnectServer.setEnabled(false); + menuItemDisconnectServer.setData("disconnectItem", true); + + MenuItem menuItemShowConnectionError = + addItemInMenu( + serverMenu, + Strings.CONTEXT_MENU_SHOW_CONNECTION_ERROR, + null, + showServerConnectionErrorListener); + menuItemShowConnectionError.setEnabled(false); + menuItemShowConnectionError.setData("connectionErrorItem", true); - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + addMenuSeparator(serverMenu); - connectServerItem(item[0], false); - } - }); + addItemInMenu(serverMenu, Strings.CONTEXT_MENU_ADD_SERVER, addIcon, addServerListener); + addItemInMenu(serverMenu, Strings.CONTEXT_MENU_EDIT_SERVER, editIcon, editServerListener); + addItemInMenu(serverMenu, Strings.CONTEXT_MENU_UPDATE, updateIcon, updateServerListener); - menuItemDisconnectServer = new MenuItem(serverMenu, SWT.NONE); - menuItemDisconnectServer.setText( - Messages.getString("ViewerArea.DisconnectOfServer")); //$NON-NLS-1$ - menuItemDisconnectServer.setImage(disconnectActionIcon); - menuItemDisconnectServer.setEnabled(false); - menuItemDisconnectServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { + addMenuSeparator(serverMenu); - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + addItemInMenu(serverMenu, Strings.CONTEXT_MENU_MOVE_UP, moveUpIcon, serversMoveUpListener); + addItemInMenu( + serverMenu, Strings.CONTEXT_MENU_MOVE_DOWN, moveDownIcon, serversMoveDownListener); + addItemInMenu(serverMenu, Strings.CONTEXT_MENU_ORGANIZE_SERVERS, sortIcon, serversSortListener); - disconnectServerItem(item[0]); - } - }); + addMenuSeparator(serverMenu); - menuItemShowConnectionError = new MenuItem(serverMenu, SWT.NONE); - menuItemShowConnectionError.setText( - Messages.getString("ViewerArea.ShowConnectionError")); //$NON-NLS-1$ - menuItemShowConnectionError.setEnabled(false); - menuItemShowConnectionError.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { + addItemInMenu(serverMenu, Strings.CONTEXT_MENU_REMOVE_SERVER, deleteIcon, deleteServerListener); + } - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + private void initClusterMenu() { - var messageBox = new MessageBox(Display.getDefault().getActiveShell()); - messageBox.setMessage(getCurrentServerConfig(item[0]).getConnectionError()); - messageBox.open(); - } - }); + clusterMenu = new Menu(serversTree); - addMenuSeparator(serverMenu); + addItemInMenu(clusterMenu, Strings.CONTEXT_MENU_CREATE_CLUSTER, addIcon, createClusterListener); + addItemInMenu(clusterMenu, Strings.CONTEXT_MENU_EDIT_CLUSTER, editIcon, editClusterListener); + addItemInMenu(clusterMenu, Strings.CONTEXT_MENU_UPDATE, updateIcon, updateClusterListener); + addMenuSeparator(clusterMenu); + addItemInMenu( + clusterMenu, Strings.CONTEXT_MENU_DELETE_CLUSTER, deleteIcon, deleteClusterListener); + } - MenuItem menuItemAddNewServer = new MenuItem(serverMenu, SWT.NONE); - menuItemAddNewServer.setText(Messages.getString("ViewerArea.AddServer")); //$NON-NLS-1$ - menuItemAddNewServer.setImage(addIcon); - menuItemAddNewServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { + private void initWorkingServerMenu() { - Server newServer = clusterProvider.createNewServer(); - CreateEditServerDialog connectionDialog; - try { - connectionDialog = - new CreateEditServerDialog(getParent().getDisplay().getActiveShell(), newServer); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error("Error init CreateEditServerDialog for new server", excp); //$NON-NLS-1$ - return; - } + workingServerMenu = new Menu(serversTree); - int dialogResult = connectionDialog.open(); - if (dialogResult != 0) { - return; - } + addItemInMenu( + workingServerMenu, + Strings.CONTEXT_MENU_CREATE_WORKING_SERVER, + addIcon, + createWorkingServerListenerInTree); + + addItemInMenu( + workingServerMenu, + Strings.CONTEXT_MENU_EDIT_WORKING_SERVER, + editIcon, + editWorkingServerListenerInTree); + } - clusterProvider.addNewServer(newServer); - TreeItem newServerItem = addServerItemInServersTree(newServer); - updateClustersInTree(newServerItem); - } - }); + private void initInfobaseNodeMenu() { - MenuItem menuItemEditServer = new MenuItem(serverMenu, SWT.NONE); - menuItemEditServer.setText(Messages.getString("ViewerArea.EditServer")); //$NON-NLS-1$ - menuItemEditServer.setImage(editIcon); - menuItemEditServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { + infobaseNodeMenu = new Menu(serversTree); - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + addItemInMenu( + infobaseNodeMenu, Strings.CONTEXT_MENU_CREATE_INFOBASE, addIcon, createInfobaseListener); + + addItemInMenu( + infobaseNodeMenu, + Strings.CONTEXT_MENU_UPDATE_INFOBASES, + updateIcon, + updateInfobasesListener); + + // группа вложенного меню + Menu subMenuSortInfobases = + addItemGroupInMenu(infobaseNodeMenu, Strings.CONTEXT_MENU_ORDER_INFOBASES_BY, sortIcon); + + InfobasesSortDirection infobasesSortDirection = config.getInfobasesSortDirection(); + + addRadioItemInMenu( + subMenuSortInfobases, + Strings.CONTEXT_MENU_ORDER_INFOBASES_BYDEFAULT, + sortInfobasesListener, + InfobasesSortDirection.DISABLE, + infobasesSortDirection.equals(InfobasesSortDirection.DISABLE)); + + addRadioItemInMenu( + subMenuSortInfobases, + Strings.CONTEXT_MENU_ORDER_INFOBASES_BYNAME, + sortInfobasesListener, + InfobasesSortDirection.BY_NAME, + infobasesSortDirection.equals(InfobasesSortDirection.BY_NAME)); + + addRadioItemInMenu( + subMenuSortInfobases, + Strings.CONTEXT_MENU_ORDER_INFOBASES_BYFAFORITES_ANDNAME, + sortInfobasesListener, + InfobasesSortDirection.BY_FAVORITES_AND_NAME, + infobasesSortDirection.equals(InfobasesSortDirection.BY_FAVORITES_AND_NAME)); + } - TreeItem serverItem = item[0]; - Server server = getCurrentServerConfig(serverItem); - CreateEditServerDialog connectionDialog; - try { - connectionDialog = - new CreateEditServerDialog(getParent().getDisplay().getActiveShell(), server); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error( - "Error init CreateEditServerDialog for server {}", //$NON-NLS-1$ - server.getTreeDescription(), - excp); - return; - } + private void initInfobaseMenu() { - int dialogResult = connectionDialog.open(); - if (dialogResult == 0) { - // перерисовать в дереве - serverItem.setText(new String[] {server.getTreeDescription()}); - clusterProvider.saveConfig(); - updateClustersInTree(serverItem); - } - } - }); + infobaseMenu = new Menu(serversTree); + infobaseMenu.addListener(SWT.Show, setActiveInfobaseFavoritesActionListener); - MenuItem menuItemUpdateServer = new MenuItem(serverMenu, SWT.NONE); - menuItemUpdateServer.setText(Messages.getString("ViewerArea.Update")); //$NON-NLS-1$ - menuItemUpdateServer.setImage(updateIcon); - menuItemUpdateServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + addItemInMenu( + infobaseMenu, Strings.CONTEXT_MENU_COPY_INFOBASE, addIcon, createInfobaseListener); - updateClustersInTree(item[0]); - } - }); + addItemInMenu(infobaseMenu, Strings.CONTEXT_MENU_EDIT_INFOBASE, editIcon, editInfobaseListener); - addMenuSeparator(serverMenu); + addItemInMenu( + infobaseMenu, Strings.CONTEXT_MENU_DELETE_INFOBASE, deleteIcon, deleteInfobaseListener); - MenuItem menuItemDeleteServer = new MenuItem(serverMenu, SWT.NONE); - menuItemDeleteServer.setText(Messages.getString("ViewerArea.RemoveServer")); //$NON-NLS-1$ - menuItemDeleteServer.setImage(deleteIcon); - menuItemDeleteServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + addMenuSeparator(infobaseMenu); - TreeItem serverItem = item[0]; - Server server = getCurrentServerConfig(serverItem); - clusterProvider.removeServer(server); - disposeTreeItemWithChildren(serverItem); - } - }); - } + MenuItem favoritesItem = + addItemInMenu( + infobaseMenu, + Strings.CONTEXT_MENU_ADD_IN_FAVORITES, + favoritesIcon, + addInfobaseToFavoritesListener); + favoritesItem.setData("favoritesItem", true); - private void initClusterMenu() { - // Cluster Menu - clusterMenu = new Menu(serversTree); + Menu subMenuSessionManagement = + addItemGroupInMenu(infobaseMenu, Strings.CONTEXT_MENU_SESSION_MANAGE, lockUsersIcon); - MenuItem menuItemCreateCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemCreateCluster.setText(Messages.getString("ViewerArea.CreateCluster")); //$NON-NLS-1$ - menuItemCreateCluster.setImage(addIcon); - menuItemCreateCluster.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + addItemInMenu( + subMenuSessionManagement, Strings.CONTEXT_MENU_LOCK_SESSIONS_NOW, null, lockUsersListener); - Server server = getCurrentServerConfig(item[0]); + addItemInMenu( + subMenuSessionManagement, + Strings.CONTEXT_MENU_TERMINATE_ALL_SESSIONS, + null, + terminateAllSessionsListener); - CreateEditClusterDialog editClusterDialog; - try { - editClusterDialog = - new CreateEditClusterDialog( - getParent().getDisplay().getActiveShell(), server, null); - } catch (Exception excp) { - LOGGER.error( - "Error init CreateEditClusterDialog for new cluster", //$NON-NLS-1$ - excp); - return; - } + addItemInMenu( + subMenuSessionManagement, + Strings.CONTEXT_MENU_TERMINATE_USERS_SESSIONS, + null, + terminateUsersSessionsListener); + } - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - updateClustersInTree(item[0].getParentItem()); - } - } - }); + private TabItem initListTable( + TabFolder tabFolder, Class clazz, boolean checkable) { - MenuItem menuItemEditCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemEditCluster.setText(Messages.getString("ViewerArea.EditCluster")); //$NON-NLS-1$ - menuItemEditCluster.setImage(editIcon); - menuItemEditCluster.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + TabItem newTab = new TabItem(tabFolder, SWT.NONE); - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); + int style = + checkable + ? SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK + : SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI; - CreateEditClusterDialog editClusterDialog; - try { - editClusterDialog = - new CreateEditClusterDialog( - getParent().getDisplay().getActiveShell(), server, clusterId); - } catch (Exception excp) { - LOGGER.error( - "Error init CreateEditClusterDialog for cluster id {}", //$NON-NLS-1$ - clusterId, - excp); - return; - } + Table table = new Table(tabFolder, style); + newTab.setControl(table); + table.setHeaderVisible(true); + table.setLinesVisible(true); - int dialogResult = editClusterDialog.open(); - if (dialogResult == 0) { - updateClustersInTree(item[0]); - } - } - }); + table.addKeyListener(tableKeyPressedListener); + table.addMouseListener(tablesMouseClickListener); + if (checkable) { + table.addListener(SWT.Selection, switchWatchingListener); + } - MenuItem menuItemUpdateCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemUpdateCluster.setText(Messages.getString("ViewerArea.Update")); //$NON-NLS-1$ - menuItemUpdateCluster.setImage(updateIcon); - menuItemUpdateCluster.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + ColumnProperties columnProperties = getColumnProperties(clazz); - Server server = getCurrentServerConfig(item[0]); - fillChildrenItemsOfCluster(item[0], server); - } - }); + String[] columnNameList = columnProperties.getColumnsDescription(); + for (String columnName : columnNameList) { + addTableColumn(table, columnName, columnProperties); + } - addMenuSeparator(clusterMenu); + int[] columnOrder = columnProperties.getOrder(); + if (columnOrder != null && table.getColumnCount() == columnOrder.length) { + table.setColumnOrder(columnOrder); + } - MenuItem menuItemDeleteCluster = new MenuItem(clusterMenu, SWT.NONE); - menuItemDeleteCluster.setText(Messages.getString("ViewerArea.DeleteCluster")); //$NON-NLS-1$ - menuItemDeleteCluster.setImage(deleteIcon); - menuItemDeleteCluster.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + BaseInfoExtended.linkTabItem(clazz, newTab); + return newTab; + } - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); + private void initTableContextMenu( + TabItem tab, boolean updatable, boolean creatable, boolean editable, boolean killable) { + Table table = getTable(tab); + Menu tableMenu = new Menu(table); + table.setMenu(tableMenu); - var messageBox = - new MessageBox( - Display.getDefault().getActiveShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); - messageBox.setMessage( - Messages.getString("ViewerArea.DeleteClusterQuestion")); //$NON-NLS-1$ - int rc = messageBox.open(); + if (updatable) { + addItemInMenu(tableMenu, Strings.CONTEXT_MENU_UPDATE_F5, updateIcon, updateTablesListener); + } - if (rc == SWT.YES && server.unregCluster(clusterId)) { - item[0].dispose(); - } - } - }); - } + if (creatable) { + addItemInMenu( + tableMenu, + Strings.CONTEXT_MENU_CREATE_WORKING_SERVER, + addIcon, + createWorkingServerListener); + } - private void initWorkingServerMenu() { + if (editable) { + String title = tableContextItemEdit.get(tab); + addItemInMenu(tableMenu, title, editIcon, editItemInTablesListener); + } - workingServerMenu = new Menu(serversTree); + if (killable) { + String title = tableContextItemDelete.get(tab); + addItemInMenu(tableMenu, title, deleteIcon, deleteItemInTablesListener); + } + } - MenuItem menuItemCreateWorkingServer = new MenuItem(workingServerMenu, SWT.NONE); - menuItemCreateWorkingServer.setText( - Messages.getString("ViewerArea.CreateWorkingServer")); //$NON-NLS-1$ - menuItemCreateWorkingServer.setImage(addIcon); - menuItemCreateWorkingServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + private void initMaps() { + + // обработчики кнопки тулбара "Добавить" + toolbarCreateListeners.put(TreeItemType.SERVER, addServerListener); + toolbarCreateListeners.put(TreeItemType.CLUSTER, createClusterListener); + toolbarCreateListeners.put(TreeItemType.INFOBASE_NODE, createInfobaseListener); + toolbarCreateListeners.put(TreeItemType.INFOBASE, createInfobaseListener); + toolbarCreateListeners.put(TreeItemType.WORKINGSERVER_NODE, createWorkingServerListenerInTree); + toolbarCreateListeners.put(TreeItemType.WORKINGSERVER, createWorkingServerListenerInTree); + + // обработчики кнопки тулбара "Изменить" + toolbarEditListeners.put(TreeItemType.SERVER, editServerListener); + toolbarEditListeners.put(TreeItemType.CLUSTER, editClusterListener); + toolbarEditListeners.put(TreeItemType.INFOBASE, editInfobaseListener); + toolbarEditListeners.put(TreeItemType.WORKINGSERVER, editWorkingServerListenerInTree); + + // обработчики кнопки тулбара "Удалить" + toolbarDeleteListeners.put(TreeItemType.SERVER, deleteServerListener); + toolbarDeleteListeners.put(TreeItemType.CLUSTER, deleteClusterListener); + toolbarDeleteListeners.put(TreeItemType.INFOBASE, deleteInfobaseListener); + + // контекстные меню дерева серверов + serversTreeContextMenus.put(TreeItemType.SERVER, serverMenu); + serversTreeContextMenus.put(TreeItemType.CLUSTER, clusterMenu); + serversTreeContextMenus.put(TreeItemType.INFOBASE_NODE, infobaseNodeMenu); + serversTreeContextMenus.put(TreeItemType.INFOBASE, infobaseMenu); + serversTreeContextMenus.put(TreeItemType.WORKINGSERVER, workingServerMenu); + + // тексты пунктов контекстного меню списков + tableContextItemEdit.put(tabSessions, Strings.CONTEXT_MENU_VIEW_SESSION_F2); + tableContextItemEdit.put(tabWorkingServers, Strings.CONTEXT_MENU_EDIT_WORKING_SERVER_F2); + tableContextItemDelete.put(tabSessions, Strings.CONTEXT_MENU_KILL_SESSION_DEL); + tableContextItemDelete.put(tabConnections, Strings.CONTEXT_MENU_KILL_CONNECTION_DEL); + tableContextItemDelete.put(tabWorkingServers, Strings.CONTEXT_MENU_DELETE_WORKING_SERVER_DEL); + + // соответствие таблиц списков + linksTablesToExtendedClass.put(tabSessions, SessionInfoExtended.class); + linksTablesToExtendedClass.put(tabConnections, ConnectionInfoExtended.class); + linksTablesToExtendedClass.put(tabLocks, LockInfoExtended.class); + linksTablesToExtendedClass.put(tabWorkingServers, WorkingServerInfoExtended.class); + linksTablesToExtendedClass.put(tabWorkingProcesses, WorkingProcessInfoExtended.class); + } - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); + private ToolItem addItemInToolbar( + ToolBar parent, String text, Image icon, SelectionAdapter listener) { - CreateEditWorkingServerDialog editWorkingServerDialog; - try { - editWorkingServerDialog = - new CreateEditWorkingServerDialog( - getParent().getDisplay().getActiveShell(), server, clusterId, null); - } catch (Exception excp) { - LOGGER.error( - "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ - clusterId, - excp); - return; - } - - int dialogResult = editWorkingServerDialog.open(); - if (dialogResult == 0) { - var newWorkingServerUuid = editWorkingServerDialog.getNewWorkingServerId(); - if (newWorkingServerUuid != null) { - IWorkingServerInfo workingServerInfo = - server.getWorkingServerInfo(clusterId, newWorkingServerUuid); - addWorkingServerItemInNode(item[0].getParentItem(), workingServerInfo); - } - } - } - }); - - MenuItem menuItemEditWorkingServer = new MenuItem(workingServerMenu, SWT.NONE); - menuItemEditWorkingServer.setText( - Messages.getString("ViewerArea.EditWorkingServer")); //$NON-NLS-1$ - menuItemEditWorkingServer.setImage(editIcon); - menuItemEditWorkingServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } - - Server server = getCurrentServerConfig(item[0]); - UUID workingServerId = getCurrentWorkingServerId(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - - CreateEditWorkingServerDialog editClusterDialog; - try { - editClusterDialog = - new CreateEditWorkingServerDialog( - getParent().getDisplay().getActiveShell(), - server, - clusterId, - workingServerId); - } catch (Exception excp) { - excp.printStackTrace(); - LOGGER.error( - "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ - workingServerId, - excp); - return; - } + ToolItem toolItem = new ToolItem(parent, SWT.PUSH); + toolItem.setText(text); + toolItem.setImage(icon); + toolItem.addSelectionListener(listener); - editClusterDialog.open(); - } - }); + return toolItem; } - private void initInfobaseNodeMenu() { + private void addMenuSeparator(Menu menu) { + new MenuItem(menu, SWT.SEPARATOR); + } - infobaseNodeMenu = new Menu(serversTree); + private Menu addItemGroupInMenu(Menu parent, String text, Image icon) { + // TODO rename createCascadeMenuGroup - MenuItem menuItemNewInfobase = new MenuItem(infobaseNodeMenu, SWT.NONE); - menuItemNewInfobase.setText(Messages.getString("ViewerArea.CreateInfobase")); //$NON-NLS-1$ - menuItemNewInfobase.setImage(addIcon); - menuItemNewInfobase.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + Menu subMenu = new Menu(parent); - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); + MenuItem groupMenu = new MenuItem(parent, SWT.CASCADE); + groupMenu.setText(text); + groupMenu.setImage(icon); + groupMenu.setMenu(subMenu); - CreateInfobaseDialog infobaseDialog; - try { - infobaseDialog = - new CreateInfobaseDialog( - getParent().getDisplay().getActiveShell(), server, clusterId, null); - } catch (Exception excp) { - LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ - return; - } + return subMenu; + } - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - var newInfobaseUuid = infobaseDialog.getNewInfobaseUuid(); - if (newInfobaseUuid != null) { - IInfoBaseInfoShort infoBaseInfo = - server.getInfoBaseShortInfo(clusterId, newInfobaseUuid); - addInfobaseItemInInfobaseNode(item[0], infoBaseInfo); - } - } - } - }); + private MenuItem addItemInMenu(Menu parent, String text, Image icon, SelectionAdapter listener) { - MenuItem menuItemUpdateInfobases = new MenuItem(infobaseNodeMenu, SWT.NONE); - menuItemUpdateInfobases.setText( - Messages.getString("ViewerArea.UpdateInfobases")); //$NON-NLS-1$ - menuItemUpdateInfobases.setImage(updateIcon); - menuItemUpdateInfobases.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + MenuItem menuItem = new MenuItem(parent, SWT.NONE); // SWT.BOLD + menuItem.setText(text); + menuItem.setImage(icon); + menuItem.addSelectionListener(listener); - Server server = getCurrentServerConfig(item[0]); - fillInfobasesOfCluster(item[0].getParentItem(), server); - } - }); + return menuItem; } - private void initInfobaseMenu() { - - infobaseMenu = new Menu(serversTree); - - MenuItem menuItemCopyInfobase = new MenuItem(infobaseMenu, SWT.NONE); - menuItemCopyInfobase.setText( - Messages.getString("ViewerArea.CreateNewInfobaseUsingThis")); //$NON-NLS-1$ - menuItemCopyInfobase.setImage(addIcon); - menuItemCopyInfobase.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + private MenuItem addRadioItemInMenu( + Menu parent, + String text, + SelectionAdapter listener, + Object data, + boolean selected) { - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID sampleInfobaseId = getCurrentInfobaseId(item[0]); + MenuItem menuItem = new MenuItem(parent, SWT.RADIO); + menuItem.setText(text); + menuItem.addSelectionListener(listener); + menuItem.setData(data); + menuItem.setSelection(selected); - CreateInfobaseDialog infobaseDialog; - try { - infobaseDialog = - new CreateInfobaseDialog( - getParent().getDisplay().getActiveShell(), - server, - clusterId, - sampleInfobaseId); - } catch (Exception excp) { - LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ - return; - } + return menuItem; + } - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - var newInfobaseUuid = infobaseDialog.getNewInfobaseUuid(); - if (newInfobaseUuid != null) { - IInfoBaseInfoShort infoBaseInfo = - server.getInfoBaseShortInfo(clusterId, newInfobaseUuid); - addInfobaseItemInInfobaseNode(item[0].getParentItem(), infoBaseInfo); - } - } - } - }); + private TreeItem addServerItemInServersTree(Server server) { + return addServerItemInServersTree(server, -1); + } - MenuItem menuItemEditInfobase = new MenuItem(infobaseMenu, SWT.NONE); - menuItemEditInfobase.setText(Messages.getString("ViewerArea.EditInfobase")); //$NON-NLS-1$ - menuItemEditInfobase.setImage(editIcon); - menuItemEditInfobase.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + private TreeItem addServerItemInServersTree(Server server, int index) { - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); + return addItemInNode( + serversTree, + index, + server.getTreeTitle(), + TreeItemType.SERVER, + SERVER_INFO, + server, + server.isConnected() ? serverConnectedIcon : serverIcon); + } - EditInfobaseDialog infobaseDialog; - try { - infobaseDialog = - new EditInfobaseDialog( - getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); - } catch (Exception excp) { - excp.printStackTrace(); - return; - } + private TreeItem addClusterItemInServersTree(TreeItem serverItem, IClusterInfo clusterInfo) { - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - // TODO обновить в дереве description инфобазы - // server.clusterConnector.updateInfoBase(server.clusterID, infoBaseInfo); - } - } - }); + Server server = getServer(serverItem); + if (server == null) { + LOGGER.error("Error get Server from serverItem"); //$NON-NLS-1$ + return null; + } - MenuItem menuItemDeleteInfobase = new MenuItem(infobaseMenu, SWT.NONE); - menuItemDeleteInfobase.setText(Messages.getString("ViewerArea.DeleteInfobase")); //$NON-NLS-1$ - menuItemDeleteInfobase.setImage(deleteIcon); - menuItemDeleteInfobase.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + return addItemInNode( + serverItem, + server.getClusterTreeTitle(clusterInfo), + TreeItemType.CLUSTER, + ID_DATA_KEY, + clusterInfo.getClusterId(), + clusterIcon); + } - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); + private TreeItem addInfobasesNode(TreeItem nodeItem, UUID clusterId, String title) { + return addItemInNode( + nodeItem, title, TreeItemType.INFOBASE_NODE, ID_DATA_KEY, clusterId, infobasesIcon); + } - DropInfobaseDialog infobaseDialog; - try { - infobaseDialog = - new DropInfobaseDialog( - getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); - } catch (Exception excp) { - excp.printStackTrace(); - return; - } + private TreeItem addInfobaseItemInNode(TreeItem infobaseNode, InfoBaseInfoShortExt infoBaseInfo) { + return addInfobaseItemInNode(infobaseNode, infoBaseInfo, -1); + } - int dialogResult = infobaseDialog.open(); - if (dialogResult == 0) { - item[0].dispose(); - } - } - }); + private TreeItem addInfobaseItemInNode( + TreeItem infobaseNode, InfoBaseInfoShortExt infoBaseInfo, int index) { - // Создание вложенных подпунктов меню - Menu infobaseSubMenuSessionManage = new Menu(infobaseMenu); + String infobaseTitle = infoBaseInfo.getInfobaseDescription(); - MenuItem infobaseMenuSessionManage = new MenuItem(infobaseMenu, SWT.CASCADE); - infobaseMenuSessionManage.setText( - Messages.getString("ViewerArea.SessionManage")); //$NON-NLS-1$ - infobaseMenuSessionManage.setMenu(infobaseSubMenuSessionManage); - // infobaseSubMenuSessionManage.setImage(terminateSessionIcon); + TreeItem item = + addItemInNode( + infobaseNode, + index, + infobaseTitle, + TreeItemType.INFOBASE, + ID_DATA_KEY, + infoBaseInfo.getInfoBaseId(), + infoBaseInfo.getIcon()); - MenuItem menuItemLockUserSessionsNow = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); - menuItemLockUserSessionsNow.setText( - Messages.getString("ViewerArea.LockSessionsNow")); //$NON-NLS-1$ - menuItemLockUserSessionsNow.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + item.setData(InfoBaseInfoShortExt.class.getSimpleName(), infoBaseInfo); - TreeItem selectItem = item[0]; + return item; + } - Server server = getCurrentServerConfig(selectItem); - UUID clusterId = getCurrentClusterId(selectItem); - UUID infobaseId = getCurrentInfobaseId(selectItem); + private TreeItem addWorkingProcessNode(TreeItem nodeItem, UUID clusterId, String title) { + return addItemInNode( + nodeItem, + title, + TreeItemType.WORKINGPROCESS_NODE, + ID_DATA_KEY, + clusterId, + workingProcessesIcon); + } - IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infobaseId); - if (infoBaseInfo == null) { - return; - } + private TreeItem addWorkingProcessItemInNode(TreeItem wpNodeItem, IWorkingProcessInfo wpInfo) { - infoBaseInfo.setScheduledJobsDenied(true); - infoBaseInfo.setSessionsDenied(true); - infoBaseInfo.setDeniedFrom(null); - infoBaseInfo.setDeniedTo(null); - infoBaseInfo.setDeniedMessage(""); //$NON-NLS-1$ - infoBaseInfo.setDeniedParameter(""); //$NON-NLS-1$ - infoBaseInfo.setPermissionCode(""); //$NON-NLS-1$ + Server server = getServer(wpNodeItem); + if (server == null) { + LOGGER.error("Error get Server from wpNodeItem"); //$NON-NLS-1$ + return null; + } - server.updateInfoBase(clusterId, infoBaseInfo); - } - }); + return addItemInNode( + wpNodeItem, + server.getWorkingProcessTreeTitle(wpInfo), + TreeItemType.WORKINGPROCESS, + ID_DATA_KEY, + wpInfo.getWorkingProcessId(), + workingProcessIcon); + } - MenuItem menuItemTerminateAllSessions = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); - menuItemTerminateAllSessions.setText( - Messages.getString("ViewerArea.TerminateAllSessions")); //$NON-NLS-1$ - menuItemTerminateAllSessions.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + private TreeItem addWorkingServerNode(TreeItem nodeItem, UUID clusterId, String title) { + return addItemInNode( + nodeItem, + title, + TreeItemType.WORKINGSERVER_NODE, + ID_DATA_KEY, + clusterId, + workingServerIcon); + } - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); + private TreeItem addWorkingServerItemInNode(TreeItem wsNodeItem, IWorkingServerInfo wsInfo) { - server.terminateAllSessionsOfInfobase(clusterId, infobaseId, false); - } - }); + Server server = getServer(wsNodeItem); + if (server == null) { + LOGGER.error("Error get Server from wsNodeItem"); //$NON-NLS-1$ + return null; + } - MenuItem menuItemTerminateUserSessions = new MenuItem(infobaseSubMenuSessionManage, SWT.NONE); - menuItemTerminateUserSessions.setText( - Messages.getString("ViewerArea.TerminateUsersSessions")); //$NON-NLS-1$ - menuItemTerminateUserSessions.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + return addItemInNode( + wsNodeItem, + server.getWorkingServerTreeTitle(wsInfo), + TreeItemType.WORKINGSERVER, + ID_DATA_KEY, + wsInfo.getWorkingServerId(), + workingServerIcon); + } - Server server = getCurrentServerConfig(item[0]); - UUID clusterId = getCurrentClusterId(item[0]); - UUID infobaseId = getCurrentInfobaseId(item[0]); + private TreeItem addItemInNode( + Tree nodeItem, + int index, + String title, + TreeItemType itemType, + String idDataKey, + Object idDataValue, + Image icon) { + + TreeItem item = null; + if (index == -1) { + item = new TreeItem(nodeItem, SWT.NONE); + } else { + item = new TreeItem(nodeItem, SWT.NONE, index); + } + setItemProperties(item, title, itemType, idDataKey, idDataValue, icon); - server.terminateAllSessionsOfInfobase(clusterId, infobaseId, true); - } - }); + return item; } - private void initSessionTable(TabFolder tabFolder) { - - tabSessions = new TabItem(tabFolder, SWT.NONE); - tabSessions.setText(Messages.getString("ViewerArea.Sessions")); //$NON-NLS-1$ + private TreeItem addItemInNode( + TreeItem nodeItem, + int index, + String title, + TreeItemType itemType, + String idDataKey, + Object idDataValue, + Image icon) { + + TreeItem item = null; + if (index == -1) { + item = new TreeItem(nodeItem, SWT.NONE); + } else { + item = new TreeItem(nodeItem, SWT.NONE, index); + } + setItemProperties(item, title, itemType, idDataKey, idDataValue, icon); - tableSessions = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK); - tabSessions.setControl(tableSessions); - tableSessions.setHeaderVisible(true); - tableSessions.setLinesVisible(true); + return item; + } - initSessionsTableContextMenu(); + private TreeItem addItemInNode( + TreeItem nodeItem, + String title, + TreeItemType itemType, + String idDataKey, + Object idDataValue, + Image icon) { - SessionInfoExtended.initColumnsName(sessionColumnsMap); + TreeItem item = new TreeItem(nodeItem, SWT.NONE); + setItemProperties(item, title, itemType, idDataKey, idDataValue, icon); - ColumnProperties columnProperties = - ClusterProvider.getCommonConfig().getSessionColumnProperties(); + return item; + } - String[] columnNameList = sessionColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) { - addTableColumn( - tableSessions, columnName, columnProperties.getWidth(), columnProperties.getVisible()); - } + private void setItemProperties( + TreeItem item, + String title, + TreeItemType itemType, + String idDataKey, + Object idDataValue, + Image icon) { + + item.setText(new String[] {title}); + item.setData("Type", itemType); //$NON-NLS-1$ + item.setData(idDataKey, idDataValue); + item.setImage(icon); + item.setChecked(false); - int[] columnOrder = columnProperties.getOrder(); - if (columnOrder != null && tableSessions.getColumnCount() == columnOrder.length) { - tableSessions.setColumnOrder(columnOrder); + if (itemType.equals(currentHighlightingType) + && Objects.equals(idDataValue, currentHighlightingData)) { + highlightTreeItem(item); } } - private void initSessionsTableContextMenu() { + private void addTableColumn(Table table, String text, ColumnProperties columnProperties) { - Menu tableSessionsMenu = new Menu(tableSessions); - tableSessions.setMenu(tableSessionsMenu); - tableSessions.addKeyListener(keyListener); + final int[] columnWidth = columnProperties.getWidth(); + final boolean[] columnVisible = columnProperties.getVisible(); - tableSessions.addListener( - SWT.Selection, - new Listener() { - @Override - public void handleEvent(Event event) { - if (event.detail == SWT.CHECK) { - TableItem item = (TableItem) event.item; - String id = item.getText(1).concat("*").concat(item.getText(2)); //$NON-NLS-1$ - if (item.getChecked()) { - watchedSessions.add(id); - item.setForeground(watchedSessionColor); - } else { - watchedSessions.remove(id); - item.setForeground(standardColor); - } - } - } - }); + var newColumn = new TableColumn(table, SWT.NONE); + newColumn.setText(text); + newColumn.setMoveable(true); + newColumn.setAlignment(SWT.RIGHT); - // Выделение одной ячейки, для копирования значения из нее через CTRL+C - // Из-за добавления этого Listener-а пропадает прямоугольник выделения строк (передвигая мышь с - // зажатой ЛКМ) - // tableSessions.addListener( - // SWT.MouseDown, - // new Listener() { - // @Override - // public void handleEvent(Event event) { - // Table currentTable = (Table) event.widget; - // - // Point pt = new Point(event.x, event.y); - // TableItem item = currentTable.getItem(pt); - // if (item != null) { - // for (int col = 0; col < currentTable.getColumnCount(); col++) { - // Rectangle rect = item.getBounds(col); - // if (rect.contains(pt)) { - // - // if (Objects.nonNull(lastSelectItem) && !lastSelectItem.isDisposed()) { - // lastSelectItem.setForeground(lastSelectColumn, new Color(0, 0, 0)); - // } - // - // // System.out.println("item clicked."); - // // System.out.println("column is " + col); - // System.out.println(item.getText(col)); - // - // // Color blue = display.getSystemColor(SWT.COLOR_BLUE); - // item.setForeground(col, new Color(0, 100, 128)); - // // item.setFont(col, fontBold); - // - // lastSelectItem = item; - // lastSelectColumn = col; - // break; - // } - // } - // } - // } - // }); - - MenuItem menuItemUpdateList = new MenuItem(tableSessionsMenu, SWT.NONE); - menuItemUpdateList.setText( - Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - MenuItem menuItemViewSession = new MenuItem(tableSessionsMenu, SWT.NONE); - menuItemViewSession.setText( - Messages.getString("ViewerArea.ViewSession").concat("\tF2")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemViewSession.setAccelerator(SWT.F2); - menuItemViewSession.setImage(editIcon); - menuItemViewSession.addSelectionListener(editItemListener); - - MenuItem menuItemKillSession = new MenuItem(tableSessionsMenu, SWT.NONE); - menuItemKillSession.setText( - Messages.getString("ViewerArea.KillSession").concat("\tDEL")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemKillSession.setAccelerator(SWT.DEL); - menuItemKillSession.setImage(deleteIcon); - menuItemKillSession.addSelectionListener(deleteItemListener); - } - - private void deleteSelectSession() { - - Table currentTable = null; - - if (currentTabitem.equals(tabSessions)) { - currentTable = tableSessions; - } else if (currentTabitem.equals(tabConnections)) { - currentTable = tableConnections; - } else if (currentTabitem.equals(tabWorkingServers)) { - currentTable = tableWorkingServers; + int numOfColumn = table.getColumnCount() - 1; + newColumn.setData(numOfColumn); + if (numOfColumn == columnProperties.getSortColumn()) { + table.setSortColumn(newColumn); + table.setSortDirection(columnProperties.getSortDirectionSwt()); } - if (currentTable == null) { - return; + if (columnVisible != null && columnVisible[numOfColumn]) { + newColumn.setResizable(true); + newColumn.setWidth( + // columnWidth == null //TODO нужно ли это еще + // || columnWidth.length <= table.getColumnCount() + // || + columnWidth[numOfColumn] == 0 ? 100 : columnWidth[numOfColumn]); + } else { + newColumn.setResizable(false); + newColumn.setWidth(0); } - TableItem[] selectedItems = currentTable.getSelection(); - if (selectedItems.length == 0) { - return; - } + newColumn.addListener(SWT.Move, columnMoveListener); + newColumn.addListener(SWT.Resize, columnResizeListener); + newColumn.addListener(SWT.Selection, columnSortListener); + } - for (TableItem item : selectedItems) { - item.setForeground(deletedItemColor); + private Server getCurrentServer() { + return getServer(currentTreeItem); + } - if (currentTable.equals(tableSessions)) { - Server server = (Server) item.getData(SERVER_INFO); - UUID clusterId = (UUID) item.getData(CLUSTER_ID); - UUID sessionId = (UUID) item.getData(SESSION_ID); + private UUID getCurrentClusterId() { + return getClusterId(currentTreeItem); + } - if (server.terminateSession(clusterId, sessionId)) { - item.dispose(); // update tableSessions - } + private UUID getCurrentWorkingProcessId() { + return getWorkingProcessId(currentTreeItem); + } - } else if (currentTable.equals(tableConnections)) { - Server server = (Server) item.getData(SERVER_INFO); - UUID clusterId = (UUID) item.getData(CLUSTER_ID); - UUID pricessId = (UUID) item.getData(WORKINGPROCESS_ID); - UUID connectionId = (UUID) item.getData(CONNECTION_ID); - UUID infobaseId = (UUID) item.getData(INFOBASE_ID); + private UUID getCurrentWorkingServerId() { + return getWorkingServerId(currentTreeItem); + } - if (server.disconnectConnection(clusterId, pricessId, connectionId, infobaseId)) { - item.dispose(); // update tableConnections - } + private Server getServer(TreeItem item) { + if (item == null) { + return null; + } + + if (getTreeItemType(item) == TreeItemType.SERVER) { + return (Server) item.getData(SERVER_INFO); + } - } else if (currentTable.equals(tableWorkingServers)) { - Server server = (Server) item.getData(SERVER_INFO); - UUID clusterId = (UUID) item.getData(CLUSTER_ID); - UUID workingServerId = (UUID) item.getData(WORKINGSERVER_ID); + TreeItem parentItem = item.getParentItem(); + while (parentItem != null) { - if (server.unregWorkingServer(clusterId, workingServerId)) { - item.dispose(); // update tableWorkingServers - } + if (getTreeItemType(parentItem) == TreeItemType.SERVER) { + return (Server) parentItem.getData(SERVER_INFO); } else { - break; + parentItem = parentItem.getParentItem(); } } + return null; } - private void initConnectionsTable(TabFolder tabFolder) { - - tabConnections = new TabItem(tabFolder, SWT.NONE); - tabConnections.setText(Messages.getString("ViewerArea.Connections")); //$NON-NLS-1$ - - tableConnections = - new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabConnections.setControl(tableConnections); - tableConnections.setHeaderVisible(true); - tableConnections.setLinesVisible(true); - - initConnectionsTableContextMenu(); - - ConnectionInfoExtended.initColumnsName(connectionColumnsMap); + private UUID getClusterId(TreeItem item) { + return getTreeItemId(TreeItemType.CLUSTER, item); + } - ColumnProperties columnProperties = - ClusterProvider.getCommonConfig().getConnectionColumnProperties(); + private UUID getWorkingProcessId(TreeItem item) { + return getTreeItemId(TreeItemType.WORKINGPROCESS, item); + } - String[] columnNameList = connectionColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) { - addTableColumn( - tableConnections, columnName, columnProperties.getWidth(), columnProperties.getVisible()); - } + private UUID getWorkingServerId(TreeItem item) { + return getTreeItemId(TreeItemType.WORKINGSERVER, item); + } - int[] columnOrder = columnProperties.getOrder(); - if (columnOrder != null && tableConnections.getColumnCount() == columnOrder.length) { - tableConnections.setColumnOrder(columnOrder); + private UUID getInfobaseId(TreeItem item) { + if (getTreeItemType(item) == TreeItemType.INFOBASE) { + return (UUID) item.getData(ID_DATA_KEY); + } else { + return null; } } - private void initConnectionsTableContextMenu() { - - Menu tableConnectionsMenu = new Menu(tableConnections); - tableConnections.setMenu(tableConnectionsMenu); - tableConnections.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(tableConnectionsMenu, SWT.NONE); - menuItemUpdateList.setText( - Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - MenuItem menuItemKillSession = new MenuItem(tableConnectionsMenu, SWT.NONE); - menuItemKillSession.setText( - Messages.getString("ViewerArea.KillConnection").concat("\tDEL")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemKillSession.setAccelerator(SWT.DEL); - menuItemKillSession.setImage(deleteIcon); - menuItemKillSession.addSelectionListener(deleteItemListener); + private InfoBaseInfoShortExt getInfobaseShortInfoExt(TreeItem item) { + if (getTreeItemType(item) == TreeItemType.INFOBASE) { + return (InfoBaseInfoShortExt) item.getData(InfoBaseInfoShortExt.class.getSimpleName()); + } else { + return null; + } } - private void initLocksTable(TabFolder tabFolder) { - - tabLocks = new TabItem(tabFolder, SWT.NONE); - tabLocks.setText(Messages.getString("ViewerArea.Locks")); //$NON-NLS-1$ - - tableLocks = new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabLocks.setControl(tableLocks); - tableLocks.setHeaderVisible(true); - tableLocks.setLinesVisible(true); - - initLocksTableContextMenu(); + private UUID getTreeItemId(TreeItemType itemType, TreeItem item) { + if (item == null) { + return null; + } - LockInfoExtended.initColumnsName(lockColumnsMap); + if (getTreeItemType(item) == itemType) { + return (UUID) item.getData(ID_DATA_KEY); + } - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().getLockColumnProperties(); + TreeItem parentItem = item.getParentItem(); + while (parentItem != null) { - String[] columnNameList = lockColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) { - addTableColumn( - tableLocks, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + if (getTreeItemType(parentItem) == itemType) { + return (UUID) parentItem.getData(ID_DATA_KEY); + } else { + parentItem = parentItem.getParentItem(); + } } + return null; + } - int[] columnOrder = columnProperties.getOrder(); - if (columnOrder != null && tableLocks.getColumnCount() == columnOrder.length) { - tableLocks.setColumnOrder(columnOrder); - } + private TreeItemType getTreeItemType(TreeItem item) { + // TODO переделать в equals? + return (TreeItemType) item.getData("Type"); //$NON-NLS-1$ } - private void initLocksTableContextMenu() { + private void runAutonnectAllServers() { - Menu tableLocksMenu = new Menu(tableLocks); - tableLocks.setMenu(tableLocksMenu); - tableLocks.addKeyListener(keyListener); + TreeItem[] serversItem = serversTree.getItems(); - MenuItem menuItemUpdateList = new MenuItem(tableLocksMenu, SWT.NONE); - menuItemUpdateList.setText( - Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); + for (TreeItem serverItem : serversItem) { + Server server = getServer(serverItem); + if (server != null && !server.isConnected() && server.getAutoconnect()) { + connectServerItem(serverItem, true); + } + } } - private void initWorkingProcessesTable(TabFolder tabFolder) { + private void connectServerItem(TreeItem serverItem, boolean silentMode) { - tabWorkingProcesses = new TabItem(tabFolder, SWT.NONE); - tabWorkingProcesses.setText(Messages.getString("ViewerArea.WorkingProcesses")); //$NON-NLS-1$ + // async не работает асинхронно + serverItem.setImage(serverConnectingIcon); + Display.getDefault() + .asyncExec( + new Runnable() { - tableWorkingProcesses = - new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabWorkingProcesses.setControl(tableWorkingProcesses); - tableWorkingProcesses.setHeaderVisible(true); - tableWorkingProcesses.setLinesVisible(true); + @Override + public void run() { - initWorkingProcessesTableContextMenu(); + Server server = getServer(serverItem); + if (server == null) { + return; + } + server.connectToServer(false, silentMode); - WorkingProcessInfoExtended.initColumnsName(wpColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().getWpColumnProperties(); - - String[] columnNameList = wpColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) { - addTableColumn( - tableWorkingProcesses, columnName, columnProperties.getWidth(), columnProperties.getVisible()); - } - - int[] columnOrder = columnProperties.getOrder(); - if (columnOrder != null && tableWorkingProcesses.getColumnCount() == columnOrder.length) { - tableWorkingProcesses.setColumnOrder(columnOrder); - } - } - - private void initWorkingProcessesTableContextMenu() { - - Menu tableWorkingProcessesMenu = new Menu(tableWorkingProcesses); - tableWorkingProcesses.setMenu(tableWorkingProcessesMenu); - tableWorkingProcesses.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(tableWorkingProcessesMenu, SWT.NONE); - menuItemUpdateList.setText( - Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); + serverItem.setImage( // TODO server.getImage() + server.isConnected() ? serverConnectedIcon : serverDisconnectIcon); + serverItem.setText(new String[] {server.getTreeTitle()}); + updateClustersInTree(serverItem); + } + }); } - private void initWorkingServersTable(TabFolder tabFolder) { - - tabWorkingServers = new TabItem(tabFolder, SWT.NONE); - tabWorkingServers.setText(Messages.getString("ViewerArea.WorkingServers")); //$NON-NLS-1$ - - tableWorkingServers = - new Table(tabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI); // | SWT.CHECK - tabWorkingServers.setControl(tableWorkingServers); - tableWorkingServers.setHeaderVisible(true); - tableWorkingServers.setLinesVisible(true); - - initWorkingServersTableContextMenu(); - - WorkingServerInfoExtended.initColumnsName(wsColumnsMap); - - ColumnProperties columnProperties = ClusterProvider.getCommonConfig().getWsColumnProperties(); - - String[] columnNameList = wsColumnsMap.keySet().toArray(new String[0]); - for (String columnName : columnNameList) { - addTableColumn( - tableWorkingServers, columnName, columnProperties.getWidth(), columnProperties.getVisible()); + private void disconnectServerItem(TreeItem serverItem) { + Server server = getServer(serverItem); + if (server == null) { + return; } + server.disconnectFromAgent(); + serverItem.setImage(serverIcon); - int[] columnOrder = columnProperties.getOrder(); - if (columnOrder != null && tableWorkingServers.getColumnCount() == columnOrder.length) { - tableWorkingServers.setColumnOrder(columnOrder); + TreeItem[] clusterItems = serverItem.getItems(); + for (TreeItem clusterItem : clusterItems) { + clusterItem.dispose(); } } - private void initWorkingServersTableContextMenu() { - - Menu workingServersMenu = new Menu(tableWorkingServers); - tableWorkingServers.setMenu(workingServersMenu); - tableWorkingServers.addKeyListener(keyListener); - - MenuItem menuItemUpdateList = new MenuItem(workingServersMenu, SWT.NONE); - menuItemUpdateList.setText( - Messages.getString("ViewerArea.Update").concat("\tF5")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemUpdateList.setAccelerator(SWT.F5); // TODO ??? - menuItemUpdateList.setImage(updateIcon); - menuItemUpdateList.addSelectionListener(updateItemListener); - - MenuItem menuItemCreateWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); - menuItemCreateWorkingServer.setText( - Messages.getString("ViewerArea.CreateWorkingServer")); //$NON-NLS-1$ - menuItemCreateWorkingServer.setImage(addIcon); - menuItemCreateWorkingServer.addSelectionListener( - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - TableItem[] item = tableWorkingServers.getSelection(); - if (item.length == 0) { - return; - } - - Server server = (Server) item[0].getData(SERVER_INFO); - UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); - - CreateEditWorkingServerDialog editWorkingServerDialog; - try { - editWorkingServerDialog = - new CreateEditWorkingServerDialog( - getParent().getDisplay().getActiveShell(), server, clusterId, null); - } catch (Exception excp) { - LOGGER.error( - "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ - clusterId, - excp); - return; - } - - int dialogResult = editWorkingServerDialog.open(); - if (dialogResult == 0) { - var newWorkingServerUuid = editWorkingServerDialog.getNewWorkingServerId(); - if (newWorkingServerUuid != null) { - IWorkingServerInfo workingServerInfo = - server.getWorkingServerInfo(clusterId, newWorkingServerUuid); - addWorkingServerInTable(server, clusterId, workingServerInfo); - } - } - } - }); - - MenuItem menuItemEditWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); - menuItemEditWorkingServer.setText( - Messages.getString("ViewerArea.EditWorkingServer").concat("\tF2")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemEditWorkingServer.setImage(editIcon); - menuItemEditWorkingServer.addSelectionListener(editItemListener); - - MenuItem menuItemDeleteWorkingServer = new MenuItem(workingServersMenu, SWT.NONE); - menuItemDeleteWorkingServer.setText( - Messages.getString("ViewerArea.DeleteWorkingServer").concat("\tDEL")); //$NON-NLS-1$ //$NON-NLS-2$ - menuItemDeleteWorkingServer.setImage(deleteIcon); - menuItemDeleteWorkingServer.addSelectionListener(deleteItemListener); - } - private void fillServersList() { // TODO Auto-generated method stub } private void updateClustersInTree(TreeItem serverItem) { - Server server = getCurrentServerConfig(serverItem); - TreeItem[] clustersItems = serverItem.getItems(); + Server server = getServer(serverItem); + if (server == null) { + return; + } // у отключенного сервера удаляем все дочерние элементы if (!server.isConnected()) { - for (TreeItem clusterItem : clustersItems) { - disposeTreeItemWithChildren(clusterItem); - } + Arrays.stream(serverItem.getItems()).forEach(Widget::dispose); return; } List clusters = server.getClusters(); // удаление несуществующих элементов - for (TreeItem clusterItem : clustersItems) { - UUID currentClusterId = getCurrentClusterId(clusterItem); - List foundCluster = - clusters.stream() - .filter(c -> c.getClusterId().equals(currentClusterId)) - .collect(Collectors.toList()); - - if (foundCluster.isEmpty()) { - disposeTreeItemWithChildren(clusterItem); - } - } + Arrays.stream(serverItem.getItems()) + .forEach( + clusterItem -> { + List foundCluster = + clusters.stream() + .filter(c -> c.getClusterId().equals(getClusterId(clusterItem))) + .collect(Collectors.toList()); + if (foundCluster.isEmpty()) { + clusterItem.dispose(); + } + }); - // добавление новых элементов + // добавление новых элементов или обновление существующих clusters.forEach( clusterInfo -> { - var itemFound = false; - TreeItem currentClusterItem = null; - for (TreeItem clusterItem : serverItem.getItems()) { - if (getCurrentClusterId(clusterItem).equals(clusterInfo.getClusterId())) { - currentClusterItem = clusterItem; - itemFound = true; - break; - } - } - - if (!itemFound) { - currentClusterItem = addClusterItemInServersTree(serverItem, clusterInfo); - } - - // Заполнение дерева кластера - if (currentClusterItem != null) { - fillChildrenItemsOfCluster(currentClusterItem, server); - } + TreeItem currentClusterItem = + Arrays.stream(serverItem.getItems()) + .filter(cl -> getClusterId(cl).equals(clusterInfo.getClusterId())) + .findFirst() + .orElseGet(() -> addClusterItemInServersTree(serverItem, clusterInfo)); + + // Обновление дерева кластера + updateNodesOfCluster(currentClusterItem, server); }); // Разворачиваем дерево, если включена настройка - serverItem.setExpanded(ClusterProvider.getCommonConfig().isExpandServersTree()); + serverItem.setExpanded(config.isExpandServersTree()); } - private void fillChildrenItemsOfCluster(TreeItem clusterItem, Server server) { + private void updateNodesOfCluster(TreeItem clusterItem, Server server) { - fillInfobasesOfCluster(clusterItem, server); - fillWorkingProcessesInCluster(clusterItem, server); - fillWorkingServersInCluster(clusterItem, server); + updateInfobasesOfCluster(clusterItem, server); + updateWorkingProcessesInCluster(clusterItem, server); + updateWorkingServersInCluster(clusterItem, server); - clusterItem.setExpanded(ClusterProvider.getCommonConfig().isExpandClustersTree()); + clusterItem.setExpanded(config.isExpandClustersTree()); } - private void fillInfobasesOfCluster(TreeItem clusterItem, Server server) { - - TreeItem infobasesNode = null; - for (TreeItem treeItem : clusterItem.getItems()) { - if (treeItem.getData("Type") == TreeItemType.INFOBASE_NODE) { //$NON-NLS-1$ - infobasesNode = treeItem; - break; - } - } + private void updateInfobasesOfCluster(TreeItem clusterItem, Server server) { + // Refactor this method to reduce its Cognitive Complexity from 29 to the 15 allowed. - if (infobasesNode == null) { - infobasesNode = new TreeItem(clusterItem, SWT.NONE); - infobasesNode.setData("Type", TreeItemType.INFOBASE_NODE); //$NON-NLS-1$ - infobasesNode.setImage(infobasesIcon); - infobasesNode.setChecked(false); - } + UUID clusterId = getClusterId(clusterItem); + server.provideSavedInfobasesCredentialsToCluster(clusterId); + List infoBases = server.getInfoBasesShort(clusterId); + var infobasesNodeTitle = String.format(Strings.TREE_INFOBASES_COUNT, infoBases.size()); - UUID clusterId = getCurrentClusterId(infobasesNode); - List infoBases = server.getInfoBasesShort(clusterId); + // поиск или создание узла инфобаз + TreeItem infobasesNode = + Arrays.stream(clusterItem.getItems()) + .filter(node -> node.getData("Type").equals(TreeItemType.INFOBASE_NODE)) + .findFirst() + .orElseGet(() -> addInfobasesNode(clusterItem, clusterId, infobasesNodeTitle)); - var infobasesNodeTitle = - String.format( - Messages.getString("ViewerArea.InfobasesCount"), infoBases.size()); //$NON-NLS-1$ - infobasesNode.setText(new String[] {infobasesNodeTitle}); + infobasesNode.setText(new String[] {infobasesNodeTitle}); // TODO надо обновить только у старых + // если у кластера нет инфобаз, то у узла удаляем все элементы if (infoBases.isEmpty()) { - for (TreeItem infobase : infobasesNode.getItems()) { - infobase.dispose(); - } + Arrays.stream(infobasesNode.getItems()).forEach(Widget::dispose); return; } + // TODO с учетом сортировки, может быть дешевле просто удалить все и заново заполнить // удаление несуществующих элементов - for (TreeItem infobaseItem : infobasesNode.getItems()) { - UUID currentInfobaseId = getCurrentInfobaseId(infobaseItem); - List foundItems = - infoBases.stream() - .filter(c -> c.getInfoBaseId().equals(currentInfobaseId)) - .collect(Collectors.toList()); - - if (foundItems.isEmpty()) { - infobaseItem.dispose(); - } - } + Arrays.stream(infobasesNode.getItems()) + .forEach( + infobaseItem -> { + List foundItems = + infoBases.stream() + .filter(ib -> ib.getInfoBaseId().equals(getInfobaseId(infobaseItem))) + .collect(Collectors.toList()); + if (foundItems.isEmpty()) { + infobaseItem.dispose(); + } + }); // добавление новых элементов - for (IInfoBaseInfoShort infoBaseInfo : infoBases) { - // infoBases.forEach(infoBaseInfo -> { - - var itemFound = false; - for (TreeItem infobaseItem : infobasesNode.getItems()) { - if (getCurrentInfobaseId(infobaseItem).equals(infoBaseInfo.getInfoBaseId())) { - itemFound = true; - break; - } - } - - if (!itemFound) { - addInfobaseItemInInfobaseNode(infobasesNode, infoBaseInfo); - } - } + infoBases.forEach( + infoBaseInfo -> { + TreeItem infobaseItem = + Arrays.stream(infobasesNode.getItems()) + .filter(ibItem -> infoBaseInfo.getInfoBaseId().equals(getInfobaseId(ibItem))) + .findFirst() + .orElseGet(() -> addInfobaseItemInNode(infobasesNode, infoBaseInfo)); + + InfoBaseInfoShortExt infoBaseInfoFromItem = getInfobaseShortInfoExt(infobaseItem); + + // обновление порядкового номера базы из кластера + // имеет смысл делать только для старых элементов + if (infoBaseInfo.getIndex() != infoBaseInfoFromItem.getIndex()) { + infoBaseInfoFromItem.setIndex(infoBaseInfo.getIndex()); + } + // обновление представления инфобазы + // имеет смысл делать только для старых элементов + if (!infobaseItem.getText().equals(infoBaseInfoFromItem.getInfobaseDescription())) { + infobaseItem.setText(infoBaseInfoFromItem.getInfobaseDescription()); + } + }); - infobasesNode.setExpanded(ClusterProvider.getCommonConfig().isExpandInfobasesTree()); + infobasesNode.setExpanded(config.isExpandInfobasesTree()); } - private void fillWorkingProcessesInCluster(TreeItem clusterItem, Server server) { + private void updateWorkingProcessesInCluster(TreeItem clusterItem, Server server) { - TreeItem workingProcessesNode = null; - for (TreeItem treeItem : clusterItem.getItems()) { - if (treeItem.getData("Type") == TreeItemType.WORKINGPROCESS_NODE) { //$NON-NLS-1$ - workingProcessesNode = treeItem; - break; - } - } + UUID clusterId = getClusterId(clusterItem); + List workingProcesses = server.getWorkingProcesses(clusterId); + String wpNodeTitle = WorkingProcessInfoExtended.getNodeTitle(workingProcesses.size()); + + // поиск или создание узла рабочих процессов + TreeItem workingProcessesNode = + Arrays.stream(clusterItem.getItems()) + .filter(node -> node.getData("Type").equals(TreeItemType.WORKINGPROCESS_NODE)) + .findFirst() + .orElseGet(() -> addWorkingProcessNode(clusterItem, clusterId, wpNodeTitle)); - if (!ClusterProvider.getCommonConfig().isShowWorkingProcessesTree()) { + if (!config.isShowWorkingProcessesTree()) { + // TODO его в таком случае и создавать не надо шагом выше if (workingProcessesNode != null) { workingProcessesNode.dispose(); } return; } - if (workingProcessesNode == null) { - workingProcessesNode = new TreeItem(clusterItem, SWT.NONE); - workingProcessesNode.setData("Type", TreeItemType.WORKINGPROCESS_NODE); //$NON-NLS-1$ - workingProcessesNode.setImage(workingProcessesIcon); - workingProcessesNode.setChecked(false); - } - - UUID clusterId = getCurrentClusterId(workingProcessesNode); - List workingProcesses = server.getWorkingProcesses(clusterId); - - var workingProcessesNodeTitle = - String.format( - Messages.getString("ViewerArea.WorkingProcessesCount"), //$NON-NLS-1$ - workingProcesses.size()); - workingProcessesNode.setText(new String[] {workingProcessesNodeTitle}); + workingProcessesNode.setText(new String[] {wpNodeTitle}); + // если у кластера нет рабочих процессов, то у узла удаляем все элементы if (workingProcesses.isEmpty()) { - for (TreeItem workingProcess : workingProcessesNode.getItems()) { - workingProcess.dispose(); - } + Arrays.stream(workingProcessesNode.getItems()).forEach(Widget::dispose); return; } // удаление несуществующих элементов - for (TreeItem workingProcessItem : workingProcessesNode.getItems()) { - UUID currentWorkingProcessId = getCurrentWorkingProcessId(workingProcessItem); - List foundItems = - workingProcesses.stream() - .filter(c -> c.getWorkingProcessId().equals(currentWorkingProcessId)) - .collect(Collectors.toList()); - - if (foundItems.isEmpty()) { - workingProcessItem.dispose(); - } - } + Arrays.stream(workingProcessesNode.getItems()) + .forEach( + workingProcessItem -> { + UUID currentWorkingProcessId = getWorkingProcessId(workingProcessItem); + List foundItems = + workingProcesses.stream() + .filter(wp -> wp.getWorkingProcessId().equals(currentWorkingProcessId)) + .collect(Collectors.toList()); + if (foundItems.isEmpty()) { + workingProcessItem.dispose(); + } + }); // добавление новых элементов - for (IWorkingProcessInfo workingProcessInfo : workingProcesses) { - // wProcesses.forEach(workingProcessInfo -> { - - var itemFound = false; - for (TreeItem workingProcessItem : workingProcessesNode.getItems()) { - if (getCurrentWorkingProcessId(workingProcessItem) - .equals(workingProcessInfo.getWorkingProcessId())) { - itemFound = true; - break; - } - } - - if (!itemFound) { - addWorkingProcessItemInNode(workingProcessesNode, workingProcessInfo); - } - } + workingProcesses.forEach( + wpInfo -> { + TreeItem workingProcessItem = + Arrays.stream(workingProcessesNode.getItems()) + .filter( + wpItem -> wpInfo.getWorkingProcessId().equals(getWorkingProcessId(wpItem))) + .findFirst() + .orElseGet(() -> addWorkingProcessItemInNode(workingProcessesNode, wpInfo)); + }); } - private void fillWorkingServersInCluster(TreeItem clusterItem, Server server) { + private void updateWorkingServersInCluster(TreeItem clusterItem, Server server) { - TreeItem workingServersNode = null; - for (TreeItem treeItem : clusterItem.getItems()) { - if (treeItem.getData("Type") == TreeItemType.WORKINGSERVER_NODE) { //$NON-NLS-1$ - workingServersNode = treeItem; - break; - } - } + UUID clusterId = getClusterId(clusterItem); + List workingServers = server.getWorkingServers(clusterId); + String wsNodeTitle = WorkingServerInfoExtended.getNodeTitle(workingServers.size()); - if (!ClusterProvider.getCommonConfig().isShowWorkingServersTree()) { + // поиск или создание узла рабочих процессов + TreeItem workingServersNode = + Arrays.stream(clusterItem.getItems()) + .filter(node -> node.getData("Type").equals(TreeItemType.WORKINGSERVER_NODE)) + .findFirst() + .orElseGet(() -> addWorkingServerNode(clusterItem, clusterId, wsNodeTitle)); + + if (!config.isShowWorkingServersTree()) { + // TODO его в таком случае и создавать не надо шагом выше if (workingServersNode != null) { workingServersNode.dispose(); } return; } - if (workingServersNode == null) { - workingServersNode = new TreeItem(clusterItem, SWT.NONE); - workingServersNode.setData("Type", TreeItemType.WORKINGSERVER_NODE); //$NON-NLS-1$ - workingServersNode.setImage(workingServerIcon); - workingServersNode.setChecked(false); - } - - UUID clusterId = getCurrentClusterId(workingServersNode); - List workingServers = server.getWorkingServers(clusterId); - - var workingServerNodeTitle = - String.format( - Messages.getString("ViewerArea.WorkingServersCount"), //$NON-NLS-1$ - workingServers.size()); - workingServersNode.setText(new String[] {workingServerNodeTitle}); + workingServersNode.setText(new String[] {wsNodeTitle}); + // если у кластера нет рабочих серверов, то у узла удаляем все элементы if (workingServers.isEmpty()) { - for (TreeItem workingServerItem : workingServersNode.getItems()) { - workingServerItem.dispose(); - } + Arrays.stream(workingServersNode.getItems()).forEach(Widget::dispose); return; } // удаление несуществующих элементов - for (TreeItem workingServerItem : workingServersNode.getItems()) { - UUID currentWorkingServerId = getCurrentWorkingServerId(workingServerItem); - List foundItems = - workingServers.stream() - .filter(c -> c.getWorkingServerId().equals(currentWorkingServerId)) - .collect(Collectors.toList()); - - if (foundItems.isEmpty()) { - workingServerItem.dispose(); - } - } + Arrays.stream(workingServersNode.getItems()) + .forEach( + workingServerItem -> { + UUID currentWorkingProcessId = getWorkingProcessId(workingServerItem); + List foundItems = + workingServers.stream() + .filter(ws -> ws.getWorkingServerId().equals(currentWorkingProcessId)) + .collect(Collectors.toList()); + if (foundItems.isEmpty()) { + workingServerItem.dispose(); + } + }); // добавление новых элементов - for (IWorkingServerInfo workingServerInfo : workingServers) { - // wServers.forEach(workingServerInfo -> { - - var itemFound = false; - for (TreeItem workingServerItem : workingServersNode.getItems()) { - if (getCurrentWorkingServerId(workingServerItem) - .equals(workingServerInfo.getWorkingServerId())) { - itemFound = true; - break; - } - } + workingServers.forEach( + wsInfo -> { + TreeItem workingServerItem = + Arrays.stream(workingServersNode.getItems()) + .filter(wpItem -> wsInfo.getWorkingServerId().equals(getWorkingServerId(wpItem))) + .findFirst() + .orElseGet(() -> addWorkingServerItemInNode(workingServersNode, wsInfo)); + }); + } - if (!itemFound) { - addWorkingServerItemInNode(workingServersNode, workingServerInfo); - } - } + private void updateNode( + TreeItem clusterItem, Class clazz, Server server) { + + UUID clusterId = getClusterId(clusterItem); } - private TreeItem addServerItemInServersTree(Server server) { + private void fillTabs() { + + Table currentTable = getCurrentTable(); + if (currentTable == null) { + return; + } - var item = new TreeItem(serversTree, SWT.NONE); - item.setText(new String[] {server.getTreeDescription()}); - item.setData("Type", TreeItemType.SERVER); //$NON-NLS-1$ - item.setData(SERVER_INFO, server); + Server server = getCurrentServer(); + if (server == null) { + return; + } - item.setImage(server.isConnected() ? serverIconUp : serverIcon); + UUID clusterId = getCurrentClusterId(); + UUID infobaseId = getInfobaseId(currentTreeItem); + UUID workingProcessId = getCurrentWorkingProcessId(); + TreeItemType treeItemType = getTreeItemType(currentTreeItem); // TODO currentHighlightingType - return item; - } + clearTabs(); + List list = null; - private TreeItem addClusterItemInServersTree(TreeItem serverItem, IClusterInfo clusterInfo) { + // TODO getSessionsExtendedInfo, getConnectionsExtendedInfo и др. + // заменить на одну?, определяемую через map + if (currentTab.equals(tabSessions)) { + list = server.getSessionsExtendedInfo(treeItemType, clusterId, workingProcessId, infobaseId); - var clusterTitle = - String.format("%s (%s)", clusterInfo.getName(), clusterInfo.getMainPort()); //$NON-NLS-1$ + } else if (currentTab.equals(tabConnections)) { + list = + server.getConnectionsExtendedInfo(treeItemType, clusterId, workingProcessId, infobaseId); - var clusterItem = new TreeItem(serverItem, SWT.NONE); - clusterItem.setText(new String[] {clusterTitle}); - clusterItem.setData("Type", TreeItemType.CLUSTER); //$NON-NLS-1$ - clusterItem.setData(CLUSTER_ID, clusterInfo.getClusterId()); - clusterItem.setImage(clusterIcon); + } else if (currentTab.equals(tabLocks)) { + list = server.getLocksExtendedInfo(treeItemType, clusterId, infobaseId); - return clusterItem; - } + } else if (currentTab.equals(tabWorkingProcesses)) { + list = server.getWorkingProcessesExtendedInfo(treeItemType, clusterId, workingProcessId); - private void addInfobaseItemInInfobaseNode(TreeItem infobaseNode, IInfoBaseInfoShort ibInfo) { + } else if (currentTab.equals(tabWorkingServers)) { + list = server.getWorkingServersExtendedInfo(treeItemType, clusterId); - String infobaseTitle; - if (ClusterProvider.getCommonConfig().isShowInfobaseDescription() && !ibInfo.getDescr().isBlank()) { - infobaseTitle = String.format("%s (%s)", ibInfo.getName(), ibInfo.getDescr()); //$NON-NLS-1$ } else { - infobaseTitle = String.format("%s", ibInfo.getName()); //$NON-NLS-1$ + return; } - var item = new TreeItem(infobaseNode, SWT.NONE); - item.setText(new String[] {infobaseTitle}); - item.setData("Type", TreeItemType.INFOBASE); //$NON-NLS-1$ - item.setData(INFOBASE_ID, ibInfo.getInfoBaseId()); - item.setImage(0, infobaseIcon); - item.setChecked(false); - - // item.setImage(1, ibInfo.isSessionsDenied() ? lockUsersIcon : null); - + BaseInfoExtended.updateTabText(linksTablesToExtendedClass.get(currentTab), list.size()); + list.forEach(item -> item.addToTable(currentTable)); } - private void addWorkingProcessItemInNode(TreeItem wpNodeItem, IWorkingProcessInfo wpInfo) { - - var itemTitle = - String.format("%s (%s)", wpInfo.getHostName(), wpInfo.getMainPort()); //$NON-NLS-1$ + private void highlightTreeItem(TreeItem treeItem) { + currentTreeItem = treeItem; + currentTreeItem.setFont(fontBold); + } - var item = new TreeItem(wpNodeItem, SWT.NONE); - item.setText(new String[] {itemTitle}); - item.setData("Type", TreeItemType.WORKINGPROCESS); //$NON-NLS-1$ - item.setData(WORKINGPROCESS_ID, wpInfo.getWorkingProcessId()); - item.setImage(workingProcessIcon); - item.setChecked(false); + private void setActiveContextMenuInTree(TreeItem treeItem) { + TreeItemType currentContextMenuItem = getTreeItemType(treeItem); + serversTree.setMenu(serversTreeContextMenus.get(currentContextMenuItem)); } - private void addWorkingServerItemInNode(TreeItem wsNodeItem, IWorkingServerInfo wpInfo) { + private void clearTabs() { - var itemTitle = - String.format("%s (%s)", wpInfo.getHostName(), wpInfo.getMainPort()); //$NON-NLS-1$ + // BaseInfoExtended.resetTabsTextCount(); - var item = new TreeItem(wsNodeItem, SWT.NONE); - item.setText(new String[] {itemTitle}); - item.setData("Type", TreeItemType.WORKINGSERVER); //$NON-NLS-1$ - item.setData(WORKINGSERVER_ID, wpInfo.getWorkingServerId()); - item.setImage(workingServerIcon); - item.setChecked(false); + getTable(tabSessions).removeAll(); + getTable(tabConnections).removeAll(); + getTable(tabLocks).removeAll(); + getTable(tabWorkingProcesses).removeAll(); + getTable(tabWorkingServers).removeAll(); } - private void addSessionInTable( - Server server, - UUID clusterId, - UUID infobaseId, - ISessionInfo sessionInfo, - List connections) { - - SessionInfoExtended sessionInfoExtended = - new SessionInfoExtended( - server, clusterId, infobaseId, sessionInfo, connections, sessionColumnsMap); - - var sessionItem = new TableItem(tableSessions, SWT.NONE); - sessionItem.setText(sessionInfoExtended.getExtendedInfo()); - sessionItem.setData(SERVER_INFO, server); - sessionItem.setData(CLUSTER_ID, clusterId); - sessionItem.setData(SESSION_ID, sessionInfo.getSid()); // sessionInfo.getSessionId() ??? - // agentConnection.getSessionInfo(clusterId, sid); ошибка... - sessionItem.setData("sessionInfo", sessionInfo); //$NON-NLS-1$ - sessionItem.setImage(userIcon); - sessionItem.setChecked(false); - - if (IInfoExtended.highlightItem(sessionInfo.getStartedAt())) { - sessionItem.setForeground(newItemColor); - } - - Config commonConfig = ClusterProvider.getCommonConfig(); - if (commonConfig.isShadowSleepSessions() && sessionInfo.getHibernate()) { - sessionItem.setForeground(shadowItemColor); + private void clickItemInServerTree(int mouseButton) { + // TODO запутанный метод + // его надо переделать, переименовать, переосмыслить места вызова + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; } - String id = sessionItem.getText(1).concat("*").concat(sessionItem.getText(2)); //$NON-NLS-1$ - if (watchedSessions.contains(id)) { - sessionItem.setChecked(true); - sessionItem.setForeground(watchedSessionColor); - } + TreeItem treeItem = item[0]; - switch (sessionInfo.getAppId()) { - case Server.THIN_CLIENT: - case Server.THICK_CLIENT: - case Server.DESIGNER: - sessionItem.setImage(sessionInfo.getHibernate() ? sleepUserIcon : userIcon); + switch (mouseButton) { + case 1: // left click + if (treeItem.equals(currentTreeItem)) { // Objects.nonNull(treeItem) && ??? + return; + } + saveCurrentSelectedData(treeItem); + setEnableToolbarItems(); + fillTabs(); break; - case Server.SERVER_CONSOLE: - case Server.RAS_CONSOLE: - case Server.JOBSCHEDULER: - sessionItem.setImage(serviceIcon); + + case 3: // right click + setActiveContextMenuInTree(treeItem); break; + default: - sessionItem.setImage(sessionInfo.getHibernate() ? sleepUserIcon : userIcon); + break; } } - private void addConnectionInTable( - Server server, - UUID clusterId, - UUID infobaseId, - IInfoBaseConnectionShort connectionInfo, - List workingProcesses) { - - ConnectionInfoExtended sessionInfoExtended = - new ConnectionInfoExtended( - server, clusterId, infobaseId, connectionInfo, workingProcesses, connectionColumnsMap); - - var connectionItem = new TableItem(tableConnections, SWT.NONE); - connectionItem.setText(sessionInfoExtended.getExtendedInfo()); - connectionItem.setData(SERVER_INFO, server); - connectionItem.setData(CLUSTER_ID, clusterId); - connectionItem.setData(WORKINGPROCESS_ID, connectionInfo.getWorkingProcessId()); - connectionItem.setData(INFOBASE_ID, connectionInfo.getInfoBaseId()); - connectionItem.setData(CONNECTION_ID, connectionInfo.getInfoBaseConnectionId()); - connectionItem.setImage(connectionIcon); - connectionItem.setChecked(false); - - if (IInfoExtended.highlightItem(connectionInfo.getConnectedAt())) { - connectionItem.setForeground(newItemColor); - } + private Table getCurrentTable() { + // return linksTabToTables.get(currentTab); + return ((Table) currentTab.getControl()); } - private void addLocksInTable( - Server server, - UUID clusterId, - UUID infobaseId, - IObjectLockInfo lockInfo, - List sessionsInfo, - List connections) { - - LockInfoExtended lockInfoExtended = - new LockInfoExtended( - server, clusterId, infobaseId, lockInfo, sessionsInfo, connections, lockColumnsMap); - - var lockItem = new TableItem(tableLocks, SWT.NONE); - lockItem.setText(lockInfoExtended.getExtendedInfo()); - lockItem.setData(CLUSTER_ID, clusterId); - lockItem.setData(INFOBASE_ID, infobaseId); - lockItem.setData("IObjectLockInfo", lockInfo); //$NON-NLS-1$ - lockItem.setImage(locksIcon); - lockItem.setChecked(false); - - if (IInfoExtended.highlightItem(lockInfo.getLockedAt())) { - lockItem.setForeground(newItemColor); - } + private Table getTable(TabItem tab) { + return ((Table) tab.getControl()); } - private void addWorkingProcessInTable( - Server server, UUID clusterId, IWorkingProcessInfo workingProcessInfo) { - - WorkingProcessInfoExtended wpInfoExtended = - new WorkingProcessInfoExtended(server, clusterId, workingProcessInfo, wpColumnsMap); - - var wpItem = new TableItem(tableWorkingProcesses, SWT.NONE); - wpItem.setText(wpInfoExtended.getExtendedInfo()); - wpItem.setData(SERVER_INFO, server); - wpItem.setData(CLUSTER_ID, clusterId); - wpItem.setData(WORKINGPROCESS_ID, workingProcessInfo.getWorkingProcessId()); - wpItem.setImage(workingProcessIcon); - wpItem.setChecked(false); - - if (IInfoExtended.highlightItem(workingProcessInfo.getStartedAt())) { - wpItem.setForeground(newItemColor); - } + private ColumnProperties getColumnProperties(Class clazz) { + return config.getColumnsProperties(clazz); } - private void addWorkingServerInTable( - Server server, UUID clusterId, IWorkingServerInfo workingServerInfo) { - - WorkingServerInfoExtended wsInfoExtended = - new WorkingServerInfoExtended(server, clusterId, workingServerInfo, wsColumnsMap); - - var connectionItem = new TableItem(tableWorkingServers, SWT.NONE); - connectionItem.setText(wsInfoExtended.getExtendedInfo()); - connectionItem.setData(SERVER_INFO, server); - connectionItem.setData(CLUSTER_ID, clusterId); - connectionItem.setData(WORKINGSERVER_ID, workingServerInfo.getWorkingServerId()); - connectionItem.setImage(workingServerIcon); - connectionItem.setChecked(false); + private ColumnProperties getColumnProperties(TabItem tab) { + return config.getColumnsProperties(linksTablesToExtendedClass.get(tab)); } - private void addTableColumn( - Table table, String text, int[] columnWidth, boolean[] columnVisible) { // TODO properties - var newColumn = new TableColumn(table, SWT.NONE); - newColumn.setText(text); - newColumn.setMoveable(true); - newColumn.setAlignment(SWT.RIGHT); - - int numOfColumn = table.getColumnCount() - 1; + private void saveCurrentSelectedData(TreeItem treeItem) { - if (columnVisible != null && columnVisible[numOfColumn]) { - newColumn.setResizable(true); - newColumn.setWidth( - // columnWidth == null //TODO нужно ли это еще - // || columnWidth.length <= table.getColumnCount() - // || - columnWidth[numOfColumn] == 0 ? 100 : columnWidth[numOfColumn]); - } else { - newColumn.setResizable(false); - newColumn.setWidth(0); + if (currentTreeItem != null && !currentTreeItem.isDisposed()) { + currentTreeItem.setFont(fontNormal); } + currentTreeItem = treeItem; - newColumn.addListener(SWT.Move, columnMoveListener); - newColumn.addListener(SWT.Resize, columnResizeListener); - // newColumn.addControlListener(columnResizeListener); + currentHighlightingType = getTreeItemType(treeItem); + currentHighlightingData = null; - } + switch (currentHighlightingType) { + case SERVER: + currentHighlightingData = getCurrentServer(); + break; - private TreeItemType getTreeItemType(TreeItem item) { - return (TreeItemType) item.getData("Type"); //$NON-NLS-1$ - } + case CLUSTER: + case INFOBASE_NODE: + case WORKINGPROCESS_NODE: + case WORKINGSERVER_NODE: + currentHighlightingData = getCurrentClusterId(); + break; - private Server getCurrentServerConfig(TreeItem item) { + case INFOBASE: + currentHighlightingData = getInfobaseId(treeItem); + break; - if (getTreeItemType(item) == TreeItemType.SERVER) { - return (Server) item.getData(SERVER_INFO); - } + case WORKINGPROCESS: + currentHighlightingData = getCurrentWorkingProcessId(); + break; - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { + case WORKINGSERVER: + currentHighlightingData = getCurrentWorkingServerId(); + break; - if (getTreeItemType(parentItem) == TreeItemType.SERVER) { - return (Server) parentItem.getData(SERVER_INFO); - } else { - parentItem = parentItem.getParentItem(); - } + default: + break; } - throw new IllegalStateException("Error get ServerConfig from item."); //$NON-NLS-1$ - // return null; + highlightTreeItem(treeItem); } - private UUID getCurrentClusterId(TreeItem item) { - - if (getTreeItemType(item) == TreeItemType.CLUSTER) { - return (UUID) item.getData(CLUSTER_ID); - } - - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { - - if (getTreeItemType(parentItem) == TreeItemType.CLUSTER) { - return (UUID) parentItem.getData(CLUSTER_ID); - } else { - parentItem = parentItem.getParentItem(); - } - } - return null; + private void setEnableToolbarItems() { + // включение/выключение активности кнопок тулбара + addToolbarItem.setEnabled(toolbarCreateListeners.get(currentHighlightingType) != null); + editToolbarItem.setEnabled(toolbarEditListeners.get(currentHighlightingType) != null); + deleteToolbarItem.setEnabled(toolbarDeleteListeners.get(currentHighlightingType) != null); } - private UUID getCurrentWorkingProcessId(TreeItem item) { + ////////////////////////////////////////////////////////////////////////// + // LISTENERS - if (getTreeItemType(item) == TreeItemType.WORKINGPROCESS) { - return (UUID) item.getData(WORKINGPROCESS_ID); - } + MouseAdapter treeItemMouseClickListener = + new MouseAdapter() { + @Override + public void mouseDown(MouseEvent e) { + clickItemInServerTree(e.button); + } - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { + @Override + public void mouseDoubleClick(MouseEvent e) { + TreeItem[] items = ((Tree) e.widget).getSelection(); + if (items.length == 0) { + return; + } - if (getTreeItemType(parentItem) == TreeItemType.WORKINGPROCESS) { - return (UUID) parentItem.getData(WORKINGPROCESS_ID); - } else { - parentItem = parentItem.getParentItem(); - } - } - return null; - } + SelectionAdapter listener = toolbarEditListeners.get(currentHighlightingType); + if (listener != null) { + listener.widgetSelected(null); + } + } + }; - private UUID getCurrentWorkingServerId(TreeItem item) { + SelectionAdapter openSettingsListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { - if (getTreeItemType(item) == TreeItemType.WORKINGSERVER) { - return (UUID) item.getData(WORKINGSERVER_ID); - } + SettingsDialog dialog; + try { + dialog = new SettingsDialog(getParent().getDisplay().getActiveShell()); + } catch (Exception excp) { + LOGGER.error("Error init SettingsDialog", excp); //$NON-NLS-1$ + return; + } + int dialogResult = dialog.open(); + if (dialogResult == 0) { + config.saveConfig(); + for (TreeItem item : serversTree.getItems()) { + updateClustersInTree(item); + } + } + } + }; - TreeItem parentItem = item.getParentItem(); - while (parentItem != null) { + SelectionAdapter showAboutDialogListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { - if (getTreeItemType(parentItem) == TreeItemType.WORKINGSERVER) { - return (UUID) parentItem.getData(WORKINGSERVER_ID); - } else { - parentItem = parentItem.getParentItem(); - } - } - return null; - } + AboutDialog dialog; + try { + dialog = new AboutDialog(getParent().getDisplay().getActiveShell()); + } catch (Exception excp) { + LOGGER.error("Error init AboutDialog", excp); //$NON-NLS-1$ + return; + } + dialog.open(); + } + }; - private UUID getCurrentInfobaseId(TreeItem item) { - if (getTreeItemType(item) == TreeItemType.INFOBASE) { - return (UUID) item.getData(INFOBASE_ID); - } else { - return null; - } - } + SelectionAdapter findNewServersListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + List newServers = clusterProvider.findNewServers(); + if (!newServers.isEmpty()) { + fillServersList(); + } + } + }; - private void disposeTreeItemWithChildren(TreeItem item) { - TreeItem[] childItems = item.getItems(); - for (TreeItem childItem : childItems) { - disposeTreeItemWithChildren(childItem); - childItem.dispose(); - } - item.dispose(); - } + SelectionAdapter connectAllServersListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { - private Image getImage(String name) { - return new Image( - getParent().getDisplay(), - this.getClass().getResourceAsStream("/icons/".concat(name))); //$NON-NLS-1$ - } + TreeItem[] serversItem = serversTree.getItems(); + for (TreeItem serverItem : serversItem) { + Server server = getServer(serverItem); + if (server != null && !server.isConnected()) { + connectServerItem(serverItem, true); + } + } + } + }; + + SelectionAdapter disconnectAllServersListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + TreeItem[] serversItem = serversTree.getItems(); + for (TreeItem serverItem : serversItem) { + disconnectServerItem(serverItem); + } + } + }; + + Listener setActiveConnectActionListener = + new Listener() { + @Override + public void handleEvent(Event event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + if (server == null) { + return; + } + + boolean serverIsConnected = server.isConnected(); + boolean serverIsErrorConnected = !server.getConnectionError().isBlank(); + + MenuItem[] menuItems = serverMenu.getItems(); + + for (MenuItem menuItem : menuItems) { + if (Boolean.TRUE.equals(menuItem.getData("connectItem"))) { + menuItem.setEnabled(!serverIsConnected); + } + if (Boolean.TRUE.equals(menuItem.getData("disconnectItem"))) { + menuItem.setEnabled(serverIsConnected); + } + if (Boolean.TRUE.equals(menuItem.getData("connectionErrorItem"))) { + menuItem.setEnabled(serverIsErrorConnected); + } + + } + } + }; + + SelectionAdapter connectToServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + connectServerItem(item[0], false); + } + }; + + SelectionAdapter disconnectFromServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + disconnectServerItem(item[0]); + } + }; + + SelectionAdapter showServerConnectionErrorListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + if (server == null) { + return; + } + + var messageBox = new MessageBox(Display.getDefault().getActiveShell()); + messageBox.setMessage(server.getConnectionError()); + messageBox.open(); + } + }; + + SelectionAdapter toolbarListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + if (currentHighlightingType == null) { // пустое дерево + addServerListener.widgetSelected(event); + return; + } + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Map currListener = null; + String text = ((ToolItem) event.widget).getText(); + if (Strings.CONTEXT_MENU_CREATE.equals(text)) { + currListener = toolbarCreateListeners; + } else if (Strings.CONTEXT_MENU_EDIT.equals(text)) { + currListener = toolbarEditListeners; + } else if (Strings.CONTEXT_MENU_DELETE.equals(text)) { + currListener = toolbarDeleteListeners; + } else { + return; + } + + SelectionAdapter listener = currListener.get(currentHighlightingType); + if (listener != null) { + listener.widgetSelected(event); + } + } + }; + + SelectionAdapter addServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + Server newServer = config.createNewServer(); + ServerDialog dialog; + try { + dialog = new ServerDialog(getParent().getDisplay().getActiveShell(), newServer); + } catch (Exception excp) { + LOGGER.error("Error init ServerDialog for new server", excp); //$NON-NLS-1$ + return; + } + + int dialogResult = dialog.open(); + if (dialogResult != 0) { + return; + } + + config.addNewServer(newServer); + TreeItem newServerItem = addServerItemInServersTree(newServer); + updateClustersInTree(newServerItem); + } + }; + + SelectionAdapter editServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + TreeItem serverItem = item[0]; + Server server = getServer(serverItem); + if (server == null) { + return; + } + + ServerDialog dialog; + try { + dialog = new ServerDialog(getParent().getDisplay().getActiveShell(), server); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error( + "Error init ServerDialog for server {}", //$NON-NLS-1$ + server.getTreeTitle(), + excp); + return; + } + + int dialogResult = dialog.open(); + if (dialogResult == 0) { + // перерисовать в дереве + serverItem.setText(new String[] {server.getTreeTitle()}); + config.saveConfig(); + updateClustersInTree(serverItem); + } + } + }; + + SelectionAdapter updateServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + updateClustersInTree(item[0]); + } + }; + + SelectionAdapter serversMoveUpListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + TreeItem[] selectItems = serversTree.getSelection(); + if (selectItems.length == 0) { + return; + } + int currentIndex = selectItems[0].getParent().indexOf(selectItems[0]); + if (currentIndex == 0) { + return; + } + + Server server = getServer(selectItems[0]); + if (server == null) { + return; + } + + TreeItem newItem = addServerItemInServersTree(server, currentIndex - 1); + serversTree.select(newItem); + + selectItems[0].dispose(); + updateClustersInTree(newItem); // TODO а если сразу за addServerItemInServersTree + } + }; + + SelectionAdapter serversMoveDownListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + TreeItem[] selectItems = serversTree.getSelection(); + if (selectItems.length == 0) { + return; + } + int currentIndex = selectItems[0].getParent().indexOf(selectItems[0]); + + if (currentIndex == serversTree.getItemCount() - 1) { + return; + } + + Server server = getServer(selectItems[0]); + if (server == null) { + return; + } + + TreeItem newItem = addServerItemInServersTree(server, currentIndex + 2); + serversTree.select(newItem); + + selectItems[0].dispose(); + updateClustersInTree(newItem); + } + }; + + SelectionAdapter serversSortListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + Server selectedServer = getServer(serversTree.getSelection()[0]); + + // надо разобраться с терминами currentTreeItem: + // selectedTreeItem, clickedTreeItem, rightClickedTreeItem ??? + + // запоминаем текущий подсвеченный элемент дерева + // saveCurrentSelectedTreeItem(); + + TreeItem[] items = serversTree.getItems(); + for (int i = 1; i < items.length; i++) { + Server secondServer = getServer(items[i]); + if (secondServer == null) { + continue; + } + + for (int j = 0; j < i; j++) { + Server firstServer = getServer(items[j]); + if (firstServer == null) { + continue; + } + + if (firstServer.compareTo(secondServer) > 0) { + + TreeItem newItem = addServerItemInServersTree(secondServer, j); + + // возможно, будет лучше сначала упорядочить все, а уже потом пройтись циклом по + // серверам для перезаполнения дочерних элементов + // ибо при многократном передвигании подключенного сервера заполнение дочерних + // выполнится несколько лишних раз + updateClustersInTree(newItem); + + items[i].dispose(); + items = serversTree.getItems(); + break; + } + } + } + items = serversTree.getItems(); + for (int i = 0; i < items.length; i++) { + + // updateClustersInTree(items[i]); + // восстановление элемента, выделенного правим кликом + Server server = getServer(items[i]); + if (server == selectedServer) { + serversTree.select(items[i]); + break; + } + + // восстановление подсвеченного (текущего) элемента + + } + } + }; + + SelectionAdapter deleteServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + int answer = + Helper.showQuestionBox( + Messages.getString("ViewerArea.DeleteServerQuestion")); //$NON-NLS-1$ + + if (answer == SWT.YES) { + final TreeItem serverItem = item[0]; + Server server = getServer(serverItem); + config.removeServer(server); + serverItem.dispose(); + } + } + }; + + SelectionAdapter createClusterListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + + ClusterDialog dialog; + try { + dialog = new ClusterDialog(getParent().getDisplay().getActiveShell(), server, null); + } catch (Exception excp) { + LOGGER.error( + "Error init ClusterDialog for new cluster", //$NON-NLS-1$ + excp); + return; + } + + int dialogResult = dialog.open(); + if (dialogResult == 0) { + updateClustersInTree(item[0].getParentItem()); + } + } + }; + + SelectionAdapter editClusterListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + UUID clusterId = getClusterId(item[0]); + + ClusterDialog dialog; + try { + dialog = + new ClusterDialog(getParent().getDisplay().getActiveShell(), server, clusterId); + } catch (Exception excp) { + LOGGER.error( + "Error init ClusterDialog for cluster id {}", //$NON-NLS-1$ + clusterId, + excp); + return; + } + + int dialogResult = dialog.open(); + if (dialogResult == 0) { + updateClustersInTree(item[0]); + } + } + }; + + SelectionAdapter updateClusterListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + updateNodesOfCluster(item[0], server); + } + }; + + SelectionAdapter deleteClusterListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + final TreeItem clusterItem = item[0]; + + Server server = getServer(clusterItem); + UUID clusterId = getClusterId(clusterItem); + if (server == null || clusterId == null) { + return; + } + + int answer = + Helper.showQuestionBox( + Messages.getString("ViewerArea.DeleteClusterQuestion")); //$NON-NLS-1$ + + if (answer == SWT.YES && server.unregCluster(clusterId)) { + clusterItem.dispose(); + } + } + }; + + SelectionAdapter createInfobaseListener = + // TODO вызывается из контекстного меню и из тулбара + // нет ли ошибки serversTree.getSelection() при вызове из тулбара + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + UUID clusterId = getClusterId(item[0]); + UUID sampleInfobaseId = getInfobaseId(item[0]); + if (server == null || clusterId == null) { + return; + } + + CreateInfobaseDialog dialog; + try { + dialog = + new CreateInfobaseDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, sampleInfobaseId); + } catch (Exception excp) { + LOGGER.error("Error in CreateInfobaseDialog", excp); //$NON-NLS-1$ + return; + } + + int dialogResult = dialog.open(); + if (dialogResult == 0) { + TreeItem clusterItem = + sampleInfobaseId == null + ? item[0].getParentItem() + : item[0].getParentItem().getParentItem(); + updateInfobasesOfCluster(clusterItem, server); + + } + } + }; + + SelectionAdapter editInfobaseListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + final TreeItem infobaseItem = item[0]; + + Server server = getServer(infobaseItem); + UUID clusterId = getClusterId(infobaseItem); + UUID infobaseId = getInfobaseId(infobaseItem); + if (server == null || clusterId == null || infobaseId == null) { + return; + } + + InfobaseDialog dialog; + try { + dialog = + new InfobaseDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); + } catch (Exception excp) { + excp.printStackTrace(); + return; + } + + int dialogResult = dialog.open(); + if (dialogResult == 0) { + InfoBaseInfoShortExt ibInfo = + new InfoBaseInfoShortExt( + server.getInfoBaseShortInfo(clusterId, infobaseId), 0, false); + + // обновление представления инфобазы + if (!infobaseItem.getText().equals(ibInfo.getInfobaseDescription())) { + infobaseItem.setText(ibInfo.getInfobaseDescription()); + } + } + } + }; + + SelectionAdapter deleteInfobaseListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + final TreeItem infobaseItem = item[0]; + + Server server = getServer(infobaseItem); + UUID clusterId = getClusterId(infobaseItem); + UUID infobaseId = getInfobaseId(infobaseItem); + if (server == null || clusterId == null || infobaseId == null) { + return; + } + + DropInfobaseDialog dialog; + try { + dialog = + new DropInfobaseDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, infobaseId); + } catch (Exception excp) { + excp.printStackTrace(); + return; + } + + int dialogResult = dialog.open(); + if (dialogResult == 0) { + final TreeItem clusterItem = infobaseItem.getParentItem().getParentItem(); + infobaseItem.dispose(); + updateInfobasesOfCluster(clusterItem, server); + } + } + }; + + SelectionAdapter updateInfobasesListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + if (server == null) { + return; + } + + updateInfobasesOfCluster(item[0].getParentItem(), server); + } + }; + + Listener setActiveInfobaseFavoritesActionListener = + new Listener() { + @Override + public void handleEvent(Event event) { + + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + if (server == null) { + return; + } + + InfoBaseInfoShortExt ib = getInfobaseShortInfoExt(item[0]); + String favoritesActionTitle = + server.infobaseIsFavorite(ib) + ? Strings.CONTEXT_MENU_DELETE_FROM_FAVORITES + : Strings.CONTEXT_MENU_ADD_IN_FAVORITES; + + MenuItem[] menuItems = ((Menu) event.widget).getItems(); + for (MenuItem menuItem : menuItems) { + if (Boolean.TRUE.equals(menuItem.getData("favoritesItem"))) { + menuItem.setText(favoritesActionTitle); + } + } + } + }; + + SelectionAdapter addInfobaseToFavoritesListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + + Server server = getServer(item[0]); + InfoBaseInfoShortExt ib = getInfobaseShortInfoExt(item[0]); + + if (server == null || ib == null) { + return; + } - private void connectToAllServers(boolean connectAll) { + server.changeInfobaseFavoriteState(ib); + item[0].setImage(ib.getIcon()); - TreeItem[] serversItem = serversTree.getItems(); + if (config.getInfobasesSortDirection() == InfobasesSortDirection.BY_FAVORITES_AND_NAME) { + sortInfobasesListener.widgetSelected(null); + } + } + }; - for (TreeItem serverItem : serversItem) { - Server server = getCurrentServerConfig(serverItem); - if ((connectAll || server.getAutoconnect()) && !server.isConnected()) { - connectServerItem(serverItem, true); - } - } - } + SelectionAdapter sortInfobasesListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { - private void diconnectFromAllServers() { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } + TreeItem ibNode = item[0]; + if ((TreeItemType) ibNode.getData("Type") == TreeItemType.INFOBASE) { //$NON-NLS-1$ + ibNode = item[0].getParentItem(); + } - TreeItem[] serversItem = serversTree.getItems(); + TreeItem[] items = ibNode.getItems(); - for (TreeItem serverItem : serversItem) { - disconnectServerItem(serverItem); - } - } + if (event != null && !(event.widget.getData() instanceof InfobasesSortDirection)) { + return; + } - private void connectServerItem(TreeItem serverItem, boolean silentMode) { + if (event != null) { + config.setInfobasesSortDirection((InfobasesSortDirection) event.widget.getData()); + } - // async не работает асинхронно - serverItem.setImage(serverIconConnecting); - Display.getDefault() - .asyncExec( - new Runnable() { + for (int i = 1; i < items.length; i++) { + InfoBaseInfoShortExt secondIb = getInfobaseShortInfoExt(items[i]); - @Override - public void run() { + for (int j = 0; j < i; j++) { + InfoBaseInfoShortExt firstIb = getInfobaseShortInfoExt(items[j]); - Server server = getCurrentServerConfig(serverItem); - server.connectToServer(false, silentMode); + if (firstIb != null && secondIb != null && firstIb.compareTo(secondIb) > 0) { + addInfobaseItemInNode(ibNode, secondIb, j); - serverItem.setImage(server.isConnected() ? serverIconUp : serverIconDown); - serverItem.setText(new String[] {server.getTreeDescription()}); - updateClustersInTree(serverItem); + items[i].dispose(); + items = ibNode.getItems(); + break; } - }); - } - - private void disconnectServerItem(TreeItem serverItem) { - Server server = getCurrentServerConfig(serverItem); - server.disconnectFromAgent(); - serverItem.setImage(serverIcon); - - TreeItem[] clusterItems = serverItem.getItems(); - for (TreeItem clusterItem : clusterItems) { - disposeTreeItemWithChildren(clusterItem); - } - } + } + } + } + }; - private void fillTabs(TreeItem treeItem) { + SelectionAdapter lockUsersListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } - highlightTreeItem(treeItem); + TreeItem selectItem = item[0]; - Server server; - UUID clusterId; - UUID infobaseId; - UUID workingProcessId; + Server server = getServer(selectItem); + UUID clusterId = getClusterId(selectItem); + UUID infobaseId = getInfobaseId(selectItem); + if (server == null) { + return; + } - List sessions; - List connections; - List locks; - List workingProcesses; - List workingServers; + IInfoBaseInfo infoBaseInfo = server.getInfoBaseInfo(clusterId, infobaseId); + if (infoBaseInfo == null) { + return; + } - clearTabs(); - switch (getTreeItemType(treeItem)) { - case SERVER: - return; + infoBaseInfo.setScheduledJobsDenied(true); + infoBaseInfo.setSessionsDenied(true); + infoBaseInfo.setDeniedFrom(null); + infoBaseInfo.setDeniedTo(null); + infoBaseInfo.setDeniedMessage(""); //$NON-NLS-1$ + infoBaseInfo.setDeniedParameter(""); //$NON-NLS-1$ + infoBaseInfo.setPermissionCode(""); //$NON-NLS-1$ - case CLUSTER: - case INFOBASE_NODE: - case WORKINGPROCESS_NODE: - server = getCurrentServerConfig(treeItem); - clusterId = getCurrentClusterId(treeItem); - infobaseId = null; - - sessions = server.getSessions(clusterId); - connections = server.getConnectionsShort(clusterId); - locks = server.getLocks(clusterId); - workingProcesses = server.getWorkingProcesses(clusterId); - workingServers = server.getWorkingServers(clusterId); - break; + server.updateInfoBase(clusterId, infoBaseInfo); + } + }; - case WORKINGPROCESS: - server = getCurrentServerConfig(treeItem); - clusterId = getCurrentClusterId(treeItem); - infobaseId = null; - workingProcessId = getCurrentWorkingProcessId(treeItem); - - sessions = server.getWorkingProcessSessions(clusterId, workingProcessId); - connections = server.getWorkingProcessConnectionsShort(clusterId, workingProcessId); - locks = new ArrayList<>(); - // locks = serverConfig.getInfoBaseLocks(clusterInfo.getClusterId(), - // infoBaseInfo.getInfoBaseId()); - - workingProcesses = new ArrayList<>(); - workingProcesses.add(server.getWorkingProcessInfo(clusterId, workingProcessId)); - workingServers = server.getWorkingServers(clusterId); - break; + SelectionAdapter terminateAllSessionsListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } - case INFOBASE: - server = getCurrentServerConfig(treeItem); - clusterId = getCurrentClusterId(treeItem); - infobaseId = getCurrentInfobaseId(treeItem); + Server server = getServer(item[0]); + UUID clusterId = getClusterId(item[0]); + UUID infobaseId = getInfobaseId(item[0]); + if (server == null) { + return; + } - sessions = server.getInfoBaseSessions(clusterId, infobaseId); - connections = server.getInfoBaseConnectionsShort(clusterId, infobaseId); - locks = server.getInfoBaseLocks(clusterId, infobaseId); + server.terminateAllSessionsOfInfobase(clusterId, infobaseId, false); + } + }; - // TODO отметить рп обслуживающий базу - workingProcesses = server.getWorkingProcesses(clusterId); - workingServers = server.getWorkingServers(clusterId); - break; + SelectionAdapter terminateUsersSessionsListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } - default: - return; - } + Server server = getServer(item[0]); + UUID clusterId = getClusterId(item[0]); + UUID infobaseId = getInfobaseId(item[0]); + if (server == null) { + return; + } - tabSessions.setText( - String.format( - Messages.getString("ViewerArea.SessionsCount"), //$NON-NLS-1$ - sessions.size())); - tabConnections.setText( - String.format( - Messages.getString("ViewerArea.ConnectionsCount"), //$NON-NLS-1$ - connections.size())); - tabLocks.setText( - String.format( - Messages.getString("ViewerArea.LocksCount"), //$NON-NLS-1$ - locks.size())); - tabWorkingProcesses.setText( - String.format( - Messages.getString("ViewerArea.WorkingProcessesCount"), //$NON-NLS-1$ - workingProcesses.size())); - tabWorkingServers.setText( - String.format( - Messages.getString("ViewerArea.WorkingServersCount"), //$NON-NLS-1$ - workingServers.size())); - - if (currentTabitem.equals(tabSessions)) { - sessions.forEach( - session -> addSessionInTable(server, clusterId, infobaseId, session, connections)); - } else if (currentTabitem.equals(tabConnections)) { - connections.forEach( - connection -> - addConnectionInTable(server, clusterId, infobaseId, connection, workingProcesses)); - } else if (currentTabitem.equals(tabLocks)) { - locks.forEach( - lock -> addLocksInTable(server, clusterId, infobaseId, lock, sessions, connections)); - } else if (currentTabitem.equals(tabWorkingProcesses)) { - workingProcesses.forEach( - workingProcess -> addWorkingProcessInTable(server, clusterId, workingProcess)); - } else if (currentTabitem.equals(tabWorkingServers)) { - workingServers.forEach( - workingServer -> addWorkingServerInTable(server, clusterId, workingServer)); - } - } + server.terminateAllSessionsOfInfobase(clusterId, infobaseId, true); + } + }; - private void addMenuSeparator(Menu menu) { - new MenuItem(menu, SWT.SEPARATOR); - } + SelectionAdapter createWorkingServerListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + Table tableWorkingServers = getCurrentTable(); + Server server = getCurrentServer(); + UUID clusterId = getCurrentClusterId(); - private void highlightTreeItem(TreeItem treeItem) { - if (Objects.isNull(currentTreeItem) || !currentTreeItem.equals(treeItem)) { + if (server == null || clusterId == null) { + return; + } - if (Objects.nonNull(currentTreeItem) && !currentTreeItem.isDisposed()) { - currentTreeItem.setFont(fontNormal); - } - treeItem.setFont(fontBold); - currentTreeItem = treeItem; - } - } + WorkingServerDialog dialog; + try { + dialog = + new WorkingServerDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, null); + } catch (Exception excp) { + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + clusterId, + excp); + return; + } - private void setContestMenuInTree(TreeItem treeItem) { + int dialogResult = dialog.open(); + if (dialogResult == 0) { + var newWorkingServerUuid = dialog.getNewWorkingServerId(); + if (newWorkingServerUuid != null) { + WorkingServerInfoExtended workingServerInfo = + new WorkingServerInfoExtended( + server, + clusterId, + server.getWorkingServerInfo(clusterId, newWorkingServerUuid)); + workingServerInfo.addToTable(tableWorkingServers); + } + } + } + }; - switch (getTreeItemType(treeItem)) { - case SERVER: - serversTree.setMenu(serverMenu); - return; - case CLUSTER: - // case WORKINGPROCESS_NODE: - serversTree.setMenu(clusterMenu); - break; - case INFOBASE_NODE: - serversTree.setMenu(infobaseNodeMenu); - break; - case INFOBASE: - serversTree.setMenu(infobaseMenu); - break; - case WORKINGPROCESS: - serversTree.setMenu(null); - break; - case WORKINGSERVER: - serversTree.setMenu(workingServerMenu); - break; - default: - serversTree.setMenu(null); - return; - } - } + SelectionAdapter createWorkingServerListenerInTree = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } - private void clearTabs() { - tabSessions.setText(Messages.getString("ViewerArea.Sessions")); //$NON-NLS-1$ - tabConnections.setText(Messages.getString("ViewerArea.Connections")); //$NON-NLS-1$ - tabLocks.setText(Messages.getString("ViewerArea.Locks")); //$NON-NLS-1$ - tabWorkingProcesses.setText(Messages.getString("ViewerArea.WorkingProcesses")); //$NON-NLS-1$ - tabWorkingServers.setText(Messages.getString("ViewerArea.WorkingServers")); //$NON-NLS-1$ + Server server = getServer(item[0]); + UUID clusterId = getClusterId(item[0]); + if (server == null || clusterId == null) { + return; + } - tableSessions.removeAll(); - tableConnections.removeAll(); - tableLocks.removeAll(); - tableWorkingProcesses.removeAll(); - tableWorkingServers.removeAll(); - } + WorkingServerDialog dialog; + try { + dialog = + new WorkingServerDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, null); + } catch (Exception excp) { + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + clusterId, + excp); + return; + } - private void clickItemInServerTree(int mouseButton) { - TreeItem[] item = serversTree.getSelection(); - if (item.length == 0) { - return; - } + int dialogResult = dialog.open(); + if (dialogResult == 0) { + var newWorkingServerUuid = dialog.getNewWorkingServerId(); + if (newWorkingServerUuid != null) { + IWorkingServerInfo workingServerInfo = + server.getWorkingServerInfo(clusterId, newWorkingServerUuid); + addWorkingServerItemInNode(item[0].getParentItem(), workingServerInfo); + } + } + } + }; - TreeItem treeItem = item[0]; + SelectionAdapter editWorkingServerListenerInTree = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + TreeItem[] item = serversTree.getSelection(); + if (item.length == 0) { + return; + } - switch (mouseButton) { - case 1: // left click - fillTabs(treeItem); - break; + Server server = getServer(item[0]); + UUID clusterId = getClusterId(item[0]); + UUID workingServerId = getWorkingServerId(item[0]); + if (server == null || clusterId == null) { + return; + } - case 3: // right click - setContestMenuInTree(treeItem); - break; + WorkingServerDialog dialog; + try { + dialog = + new WorkingServerDialog( + getParent().getDisplay().getActiveShell(), server, clusterId, workingServerId); + } catch (Exception excp) { + excp.printStackTrace(); + LOGGER.error( + "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ + workingServerId, + excp); + return; + } - default: - break; - } - } + dialog.open(); + } + }; Listener columnMoveListener = new Listener() { @@ -2395,18 +2403,11 @@ public void handleEvent(Event e) { TableColumn column = (TableColumn) e.widget; Table currentTable = column.getParent(); - Config commonConfig = ClusterProvider.getCommonConfig(); - if (currentTable.equals(tableSessions)) { - commonConfig.setSessionsColumnOrder(tableSessions.getColumnOrder()); - } else if (currentTable.equals(tableConnections)) { - commonConfig.setConnectionsColumnOrder(tableConnections.getColumnOrder()); - } else if (currentTable.equals(tableLocks)) { - commonConfig.setLocksColumnOrder(tableLocks.getColumnOrder()); - } else if (currentTable.equals(tableWorkingProcesses)) { - commonConfig.setWorkingProcessesColumnOrder(tableWorkingProcesses.getColumnOrder()); - } else if (currentTable.equals(tableWorkingServers)) { - commonConfig.setWorkingServersColumnOrder(tableWorkingServers.getColumnOrder()); + final Class clazz = + linksTablesToExtendedClass.get(currentTab); + if (clazz != null) { + config.setColumnsOrder(clazz, currentTable.getColumnOrder()); } // clusterProvider.saveConfig(); @@ -2422,21 +2423,10 @@ public void handleEvent(Event e) { int newWidth = column.getWidth(); Table currentTable = column.getParent(); TableColumn[] columns = currentTable.getColumns(); - Config commonConfig = ClusterProvider.getCommonConfig(); for (int i = 0; i < columns.length; i++) { if (columns[i].getText().equals(column.getText())) { - if (currentTable.equals(tableSessions)) { - commonConfig.setSessionsColumnWidth(i, newWidth); - } else if (currentTable.equals(tableConnections)) { - commonConfig.setConnectionsColumnWidth(i, newWidth); - } else if (currentTable.equals(tableLocks)) { - commonConfig.setLocksColumnWidth(i, newWidth); - } else if (currentTable.equals(tableWorkingProcesses)) { - commonConfig.setWorkingProcessesColumnWidth(i, newWidth); - } else if (currentTable.equals(tableWorkingServers)) { - commonConfig.setWorkingServersColumnWidth(i, newWidth); - } + config.setColumnsWidth(linksTablesToExtendedClass.get(currentTab), i, newWidth); break; } } @@ -2444,122 +2434,253 @@ public void handleEvent(Event e) { } }; - // ControlAdapter columnResizeListener = - // new ControlAdapter() { - // @Override - // public void controlResized(ControlEvent e) { - // TableColumn w = (TableColumn) e.widget; - // int width = w.getWidth(); - // TableColumn[] columns = w.getParent().getColumns(); - // - // for (int i = 0; i < columns.length; i++) { - // if (columns[i].getText().equals(w.getText())) { - // ClusterProvider.getCommonConfig().setSessionsColumnWidth(i, width); - // break; - // } - // } - // // clusterProvider.saveConfig(); - // } - // }; - - SelectionAdapter deleteItemListener = - new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - deleteSelectSession(); + Listener columnSortListener = + new Listener() { + public void handleEvent(Event e) { + Table currentTable = getCurrentTable(); + if (currentTable == null) { + return; + } + + ColumnProperties columnProperties = getColumnProperties(currentTab); + if (columnProperties == null) { + return; + } + TableColumn column = (TableColumn) e.widget; + int numColumn = (int) column.getData(); + + columnProperties.setSortColumn(numColumn); + currentTable.setSortColumn(column); + currentTable.setSortDirection(columnProperties.getSortDirectionSwt()); + + // сортировка того что уже есть в списке + TableItem[] items = currentTable.getItems(); + + for (int i = 1; i < items.length; i++) { + BaseInfoExtended secondString = (BaseInfoExtended) items[i].getData(EXTENDED_INFO); + + for (int j = 0; j < i; j++) { + BaseInfoExtended firstString = (BaseInfoExtended) items[j].getData(EXTENDED_INFO); + + if (firstString.compareTo(secondString) > 0) { + items[i].dispose(); + secondString.addToTable(currentTable, j); + items = currentTable.getItems(); + break; + } + } + } } }; - SelectionAdapter updateItemListener = + SelectionAdapter updateTablesListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - clickItemInServerTree(1); + fillTabs(); } }; - SelectionAdapter editItemListener = + SelectionAdapter editItemInTablesListener = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - Table currentTable = null; - - if (currentTabitem.equals(tabSessions)) { - currentTable = tableSessions; - } else if (currentTabitem.equals(tabConnections)) { - currentTable = tableConnections; - } else if (currentTabitem.equals(tabWorkingServers)) { - currentTable = tableWorkingServers; - } - - if (currentTable == null) { - return; - } - - TableItem[] item = currentTable.getSelection(); + TableItem[] item = getCurrentTable().getSelection(); if (item.length == 0) { return; } - if (currentTable.equals(tableSessions)) { + if (currentTab.equals(tabSessions)) { - Server server = (Server) item[0].getData(SERVER_INFO); - UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); - UUID sessionId = (UUID) item[0].getData(SESSION_ID); - ISessionInfo sessionInfo = (ISessionInfo) item[0].getData("sessionInfo"); //$NON-NLS-1$ + SessionInfoExtended sessionExtInfo = + (SessionInfoExtended) item[0].getData(EXTENDED_INFO); - SessionInfoDialog editClusterDialog; + SessionInfoDialog dialog; try { - editClusterDialog = - new SessionInfoDialog( - getParent().getDisplay().getActiveShell(), - server, - clusterId, - sessionId, - sessionInfo); + dialog = + new SessionInfoDialog(getParent().getDisplay().getActiveShell(), sessionExtInfo); } catch (Exception excp) { excp.printStackTrace(); LOGGER.error( "Error init SessionInfoDialog for session id {}", //$NON-NLS-1$ - sessionId, + sessionExtInfo.getSessionInfo().getSid(), excp); return; } - editClusterDialog.open(); + dialog.open(); - } else if (currentTable.equals(tableWorkingServers)) { - Server server = (Server) item[0].getData(SERVER_INFO); - UUID clusterId = (UUID) item[0].getData(CLUSTER_ID); - UUID workingServerId = (UUID) item[0].getData(WORKINGSERVER_ID); + } else if (currentTab.equals(tabWorkingServers)) { - CreateEditWorkingServerDialog editClusterDialog; + WorkingServerInfoExtended workingServerExtInfo = + (WorkingServerInfoExtended) item[0].getData(EXTENDED_INFO); + + WorkingServerDialog dialog; try { - editClusterDialog = - new CreateEditWorkingServerDialog( - getParent().getDisplay().getActiveShell(), - server, - clusterId, - workingServerId); + dialog = + new WorkingServerDialog( + getParent().getDisplay().getActiveShell(), workingServerExtInfo); } catch (Exception excp) { excp.printStackTrace(); LOGGER.error( "Error init WorkingServerDialog for cluster id {}", //$NON-NLS-1$ - workingServerId, + workingServerExtInfo.getWorkingServerId(), excp); return; } - int dialogResult = editClusterDialog.open(); + int dialogResult = dialog.open(); if (dialogResult == 0) { - clickItemInServerTree(0); + // clickItemInServerTree(0); // TODO что здесь должно делаться??? + fillTabs(); + } + } else { + return; + } + } + }; + + SelectionAdapter deleteItemInTablesListener = + new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + + TableItem[] selectedItems = getCurrentTable().getSelection(); + if (selectedItems.length == 0) { + return; + } + + for (TableItem item : selectedItems) { + item.setForeground(deletedItemColor); // TODO успевает ли окраситься в красный цвет + + // BaseInfoExtended extInfo = (BaseInfoExtended) item.getData("ExtendedInfo"); + // //$NON-NLS-1$ + // Server server = extInfo.getServer(); + // UUID clusterId = extInfo.getClusterId(); + + if (currentTab.equals(tabSessions)) { + SessionInfoExtended extInfo = (SessionInfoExtended) item.getData(EXTENDED_INFO); + + Server server = extInfo.getServer(); + UUID clusterId = extInfo.getClusterId(); + UUID sessionId = extInfo.getSessionInfo().getSid(); + + if (server.terminateSession(clusterId, sessionId)) { + item.dispose(); + } + + } else if (currentTab.equals(tabConnections)) { + ConnectionInfoExtended extInfo = (ConnectionInfoExtended) item.getData(EXTENDED_INFO); + + Server server = extInfo.getServer(); + UUID clusterId = extInfo.getClusterId(); + UUID pricessId = extInfo.getConnectionInfo().getWorkingProcessId(); + UUID connectionId = extInfo.getConnectionInfo().getInfoBaseConnectionId(); + UUID infobaseId = extInfo.getConnectionInfo().getInfoBaseId(); + + if (server.disconnectConnection(clusterId, pricessId, connectionId, infobaseId)) { + item.dispose(); // update tableConnections + } + + } else if (currentTab.equals(tabWorkingServers)) { + WorkingServerInfoExtended extInfo = + (WorkingServerInfoExtended) item.getData(EXTENDED_INFO); + + Server server = extInfo.getServer(); + UUID clusterId = extInfo.getClusterId(); + UUID workingServerId = extInfo.getWorkingServerId(); + + int answer = + Helper.showQuestionBox( + Messages.getString("ViewerArea.DeleteServerQuestion")); //$NON-NLS-1$ + + if (answer == SWT.YES && server.unregWorkingServer(clusterId, workingServerId)) { + item.dispose(); // update tableWorkingServers + } + + } else { + break; + } + } + } + }; + + Listener switchWatchingListener = + new Listener() { + @Override + public void handleEvent(Event event) { + if (event.detail == SWT.CHECK) { + TableItem item = (TableItem) event.item; + SessionInfoExtended ext = (SessionInfoExtended) item.getData(EXTENDED_INFO); + ext.switchWatching(item, item.getChecked()); + } + } + }; + + Listener mouseSelectCellListener = + new Listener() { + @Override + public void handleEvent(Event event) { + Table currentTable = (Table) event.widget; + + Point pt = new Point(event.x, event.y); + TableItem item = currentTable.getItem(pt); + if (item != null) { + for (int col = 0; col < currentTable.getColumnCount(); col++) { + Rectangle rect = item.getBounds(col); + if (rect.contains(pt)) { + + if (lastSelectItem != null && !lastSelectItem.isDisposed()) { + lastSelectItem.setForeground(lastSelectColumn, null); + } + item.setForeground(col, Helper.getOrangeColor()); + + lastSelectItem = item; + lastSelectColumn = col; + break; + } } } } }; - KeyAdapter keyListener = + MouseAdapter tablesMouseClickListener = + new MouseAdapter() { + @Override + public void mouseDown(MouseEvent event) { + if (event.button != 1) { + return; + } + Table currentTable = (Table) event.widget; + + Point pt = new Point(event.x, event.y); + TableItem item = currentTable.getItem(pt); + if (item != null) { + for (int col = 0; col < currentTable.getColumnCount(); col++) { + Rectangle rect = item.getBounds(col); + if (rect.contains(pt)) { + + if (lastSelectItem != null && !lastSelectItem.isDisposed()) { + lastSelectItem.setForeground(lastSelectColumn, null); + } + item.setForeground(col, Helper.getOrangeColor()); + + lastSelectItem = item; + lastSelectColumn = col; + break; + } + } + } + } + + @Override + public void mouseDoubleClick(MouseEvent e) { + editItemInTablesListener.widgetSelected(null); + } + }; + + KeyAdapter tableKeyPressedListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { @@ -2568,29 +2689,29 @@ public void keyPressed(KeyEvent e) { switch (e.keyCode) { case SWT.F2: - editItemListener.widgetSelected(null); + editItemInTablesListener.widgetSelected(null); break; case SWT.F5: - clickItemInServerTree(1); + fillTabs(); break; case SWT.DEL: - // deleteSelectSession(); - deleteItemListener.widgetSelected(null); + deleteItemInTablesListener.widgetSelected(null); break; case keyC: - // if (e.stateMask == SWT.CTRL) { - // TableItem[] selection = tableSessions.getSelection(); - // - // if (selection.length > 0) { - // Clipboard clipboard = new Clipboard(Display.getDefault()); - // clipboard.setContents(new Object[] { selection[0].getText() }, new - // Transfer[] { TextTransfer.getInstance() }); - // clipboard.dispose(); - // } - // } + if (e.stateMask == SWT.CTRL) { + TableItem[] selection = getCurrentTable().getSelection(); + + if (selection.length > 0) { + Clipboard clipboard = new Clipboard(Display.getDefault()); + clipboard.setContents( + new Object[] {selection[0].getText(lastSelectColumn)}, + new Transfer[] {TextTransfer.getInstance()}); + clipboard.dispose(); + } + } break; default: @@ -2598,4 +2719,84 @@ public void keyPressed(KeyEvent e) { } } }; + + private static class Strings { + + static final String MENU_SERVERS = getString("MainMenu.Servers"); + static final String MENU_FIND_SERVERS = getString("MainMenu.FindServers"); + static final String MENU_CONNECT_ALL_SERVERS = getString("MainMenu.ConnectAllServers"); + static final String MENU_DISCONNECT_ALL_SERVERS = getString("MainMenu.DisonnectAllServers"); + static final String MENU_SERVICE = getString("MainMenu.Service"); + static final String MENU_OPEN_SETTINGS = getString("MainMenu.OpenSettings"); + static final String MENU_ABOUT = getString("MainMenu.About"); + static final String COLUMN_SERVER = getString("ColumnServer"); + static final String TREE_INFOBASES_COUNT = getString("InfobasesCount"); + + static final String CONTEXT_MENU_UPDATE = getString("ContextMenu.Update"); + static final String CONTEXT_MENU_UPDATE_F5 = CONTEXT_MENU_UPDATE.concat("\tF5"); + + static final String CONTEXT_MENU_CONNECT_TO_SERVER = getString("ContextMenu.ConnectToServer"); + static final String CONTEXT_MENU_DISCONNECT_OF_SERVER = + getString("ContextMenu.DisconnectOfServer"); + static final String CONTEXT_MENU_SHOW_CONNECTION_ERROR = + getString("ContextMenu.ShowConnectionError"); + static final String CONTEXT_MENU_CREATE = getString("ContextMenu.Create"); + static final String CONTEXT_MENU_EDIT = getString("ContextMenu.Edit"); + static final String CONTEXT_MENU_DELETE = getString("ContextMenu.Delete"); + static final String CONTEXT_MENU_ADD_SERVER = getString("ContextMenu.AddServer"); + static final String CONTEXT_MENU_EDIT_SERVER = getString("ContextMenu.EditServer"); + static final String CONTEXT_MENU_MOVE_UP = getString("ContextMenu.MoveUp"); + static final String CONTEXT_MENU_MOVE_DOWN = getString("ContextMenu.MoveDown"); + static final String CONTEXT_MENU_ORGANIZE_SERVERS = getString("ContextMenu.OrganizeServers"); + static final String CONTEXT_MENU_REMOVE_SERVER = getString("ContextMenu.RemoveServer"); + + static final String CONTEXT_MENU_CREATE_CLUSTER = getString("ContextMenu.CreateCluster"); + static final String CONTEXT_MENU_EDIT_CLUSTER = getString("ContextMenu.EditCluster"); + static final String CONTEXT_MENU_DELETE_CLUSTER = getString("ContextMenu.DeleteCluster"); + + static final String CONTEXT_MENU_CREATE_WORKING_SERVER = + getString("ContextMenu.CreateWorkingServer"); + static final String CONTEXT_MENU_EDIT_WORKING_SERVER = + getString("ContextMenu.EditWorkingServer"); + static final String CONTEXT_MENU_EDIT_WORKING_SERVER_F2 = + getString("ContextMenu.EditWorkingServer").concat("\tF2"); + static final String CONTEXT_MENU_DELETE_WORKING_SERVER_DEL = + getString("ContextMenu.DeleteWorkingServer").concat("\tDEL"); + + static final String CONTEXT_MENU_CREATE_INFOBASE = getString("ContextMenu.CreateInfobase"); + static final String CONTEXT_MENU_UPDATE_INFOBASES = getString("ContextMenu.UpdateInfobases"); + static final String CONTEXT_MENU_ORDER_INFOBASES_BY = getString("ContextMenu.OrderInfobasesBy"); + static final String CONTEXT_MENU_ORDER_INFOBASES_BYDEFAULT = + getString("ContextMenu.OrderInfobasesByDefault"); + static final String CONTEXT_MENU_ORDER_INFOBASES_BYNAME = + getString("ContextMenu.OrderInfobasesByName"); + static final String CONTEXT_MENU_ORDER_INFOBASES_BYFAFORITES_ANDNAME = + getString("ContextMenu.OrderInfobasesByFaforitesAndName"); + + static final String CONTEXT_MENU_COPY_INFOBASE = getString("ContextMenu.CopyInfobase"); + static final String CONTEXT_MENU_EDIT_INFOBASE = getString("ContextMenu.EditInfobase"); + static final String CONTEXT_MENU_DELETE_INFOBASE = getString("ContextMenu.DeleteInfobase"); + + static final String CONTEXT_MENU_ADD_IN_FAVORITES = getString("ContextMenu.AddInFavorites"); + static final String CONTEXT_MENU_DELETE_FROM_FAVORITES = + getString("ContextMenu.DeleteFromFavorites"); + + static final String CONTEXT_MENU_SESSION_MANAGE = getString("ContextMenu.SessionManage"); + static final String CONTEXT_MENU_LOCK_SESSIONS_NOW = getString("ContextMenu.LockSessionsNow"); + static final String CONTEXT_MENU_TERMINATE_ALL_SESSIONS = + getString("ContextMenu.TerminateAllSessions"); + static final String CONTEXT_MENU_TERMINATE_USERS_SESSIONS = + getString("ContextMenu.TerminateUsersSessions"); + + static final String CONTEXT_MENU_VIEW_SESSION_F2 = + getString("ContextMenu.ViewSession").concat("\tF2"); + static final String CONTEXT_MENU_KILL_SESSION_DEL = + getString("ContextMenu.KillSession").concat("\tDEL"); + static final String CONTEXT_MENU_KILL_CONNECTION_DEL = + getString("ContextMenu.KillConnection").concat("\tDEL"); + + static String getString(String key) { + return Messages.getString("ViewerArea." + key); //$NON-NLS-1$ + } + } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/WorkingServerDialog.java similarity index 72% rename from clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java rename to clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/WorkingServerDialog.java index ff0d72b..f98e6e6 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/CreateEditWorkingServerDialog.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/WorkingServerDialog.java @@ -23,35 +23,38 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; -import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; -import org.eclipse.wb.swt.SWTResourceManager; +import ru.yanygin.clusterAdminLibrary.Helper; import ru.yanygin.clusterAdminLibrary.Server; +import ru.yanygin.clusterAdminLibrary.WorkingServerInfoExtended; -/** Dialog for create and edit Working Server parameters. */ -public class CreateEditWorkingServerDialog extends Dialog { +/** Диалог редактирования параметров рабочего сервера. */ +public class WorkingServerDialog extends Dialog { + private static final String DEFAULT_PROF_VALUE = "8"; //$NON-NLS-1$ + private static final String EMPTY_STRING = ""; //$NON-NLS-1$ + private static final String DEFAULT_INFOBASES_PER_WP = "8"; //$NON-NLS-1$ + private static final String DEFAULT_CONNECTIONS_PER_WP = "128"; //$NON-NLS-1$ + + private Server server; private UUID clusterId; private UUID workingServerId; - private Server server; - private Button btnIsDedicatedManagers; private Text txtServerName; private Text txtComputerName; private Text txtIpPort; private Text txtPortRange; - private Text txtInfoBasesPerWorkingProcessLimit; private Text txtConnectionsPerWorkingProcessLimit; private Text txtIpPortMainManager; - private Button btnIsMainServer; private Text txtWorkingProcessMemoryLimit; private Text txtSafeCallMemoryLimit; private Text txtCriticalProcessesTotalMemory; private Text txtTemporaryAllowedProcessesTotalMemory; private Text txtTemporaryAllowedProcessesTotalMemoryTimeLimit; private Text txtSafeWorkingProcessesMemoryLimit; + private Label lblSafeWorkingProcessesMemoryLimitMb; private Label lblSafeCallMemoryLimitMb; private Label lblWorkingProcessMemoryLimitMb; @@ -59,31 +62,48 @@ public class CreateEditWorkingServerDialog extends Dialog { private Label lblTemporaryAllowedProcessesTotalMemoryMb; private Label lblTemporaryAllowedProcessesTotalMemoryTimeLimitMin; - public UUID getNewWorkingServerId() { - return workingServerId; - } + private Button btnIsDedicatedManagers; + private Button btnIsMainServer; /** - * Create the dialog. + * Диалог создания нового или редактирования рабочего сервера. * * @param parentShell - parent shell * @param server - server * @param clusterId - cluster ID - * @param workingServerId - working server ID + * @param workingServerId - working server ID (null для создания нового) */ - public CreateEditWorkingServerDialog( + public WorkingServerDialog( Shell parentShell, Server server, UUID clusterId, UUID workingServerId) { super(parentShell); setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); - // super.configureShell(parentShell); - // parentShell.setText("Parameters of the 1C:Enterprise infobase"); - this.server = server; this.clusterId = clusterId; this.workingServerId = workingServerId; } + /** + * Диалог редактирования рабочего сервера. + * + * @param parentShell - parent shell + * @param workingServerExtInfo - расширенная информация рабочего сервера + */ + public WorkingServerDialog(Shell parentShell, WorkingServerInfoExtended workingServerExtInfo) { + super(parentShell); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); + + this.server = workingServerExtInfo.getServer(); + this.clusterId = workingServerExtInfo.getClusterId(); + this.workingServerId = workingServerExtInfo.getWorkingServerId(); + } + + @Override + protected void configureShell(Shell newShell) { + super.configureShell(newShell); + newShell.setText(Strings.TITLE_WINDOW); + } + /** * Create contents of the dialog. * @@ -100,47 +120,40 @@ protected Control createDialogArea(Composite parent) { Label lblServerName = new Label(container, SWT.NONE); lblServerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblServerName.setText(Messages.getString("WorkingServerDialog.ServerName")); //$NON-NLS-1$ + lblServerName.setText(Strings.SERVER_NAME); txtServerName = new Text(container, SWT.BORDER); - txtServerName.setToolTipText( - Messages.getString("WorkingServerDialog.ServerName")); //$NON-NLS-1$ txtServerName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); new Label(container, SWT.NONE); Label lblComputerName = new Label(container, SWT.NONE); lblComputerName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblComputerName.setText(Messages.getString("WorkingServerDialog.ComputerName")); //$NON-NLS-1$ + lblComputerName.setText(Strings.COMPUTER_NAME); txtComputerName = new Text(container, SWT.BORDER); - txtComputerName.setToolTipText( - Messages.getString("WorkingServerDialog.ComputerName")); //$NON-NLS-1$ txtComputerName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); new Label(container, SWT.NONE); Label lblIpPort = new Label(container, SWT.NONE); lblIpPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblIpPort.setText(Messages.getString("WorkingServerDialog.IPPort")); //$NON-NLS-1$ + lblIpPort.setText(Strings.IP_PORT); txtIpPort = new Text(container, SWT.BORDER); - txtIpPort.setToolTipText(Messages.getString("WorkingServerDialog.IPPort")); //$NON-NLS-1$ txtIpPort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); new Label(container, SWT.NONE); Label lblPortRange = new Label(container, SWT.NONE); lblPortRange.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblPortRange.setText(Messages.getString("WorkingServerDialog.PortRange")); //$NON-NLS-1$ + lblPortRange.setText(Strings.PORT_RANGE); txtPortRange = new Text(container, SWT.BORDER); - txtPortRange.setToolTipText(Messages.getString("WorkingServerDialog.PortRange")); //$NON-NLS-1$ txtPortRange.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); new Label(container, SWT.NONE); Label lblSafeWorkingProcessesMemoryLimit = new Label(container, SWT.NONE); lblSafeWorkingProcessesMemoryLimit.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSafeWorkingProcessesMemoryLimit.setText( - Messages.getString("WorkingServerDialog.SafeWorkingProcessesMemoryLimit")); //$NON-NLS-1$ + lblSafeWorkingProcessesMemoryLimit.setText(Strings.SAFE_WORKING_PROCESSES_MEMORY_LIMIT); txtSafeWorkingProcessesMemoryLimit = new Text(container, SWT.BORDER); txtSafeWorkingProcessesMemoryLimit.addModifyListener( @@ -151,8 +164,6 @@ public void modifyText(ModifyEvent e) { } }); - txtSafeWorkingProcessesMemoryLimit.setToolTipText( - Messages.getString("WorkingServerDialog.SafeWorkingProcessesMemoryLimit")); //$NON-NLS-1$ txtSafeWorkingProcessesMemoryLimit.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); @@ -164,8 +175,7 @@ public void modifyText(ModifyEvent e) { Label lblSafeCallMemoryLimit = new Label(container, SWT.NONE); lblSafeCallMemoryLimit.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblSafeCallMemoryLimit.setText( - Messages.getString("WorkingServerDialog.SafeCallMemoryLimit")); //$NON-NLS-1$ + lblSafeCallMemoryLimit.setText(Strings.SAFE_CALL_MEMORY_LIMIT); txtSafeCallMemoryLimit = new Text(container, SWT.BORDER); txtSafeCallMemoryLimit.addModifyListener( @@ -175,8 +185,6 @@ public void modifyText(ModifyEvent e) { lblSafeCallMemoryLimitMb.setText(convertToMegabytes((Text) e.widget)); } }); - txtSafeCallMemoryLimit.setToolTipText( - Messages.getString("WorkingServerDialog.SafeCallMemoryLimit")); //$NON-NLS-1$ txtSafeCallMemoryLimit.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); lblSafeCallMemoryLimitMb = new Label(container, SWT.NONE); @@ -187,8 +195,7 @@ public void modifyText(ModifyEvent e) { Label lblWorkingProcessMemoryLimit = new Label(container, SWT.NONE); lblWorkingProcessMemoryLimit.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, true, false, 1, 1)); - lblWorkingProcessMemoryLimit.setText( - Messages.getString("WorkingServerDialog.WorkingProcessMemoryLimit")); //$NON-NLS-1$ + lblWorkingProcessMemoryLimit.setText(Strings.WORKING_PROCESS_MEMORY_LIMIT); txtWorkingProcessMemoryLimit = new Text(container, SWT.BORDER); txtWorkingProcessMemoryLimit.addModifyListener( @@ -198,8 +205,6 @@ public void modifyText(ModifyEvent e) { lblWorkingProcessMemoryLimitMb.setText(convertToMegabytes((Text) e.widget)); } }); - txtWorkingProcessMemoryLimit.setToolTipText( - Messages.getString("WorkingServerDialog.WorkingProcessMemoryLimit")); //$NON-NLS-1$ txtWorkingProcessMemoryLimit.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); @@ -210,8 +215,7 @@ public void modifyText(ModifyEvent e) { lblWorkingProcessMemoryLimitMb.setLayoutData(gdlblWorkingProcessMemoryLimitMb); Label lblCriticalProcessesTotalMemory = new Label(container, SWT.NONE); - lblCriticalProcessesTotalMemory.setText( - Messages.getString("WorkingServerDialog.CriticalProcessesTotalMemory")); //$NON-NLS-1$ + lblCriticalProcessesTotalMemory.setText(Strings.CRITICAL_PROCESSES_TOTAL_MEMORY); lblCriticalProcessesTotalMemory.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); @@ -223,8 +227,6 @@ public void modifyText(ModifyEvent e) { lblCriticalProcessesTotalMemoryMb.setText(convertToMegabytes((Text) e.widget)); } }); - txtCriticalProcessesTotalMemory.setToolTipText( - Messages.getString("WorkingServerDialog.CriticalProcessesTotalMemory")); //$NON-NLS-1$ txtCriticalProcessesTotalMemory.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); @@ -238,8 +240,7 @@ public void modifyText(ModifyEvent e) { lblTemporaryAllowedProcessesTotalMemory.setLayoutData( new GridData(SWT.RIGHT, SWT.FILL, false, false, 1, 1)); lblTemporaryAllowedProcessesTotalMemory.setText( - Messages.getString( - "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryLabel")); //$NON-NLS-1$ + Strings.TEMPORARY_ALLOWED_PROCESSES_TOTAL_MEMORY); txtTemporaryAllowedProcessesTotalMemory = new Text(container, SWT.BORDER); txtTemporaryAllowedProcessesTotalMemory.addModifyListener( @@ -249,9 +250,6 @@ public void modifyText(ModifyEvent e) { lblTemporaryAllowedProcessesTotalMemoryMb.setText(convertToMegabytes((Text) e.widget)); } }); - txtTemporaryAllowedProcessesTotalMemory.setToolTipText( - Messages.getString( - "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryToolTip")); //$NON-NLS-1$ txtTemporaryAllowedProcessesTotalMemory.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); @@ -266,8 +264,7 @@ public void modifyText(ModifyEvent e) { lblTemporaryAllowedProcessesTotalMemoryTimeLimit.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblTemporaryAllowedProcessesTotalMemoryTimeLimit.setText( - Messages.getString( - "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitLabel")); //$NON-NLS-1$ + Strings.TEMPORARY_ALLOWED_PROCESSES_TOTAL_MEMORY_TIME_LIMIT); txtTemporaryAllowedProcessesTotalMemoryTimeLimit = new Text(container, SWT.BORDER); txtTemporaryAllowedProcessesTotalMemoryTimeLimit.addModifyListener( @@ -278,9 +275,6 @@ public void modifyText(ModifyEvent e) { convertToMinutes((Text) e.widget)); } }); - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText( - Messages.getString( - "WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitToolTip")); //$NON-NLS-1$ txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); @@ -292,8 +286,7 @@ public void modifyText(ModifyEvent e) { gdlblTemporaryAllowedProcessesTotalMemoryTimeLimitMin); Group groupWorkProcessesParams = new Group(container, SWT.NONE); - groupWorkProcessesParams.setText( - Messages.getString("WorkingServerDialog.WorkingProcessesParameters")); //$NON-NLS-1$ + groupWorkProcessesParams.setText(Strings.WORKING_PROCESSES_PARAMETERS); GridLayout glgroupWorkProcessesParams = new GridLayout(2, true); glgroupWorkProcessesParams.verticalSpacing = 8; groupWorkProcessesParams.setLayout(glgroupWorkProcessesParams); @@ -304,52 +297,42 @@ public void modifyText(ModifyEvent e) { Label lblInfoBasesPerWorkingProcessLimit = new Label(groupWorkProcessesParams, SWT.NONE); lblInfoBasesPerWorkingProcessLimit.setLayoutData( new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblInfoBasesPerWorkingProcessLimit.setText( - Messages.getString("WorkingServerDialog.InfobasesPerWorkingProcessLimit")); //$NON-NLS-1$ + lblInfoBasesPerWorkingProcessLimit.setText(Strings.INFOBASES_PER_WORKING_PROCESS_LIMIT); lblInfoBasesPerWorkingProcessLimit.setBounds(0, 0, 35, 15); txtInfoBasesPerWorkingProcessLimit = new Text(groupWorkProcessesParams, SWT.BORDER); txtInfoBasesPerWorkingProcessLimit.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); - txtInfoBasesPerWorkingProcessLimit.setToolTipText( - Messages.getString("WorkingServerDialog.InfobasesPerWorkingProcessLimit")); //$NON-NLS-1$ txtInfoBasesPerWorkingProcessLimit.setBounds(0, 0, 76, 21); Label lblConnectionsPerWorkingProcessLimit = new Label(groupWorkProcessesParams, SWT.WRAP); lblConnectionsPerWorkingProcessLimit.setLayoutData( new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1)); - lblConnectionsPerWorkingProcessLimit.setText( - Messages.getString("WorkingServerDialog.ConnectionsPerWorkingProcessLimit")); //$NON-NLS-1$ + lblConnectionsPerWorkingProcessLimit.setText(Strings.CONNECTIONS_PER_WORKING_PROCESS_LIMIT); lblConnectionsPerWorkingProcessLimit.setBounds(0, 0, 35, 15); txtConnectionsPerWorkingProcessLimit = new Text(groupWorkProcessesParams, SWT.BORDER); txtConnectionsPerWorkingProcessLimit.setLayoutData( new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); - txtConnectionsPerWorkingProcessLimit.setToolTipText( - Messages.getString("WorkingServerDialog.ConnectionsPerWorkingProcessLimit")); //$NON-NLS-1$ txtConnectionsPerWorkingProcessLimit.setBounds(0, 0, 76, 21); new Label(container, SWT.NONE); Label lblIpPortMainManager = new Label(container, SWT.NONE); lblIpPortMainManager.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); - lblIpPortMainManager.setText( - Messages.getString("WorkingServerDialog.IPPortMainClusterManager")); //$NON-NLS-1$ + lblIpPortMainManager.setText(Strings.IP_PORT_MAIN_CLUSTER_MANAGER); txtIpPortMainManager = new Text(container, SWT.BORDER); - txtIpPortMainManager.setToolTipText( - Messages.getString("WorkingServerDialog.IPPortMainClusterManager")); //$NON-NLS-1$ txtIpPortMainManager.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); new Label(container, SWT.NONE); new Label(container, SWT.NONE); btnIsDedicatedManagers = new Button(container, SWT.CHECK); - btnIsDedicatedManagers.setText( - Messages.getString("WorkingServerDialog.IsDedicatedManagers")); //$NON-NLS-1$ + btnIsDedicatedManagers.setText(Strings.IS_DEDICATED_MANAGERS); new Label(container, SWT.NONE); new Label(container, SWT.NONE); btnIsMainServer = new Button(container, SWT.CHECK); - btnIsMainServer.setText(Messages.getString("WorkingServerDialog.IsMainServer")); //$NON-NLS-1$ + btnIsMainServer.setText(Strings.IS_MAIN_SERVER); new Label(container, SWT.NONE); new Label(container, SWT.NONE); new Label(container, SWT.NONE); @@ -362,7 +345,19 @@ public void modifyText(ModifyEvent e) { private void initServerProperties() { IWorkingServerInfo serverInfo; - if (workingServerId != null) { // Редактируем существующий рабочий сервер + if (workingServerId == null) { + // Создаем новый рабочий сервер + int clusterPort = server.getClusterInfo(clusterId).getMainPort(); + serverInfo = new WorkingServerInfo(clusterPort); + + txtServerName.setText(EMPTY_STRING); + txtPortRange.setText(EMPTY_STRING); + txtComputerName.setText(EMPTY_STRING); + + txtInfoBasesPerWorkingProcessLimit.setText(DEFAULT_INFOBASES_PER_WP); + txtConnectionsPerWorkingProcessLimit.setText(DEFAULT_CONNECTIONS_PER_WP); + } else { + // Редактируем существующий рабочий сервер serverInfo = server.getWorkingServerInfo(clusterId, workingServerId); txtServerName.setText(serverInfo.getName()); @@ -379,16 +374,6 @@ private void initServerProperties() { Integer.toString(serverInfo.getInfoBasesPerWorkingProcessLimit())); txtConnectionsPerWorkingProcessLimit.setText( Integer.toString(serverInfo.getConnectionsPerWorkingProcessLimit())); - - } else { // Создаем новый рабочий сервер - serverInfo = new WorkingServerInfo(); - - txtServerName.setText(""); //$NON-NLS-1$ - txtPortRange.setText(""); //$NON-NLS-1$ - txtComputerName.setText(""); //$NON-NLS-1$ - - txtInfoBasesPerWorkingProcessLimit.setText("8"); //$NON-NLS-1$ - txtConnectionsPerWorkingProcessLimit.setText("128"); //$NON-NLS-1$ } txtIpPort.setText(Integer.toString(serverInfo.getMainPort())); @@ -412,21 +397,16 @@ private void initServerProperties() { txtSafeWorkingProcessesMemoryLimit.setEditable(false); txtWorkingProcessMemoryLimit.setEditable(false); - txtSafeWorkingProcessesMemoryLimit.setToolTipText( - Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ - txtWorkingProcessMemoryLimit.setToolTipText( - Messages.getString("Dialogs.DeprecatedInFifteen")); //$NON-NLS-1$ + txtSafeWorkingProcessesMemoryLimit.setToolTipText(Strings.DEPRECATED_IN_FIFTEEN); + txtWorkingProcessMemoryLimit.setToolTipText(Strings.DEPRECATED_IN_FIFTEEN); } else { // 8.3.15- txtCriticalProcessesTotalMemory.setEditable(false); txtTemporaryAllowedProcessesTotalMemory.setEditable(false); txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setEditable(false); - txtCriticalProcessesTotalMemory.setToolTipText( - Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ - txtTemporaryAllowedProcessesTotalMemory.setToolTipText( - Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ - txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText( - Messages.getString("Dialogs.AppearedInFifteen")); //$NON-NLS-1$ + txtCriticalProcessesTotalMemory.setToolTipText(Strings.APPEARED_IN_FIFTEEN); + txtTemporaryAllowedProcessesTotalMemory.setToolTipText(Strings.APPEARED_IN_FIFTEEN); + txtTemporaryAllowedProcessesTotalMemoryTimeLimit.setToolTipText(Strings.APPEARED_IN_FIFTEEN); } if (workingServerId != null) { // У уже созданного кластера запрещено менять хост и порт @@ -436,18 +416,17 @@ private void initServerProperties() { } else { // Почему новому серверу запрещено сразу ставить галочку Центральный сервер? btnIsMainServer.setEnabled(false); - txtIpPortMainManager.setText(""); //$NON-NLS-1$ } txtIpPortMainManager.setEditable(false); } private void resetToProf() { if (!server.isFifteenOrMoreAgentVersion()) { // 8.3.15- - txtSafeWorkingProcessesMemoryLimit.setText("0"); //$NON-NLS-1$ - txtWorkingProcessMemoryLimit.setText("0"); //$NON-NLS-1$ + txtSafeWorkingProcessesMemoryLimit.setText(DEFAULT_PROF_VALUE); + txtWorkingProcessMemoryLimit.setText(DEFAULT_PROF_VALUE); } - txtSafeCallMemoryLimit.setText("0"); //$NON-NLS-1$ - txtInfoBasesPerWorkingProcessLimit.setText("8"); //$NON-NLS-1$ + txtSafeCallMemoryLimit.setText(DEFAULT_PROF_VALUE); + txtInfoBasesPerWorkingProcessLimit.setText(DEFAULT_PROF_VALUE); } private boolean checkVariablesFromControls() { @@ -462,10 +441,10 @@ private boolean checkVariablesFromControls() { for (Text control : checksTextControls) { if (control.getText().isBlank()) { - control.setBackground(SWTResourceManager.getPinkColor()); + control.setBackground(Helper.getPinkColor()); existsError = true; } else { - control.setBackground(SWTResourceManager.getWhiteColor()); + control.setBackground(Helper.getWhiteColor()); } } @@ -477,9 +456,9 @@ private boolean checkVariablesFromControls() { for (Text control : checksIntControls) { try { Integer.parseInt(control.getText()); - control.setBackground(SWTResourceManager.getWhiteColor()); + control.setBackground(Helper.getWhiteColor()); } catch (Exception e) { - control.setBackground(SWTResourceManager.getPinkColor()); + control.setBackground(Helper.getPinkColor()); existsError = true; } } @@ -495,9 +474,9 @@ private boolean checkVariablesFromControls() { for (Text control : checksLongControls) { try { Long.parseLong(control.getText()); - control.setBackground(SWTResourceManager.getWhiteColor()); + control.setBackground(Helper.getWhiteColor()); } catch (Exception e) { - control.setBackground(SWTResourceManager.getPinkColor()); + control.setBackground(Helper.getPinkColor()); existsError = true; } } @@ -505,9 +484,9 @@ private boolean checkVariablesFromControls() { try { String[] portRange = txtPortRange.getText().split(":"); //$NON-NLS-1$ new PortRangeInfo(Integer.parseInt(portRange[1]), Integer.parseInt(portRange[0])); - txtPortRange.setBackground(SWTResourceManager.getWhiteColor()); + txtPortRange.setBackground(Helper.getWhiteColor()); } catch (Exception e) { - txtPortRange.setBackground(SWTResourceManager.getPinkColor()); + txtPortRange.setBackground(Helper.getPinkColor()); existsError = true; } @@ -522,11 +501,14 @@ private boolean saveNewClusterProperties() { IWorkingServerInfo workingServerInfo; if (workingServerId == null) { - workingServerInfo = new WorkingServerInfo(); + // создание нового рабочего сервера + int clusterPort = server.getClusterInfo(clusterId).getMainPort(); + workingServerInfo = new WorkingServerInfo(txtServerName.getText(), clusterPort); workingServerInfo.setHostName(txtComputerName.getText()); workingServerInfo.setMainPort(Integer.parseInt(txtIpPort.getText())); } else { + // изменение рабочего сервера workingServerInfo = server.getWorkingServerInfo(clusterId, workingServerId); } @@ -561,19 +543,32 @@ private boolean saveNewClusterProperties() { Long.parseLong(txtWorkingProcessMemoryLimit.getText())); } - try { - if (server.regWorkingServer(clusterId, workingServerInfo, workingServerId == null)) { - workingServerId = workingServerInfo.getWorkingServerId(); - return true; - } - } catch (Exception excp) { - var messageBox = new MessageBox(getParentShell()); - messageBox.setMessage(excp.getLocalizedMessage()); - messageBox.open(); + if (server.regWorkingServer(clusterId, workingServerInfo, workingServerId == null)) { + workingServerId = workingServerInfo.getWorkingServerId(); + return true; } return false; } + /** + * Получение ID нового рабочего сервера. + * + * @return ID нового рабочего сервера + */ + public UUID getNewWorkingServerId() { + return workingServerId; + } + + private String convertToMegabytes(Text textControl) { + long inMb = Long.parseLong(textControl.getText()) / (1024 * 1024); + return Long.toString(inMb).concat(Strings.MEGABYTES); + } + + private String convertToMinutes(Text textControl) { + long inMb = Long.parseLong(textControl.getText()) / (60); + return Long.toString(inMb).concat(Strings.MINUTES); + } + /** * Create contents of the button bar. * @@ -595,12 +590,7 @@ public void widgetSelected(SelectionEvent e) { createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); - Button buttonApply = - createButton( - parent, - IDialogConstants.PROCEED_ID, - Messages.getString("Dialogs.Apply"), //$NON-NLS-1$ - false); + Button buttonApply = createButton(parent, IDialogConstants.PROCEED_ID, Strings.APPLY, false); buttonApply.addSelectionListener( new SelectionAdapter() { @Override @@ -609,13 +599,8 @@ public void widgetSelected(SelectionEvent e) { } }); - Button buttonReset = - createButton( - parent, - IDialogConstants.RETRY_ID, - Messages.getString("Dialogs.Reset"), //$NON-NLS-1$ - false); - buttonReset.setText(Messages.getString("Dialogs.Reset")); //$NON-NLS-1$ + Button buttonReset = createButton(parent, IDialogConstants.RETRY_ID, Strings.RESET, false); + buttonReset.setText(Strings.RESET); buttonReset.addSelectionListener( new SelectionAdapter() { @Override @@ -625,32 +610,26 @@ public void widgetSelected(SelectionEvent e) { }); Button buttonResetToProf = - createButton( - parent, - IDialogConstants.RETRY_ID, - Messages.getString("Dialogs.ResetToPROF"), //$NON-NLS-1$ - false); + createButton(parent, IDialogConstants.RETRY_ID, Strings.RESET_TO_PROF, false); + buttonResetToProf.setText(Strings.RESET_TO_PROF); buttonResetToProf.addMouseTrackListener( new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { - txtSafeCallMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); - txtSafeWorkingProcessesMemoryLimit.setBackground( - SWTResourceManager.getLightGreenColor()); - txtWorkingProcessMemoryLimit.setBackground(SWTResourceManager.getLightGreenColor()); - txtInfoBasesPerWorkingProcessLimit.setBackground( - SWTResourceManager.getLightGreenColor()); + txtSafeCallMemoryLimit.setBackground(Helper.getLightGreenColor()); + txtSafeWorkingProcessesMemoryLimit.setBackground(Helper.getLightGreenColor()); + txtWorkingProcessMemoryLimit.setBackground(Helper.getLightGreenColor()); + txtInfoBasesPerWorkingProcessLimit.setBackground(Helper.getLightGreenColor()); } @Override public void mouseExit(MouseEvent e) { - txtSafeCallMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); - txtSafeWorkingProcessesMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); - txtWorkingProcessMemoryLimit.setBackground(SWTResourceManager.getWhiteColor()); - txtInfoBasesPerWorkingProcessLimit.setBackground(SWTResourceManager.getWhiteColor()); + txtSafeCallMemoryLimit.setBackground(Helper.getWhiteColor()); + txtSafeWorkingProcessesMemoryLimit.setBackground(Helper.getWhiteColor()); + txtWorkingProcessMemoryLimit.setBackground(Helper.getWhiteColor()); + txtInfoBasesPerWorkingProcessLimit.setBackground(Helper.getWhiteColor()); } }); - buttonResetToProf.setText(Messages.getString("Dialogs.ResetToPROF")); //$NON-NLS-1$ buttonResetToProf.addSelectionListener( new SelectionAdapter() { @Override @@ -660,15 +639,42 @@ public void widgetSelected(SelectionEvent e) { }); } - private String convertToMegabytes(Text textControl) { - long inMb = Long.parseLong(textControl.getText()) / (1024 * 1024); - return Long.toString(inMb) - .concat(Messages.getString("WorkingServerDialog.Megabytes")); //$NON-NLS-1$ - } - - private String convertToMinutes(Text textControl) { - long inMb = Long.parseLong(textControl.getText()) / (60); - return Long.toString(inMb) - .concat(Messages.getString("WorkingServerDialog.Minutes")); //$NON-NLS-1$ + private static class Strings { + + static final String TITLE_WINDOW = getString("TitleDialog"); + static final String SERVER_NAME = getString("ServerName"); + static final String COMPUTER_NAME = getString("ComputerName"); + static final String IP_PORT = getString("IPPort"); + static final String PORT_RANGE = getString("PortRange"); + static final String SAFE_WORKING_PROCESSES_MEMORY_LIMIT = + getString("SafeWorkingProcessesMemoryLimit"); + static final String SAFE_CALL_MEMORY_LIMIT = getString("SafeCallMemoryLimit"); + static final String WORKING_PROCESS_MEMORY_LIMIT = getString("WorkingProcessMemoryLimit"); + static final String CRITICAL_PROCESSES_TOTAL_MEMORY = getString("CriticalProcessesTotalMemory"); + static final String TEMPORARY_ALLOWED_PROCESSES_TOTAL_MEMORY = + getString("TemporaryAllowedProcessesTotalMemory"); + static final String TEMPORARY_ALLOWED_PROCESSES_TOTAL_MEMORY_TIME_LIMIT = + getString("TemporaryAllowedProcessesTotalMemoryTimeLimit"); + static final String WORKING_PROCESSES_PARAMETERS = getString("WorkingProcessesParameters"); + static final String INFOBASES_PER_WORKING_PROCESS_LIMIT = + getString("InfobasesPerWorkingProcessLimit"); + static final String CONNECTIONS_PER_WORKING_PROCESS_LIMIT = + getString("ConnectionsPerWorkingProcessLimit"); + static final String IP_PORT_MAIN_CLUSTER_MANAGER = getString("IPPortMainClusterManager"); + static final String IS_DEDICATED_MANAGERS = getString("IsDedicatedManagers"); + static final String IS_MAIN_SERVER = getString("IsMainServer"); + + static final String DEPRECATED_IN_FIFTEEN = Messages.getString("Dialogs.DeprecatedInFifteen"); + static final String APPEARED_IN_FIFTEEN = Messages.getString("Dialogs.AppearedInFifteen"); + static final String APPLY = Messages.getString("Dialogs.Apply"); + static final String RESET = Messages.getString("Dialogs.Reset"); + static final String RESET_TO_PROF = Messages.getString("Dialogs.ResetToPROF"); + + static final String MEGABYTES = getString("Megabytes"); + static final String MINUTES = getString("Minutes"); + + static String getString(String key) { + return Messages.getString("WorkingServerDialog." + key); //$NON-NLS-1$ + } } } diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages.properties b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages.properties index fbf7a31..032c125 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages.properties +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages.properties @@ -1,207 +1,222 @@ #Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/) #Eclipse messages class -#Tue Oct 05 12:05:26 MSK 2021 +#Sun Apr 17 15:13:55 MSK 2022 -AboutDialog.Autor = Autor:\r\nYanygin Sergey (Tula) -AboutDialog.Description = Utility for administration of 1C servers -AboutDialog.Email = E-mail:\r\nyanyginsa@gmail.com -AboutDialog.GitHub = Project on GitHub:\r\nhttps://github.com/YanSergey/OneS_ClusterAdmin -AboutDialog.MainTitle = OneS Cluster Admin -AboutDialog.Telegram = Telegram:\r\nhttps://t.me/YanSergey +AboutDialog.Autor = Autor:\r\nYanygin Sergey (Tula) +AboutDialog.CurrentVersion = version %s +AboutDialog.CurrentVersionIsLatest = (the latest version is installed) +AboutDialog.CurrentVersionIsOld = (latest version is %s, download) +AboutDialog.CurrentVersionIsUnknown = (latest version has not checked, check) +AboutDialog.Description = Utility for administration of 1C servers +AboutDialog.Email_Description = E-mail:\r\n%s +AboutDialog.GitHub_Description = Project on GitHub:\r\n%s +AboutDialog.MainTitle = OneS Cluster Admin +AboutDialog.Telegram_Description = Telegram:\r\n%s +AboutDialog.TitleDialog = About -ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors = Acceptable deviation of the number of server errors -ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrorsWithLineBreak = Acceptable deviation of the\r\nnumber of server errors (%) -ClusterDialog.AllowedAmountOfMemory = Allowed amount of memory -ClusterDialog.AllowedAmountOfMemoryWithLineBreak = Allowed amount\r\nof memory (KB) -ClusterDialog.ClusterName = Cluster name -ClusterDialog.ClusterRecyclingKillByMemoryWithDump = Cluster recycling kill by memory with dump -ClusterDialog.ComputerName = Computer name -ClusterDialog.FaultToleranceLevel = Fault tolerance level -ClusterDialog.ForceShutdownOfProblematicProcesses = Force shutdown of problematic processes -ClusterDialog.IPPort = IP Port -ClusterDialog.IntervalExceedingAllowedAmountOfMemory = Interval exceeding allowed amount of memory -ClusterDialog.IntervalExceedingAllowedAmountOfMemoryWithLineBreak = Interval exceeding allowed\r\namount of memory (second) -ClusterDialog.LoadBalancingMode = Load balancing mode -ClusterDialog.RestartInterval = Restart interval (second) -ClusterDialog.RestartWorkProcesses = Restart Work Processes -ClusterDialog.ShutDownProcessesStopAfter = Shut down processes stop after -ClusterDialog.ShutDownProcessesStopAfterSecond = Shut down processes stop after (second) +ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors = Acceptable deviation of the\r\nnumber of server errors (%) +ClusterDialog.ClusterName = Cluster name +ClusterDialog.ClusterRecyclingKillByMemoryWithDump = Cluster recycling kill by memory with dump +ClusterDialog.ComputerName = Computer name +ClusterDialog.FaultToleranceLevel = Fault tolerance level +ClusterDialog.ForceShutdownOfProblematicProcesses = Force shutdown of problematic processes +ClusterDialog.IPPort = IP Port +ClusterDialog.LoadBalancingMode = Load balancing mode +ClusterDialog.LoadBalancingModeMemoryPriority = Memory priority +ClusterDialog.LoadBalancingModePerformancePriority = Performance priority +ClusterDialog.ShutDownProcessesStopAfter = Shut down processes stop after (second) +ClusterDialog.TitleDialog = Cluster parameters +ClusterDialog.WorkingProcessesAllowedAmountOfMemory = Allowed amount\r\nof memory (KB) +ClusterDialog.WorkingProcessesIntervalExceedingAllowedAmountOfMemory = Interval exceeding allowed\r\namount of memory (second) +ClusterDialog.WorkingProcessesRestart = Restart working processes +ClusterDialog.WorkingProcessesRestartInterval = Restart interval (second) -Dialogs.AppearedInFifteen = Appeared in 8.3.15 -Dialogs.Apply = Apply -Dialogs.ClearTheDatabase = Clear the database by removing the information database data from it -Dialogs.ConnectionOnly = Connection only -Dialogs.Constantly = Constantly -Dialogs.DeleteTheEntireDatabase = Delete the entire database -Dialogs.DeprecatedInFifteen = Deprecated in 8.3.15 -Dialogs.Disable = Disable -Dialogs.DropInfobaseDescription = When deleting an information database, you can choose one of 3 actions on the database that contains the information database data: -Dialogs.LeaveDatabaseUnchanged = Leave the database and its contents unchanged -Dialogs.MemoryPriority = Memory priority -Dialogs.Password = Password -Dialogs.PerformancePriority = Performance priority -Dialogs.Reset = Reset -Dialogs.ResetToPROF = Reset to PROF -Dialogs.SecurityLevel = Security level -Dialogs.Username = Username +Dialogs.AppearedInFifteen = Appeared in 8.3.15 +Dialogs.Apply = Apply +Dialogs.ConnectionOnly = Connection only +Dialogs.Constantly = Constantly +Dialogs.DeprecatedInFifteen = Deprecated in 8.3.15 +Dialogs.Disable = Disable +Dialogs.MemoryPriority = Memory priority +Dialogs.Password = Password +Dialogs.PerformancePriority = Performance priority +Dialogs.Reset = Reset +Dialogs.ResetToPROF = Reset to PROF +Dialogs.SecurityLevel = Security level +Dialogs.Username = Username InfobaseDialog.AllowDistributeLicense = Allow distribute license\r\nat 1C:Enterprise server +InfobaseDialog.ClearTheDatabase = Clear the database by removing the information database data from it InfobaseDialog.CreateDatabaseIfNotAvailable = Create a database if it is not available InfobaseDialog.DBMSType = DBMS type InfobaseDialog.DatabaseDBName = Database DB name InfobaseDialog.DatabaseDBPassword = Database DB password InfobaseDialog.DatabaseDBUser = Database DB user InfobaseDialog.DateOffset = Date offset -InfobaseDialog.DeniedFrom = Denied from (yyyy-mm-dd hh:mm:ss): -InfobaseDialog.DeniedMessage = Denied message -InfobaseDialog.DeniedParameter = Denied parameter -InfobaseDialog.DeniedTo = Denied to (yyyy-mm-dd hh:mm:ss): +InfobaseDialog.DeleteTheEntireDatabase = Delete the entire database InfobaseDialog.Description = Description +InfobaseDialog.DropInfobaseDescription = When deleting an information database, you can choose one of 3 actions on the database that contains the information database data: InfobaseDialog.ExternalSessionManagement = External session management -InfobaseDialog.IBMDB2 = IBMDB2 InfobaseDialog.InfobaseName = Name +InfobaseDialog.LeaveDatabaseUnchanged = Leave the database and its contents unchanged InfobaseDialog.Locale = Locale -InfobaseDialog.MSSQLServer = MSSQLServer -InfobaseDialog.OracleDatabase = OracleDatabase -InfobaseDialog.PermissionCode = Permission code -InfobaseDialog.PostgreSQL = PostgreSQL InfobaseDialog.RequiredUseOfExternalManagement = Required use of external management InfobaseDialog.SafeModeSecurityProfile = Safe mode security profile InfobaseDialog.SecurityProfile = Security profile InfobaseDialog.ServerDBName = Server DB name InfobaseDialog.SessionsDenied = Sessions denied +InfobaseDialog.SessionsDeniedFrom = Denied from (yyyy-mm-dd hh:mm:ss): +InfobaseDialog.SessionsDeniedMessage = Denied message +InfobaseDialog.SessionsDeniedParameter = Denied parameter +InfobaseDialog.SessionsDeniedTo = Denied to (yyyy-mm-dd hh:mm:ss): +InfobaseDialog.SessionsPermissionCode = Permission code InfobaseDialog.SheduledJobsDenied = Sheduled jobs denied +InfobaseDialog.TitleDialog = Infobase parameters +InfobaseDialog.TitleDropInfobaseParameters = Delete infobase InfobaseDialog.YouNeedToEnter = you need to enter -InfobaseDialog.en_US = en_US -InfobaseDialog.ru_RU = ru_RU -ServerDialog.AgentParameters = Server agent parameters -ServerDialog.AutoconnectAtStartup = Autoconnect to the server at startup -ServerDialog.CentralServerAdminstrator = Central server adminstrator -ServerDialog.ConnectParameters = Connect parameters -ServerDialog.Credentials = Credentials -ServerDialog.Description = Description -ServerDialog.Host = Host -ServerDialog.ID = ID -ServerDialog.LocalRASParameters = Local RAS parameters -ServerDialog.Name = Name -ServerDialog.Password = Password -ServerDialog.Port = Port -ServerDialog.RemoteRASParameters = Remote RAS parameters -ServerDialog.SaveCredentials = Save credentials -ServerDialog.Type = Type -ServerDialog.UseLocalRAS = Use local RAS -ServerDialog.UseRemoteRAS = Use remote RAS -ServerDialog.User = User -ServerDialog.Username = Username -ServerDialog.V8Version = V8 version +ServerDialog.AgentParameters = Server agent parameters +ServerDialog.AutoconnectAtStartup = Autoconnect to the server at startup +ServerDialog.CentralServerAdminstrator = Central server adminstrator +ServerDialog.ClusterName = Cluster name +ServerDialog.ClustersCredentialsGroup = Clusters credentials +ServerDialog.ConnectParameters = Connect parameters +ServerDialog.Credentials = Credentials +ServerDialog.Description = Description +ServerDialog.Host = Host +ServerDialog.ID = ID +ServerDialog.InfobaseName = Infobase name +ServerDialog.InfobasesCredentialsGroup = Infobases credentials +ServerDialog.LocalRASParameters = Local RAS parameters +ServerDialog.Password = Password +ServerDialog.Port = Port +ServerDialog.RemoteRASParameters = Remote RAS parameters +ServerDialog.SaveCredentialsName = Only username +ServerDialog.SaveCredentialsNamePass = Username and password +ServerDialog.SaveCredentialsNone = Not save +ServerDialog.SaveCredentialsVariant = Save credentials variant +ServerDialog.SetNewUserPassword = Set new username/password +ServerDialog.ShowPasswordModeToolTipText = Show/hide passwords +ServerDialog.TitleDialog = Parameters of the server 1C:Enterprise +ServerDialog.UseLocalRAS = Use local RAS +ServerDialog.UseRemoteRAS = Use remote RAS +ServerDialog.Username = Username +ServerDialog.V8Version = V8 version -SettingsDialog.English = English -SettingsDialog.ExpandClusters = Clusters -SettingsDialog.ExpandInfobases = Infobases -SettingsDialog.ExpandNodesInTree = Expand nodes in tree -SettingsDialog.ExpandServers = Servers -SettingsDialog.ExpandWorkingProcesses = Working processes -SettingsDialog.ExpandWorkingServers = Working servers -SettingsDialog.Highlight = Highlight -SettingsDialog.HighlightDuration = Highlight duration (sec) -SettingsDialog.HighlightNewItems = Highlight new items -SettingsDialog.Locale = Locale (need restart) -SettingsDialog.ReadClipboard = Read clipboard -SettingsDialog.Russian = Russian -SettingsDialog.ShadowSleepSessions = Shadow sleep sessions -SettingsDialog.ShowInfo = Additional info -SettingsDialog.ShowInfobaseDescription = Show infobase description -SettingsDialog.ShowLocalRASConnectInfo = About connecting via a local RAS -SettingsDialog.ShowNodesInTree = Show nodes in tree -SettingsDialog.ShowServerDescription = Show server description -SettingsDialog.ShowServerVersion = Show server version -SettingsDialog.ShowWorkingProcesses = Working processes -SettingsDialog.ShowWorkingServers = Working servers -SettingsDialog.System = System +SettingsDialog.CheckUpdate = Check update +SettingsDialog.ExpandClusters = Clusters +SettingsDialog.ExpandInfobases = Infobases +SettingsDialog.ExpandNodesInTree = Expand nodes in tree +SettingsDialog.ExpandServers = Servers +SettingsDialog.ExpandWorkingProcesses = Working processes +SettingsDialog.ExpandWorkingServers = Working servers +SettingsDialog.Highlight = Highlight +SettingsDialog.HighlightDuration = Highlight duration (sec) +SettingsDialog.HighlightNewItems = Highlight new items +SettingsDialog.Locale = Locale (need restart) +SettingsDialog.LocaleEnglish = English +SettingsDialog.LocaleRussian = Russian +SettingsDialog.LocaleSystem = System +SettingsDialog.ReadClipboard = Read clipboard (when adding server) +SettingsDialog.RowSortDirection = Row sort direction +SettingsDialog.RowSortDirectionAsPrevious = As previous +SettingsDialog.RowSortDirectionAscending = Descending +SettingsDialog.RowSortDirectionDescending = Ascending +SettingsDialog.ShadowSleepSessions = Shadow sleep sessions +SettingsDialog.ShowInfo = Additional info +SettingsDialog.ShowInfobaseDescription = Show infobase description +SettingsDialog.ShowLocalRASConnectInfo = About connecting via a local RAS +SettingsDialog.ShowNodesInTree = Show nodes in tree +SettingsDialog.ShowServerDescription = Show server description +SettingsDialog.ShowServerVersion = Show server version +SettingsDialog.ShowWorkingProcesses = Working processes +SettingsDialog.ShowWorkingServers = Working servers +SettingsDialog.TitleDialog = Parameters of the application +SettingsDialog.WatchSessions = Watch sessions color -ViewerArea.About = About -ViewerArea.Active = Active -ViewerArea.AddServer = Add Server -ViewerArea.ConnPerProcessLimit = Conn per process limit -ViewerArea.ConnectToAllServers = Connect to all servers -ViewerArea.ConnectToServer = Connect to Server -ViewerArea.Connections = Connections -ViewerArea.ConnectionsCount = Connections (%s) -ViewerArea.CreateCluster = Create Cluster -ViewerArea.CreateInfobase = Create Infobase -ViewerArea.CreateNewInfobaseUsingThis = Create a new infobase using this -ViewerArea.CreateWorkingServer = Create working server -ViewerArea.DedicatedManagers = Dedicated managers -ViewerArea.DeleteCluster = Delete cluster -ViewerArea.DeleteClusterQuestion = Deleting a cluster will delete its settings and the list of registered information databases. Do you really want to delete the cluster? -ViewerArea.DeleteInfobase = Delete infobase -ViewerArea.DeleteWorkingServer = Delete working server -ViewerArea.Description = Description -ViewerArea.DisconnectOfServer = Disconnect of Server -ViewerArea.DisonnectFromAllServers = Disconnect from all servers -ViewerArea.EditCluster = Edit Cluster -ViewerArea.EditInfobase = Edit Infobase -ViewerArea.EditServer = Edit Server -ViewerArea.EditWorkingServer = Edit working server -ViewerArea.FindNewServers = Find new Servers -ViewerArea.IBPerProcessLimit = IB per process limit -ViewerArea.IPPort = IP Port -ViewerArea.IPPortMainManager = IP Port main manager -ViewerArea.InfobasesCount = Infobases (%s) -ViewerArea.KillConnection = Kill connection -ViewerArea.KillSession = Kill session -ViewerArea.LockSessionsNow = Lock sessions now -ViewerArea.Locks = Locks -ViewerArea.LocksCount = Locks (%s) -ViewerArea.MainServer = Main server -ViewerArea.Memory = Memory, Kb -ViewerArea.MemoryExceeded = Memory exceeded, sec -ViewerArea.NotUsed = Not used -ViewerArea.OpenSettings = Settings -ViewerArea.PID = PID -ViewerArea.Port = Port -ViewerArea.ProcessIsRunning = The process is running -ViewerArea.ProcessIsStopped = The process is stopped -ViewerArea.RangeIPPort = Range IP Port -ViewerArea.RemoveServer = Remove Server -ViewerArea.Server = Server -ViewerArea.Servers = Servers -ViewerArea.Service = Service -ViewerArea.Session = Session -ViewerArea.SessionManage = Session manage -ViewerArea.Sessions = Sessions -ViewerArea.SessionsCount = Sessions (%s) -ViewerArea.ShowConnectionError = Show connection error -ViewerArea.SleepAfter = Sleep after -ViewerArea.StartedAt = Started At -ViewerArea.TerminateAllSessions = Terminate all sessions -ViewerArea.TerminateUsersSessions = Terminate users sessions -ViewerArea.Update = Update -ViewerArea.UpdateInfobases = Update infobases -ViewerArea.ViewSession = Session info -ViewerArea.WorkingProcesses = Working processes -ViewerArea.WorkingProcessesCount = Working processes (%s) -ViewerArea.WorkingServers = Working servers -ViewerArea.WorkingServersCount = Working servers (%s) +ViewerArea.Active = Active +ViewerArea.ColumnServer = Server +ViewerArea.ConnPerProcessLimit = Conn per process limit +ViewerArea.ContextMenu.AddInFavorites = Add to favorites +ViewerArea.ContextMenu.AddServer = Add server +ViewerArea.ContextMenu.ConnectToServer = Connect to server +ViewerArea.ContextMenu.CopyInfobase = Copy infobase +ViewerArea.ContextMenu.Create = Create +ViewerArea.ContextMenu.CreateCluster = Create cluster +ViewerArea.ContextMenu.CreateInfobase = Create infobase +ViewerArea.ContextMenu.CreateWorkingServer = Create working server +ViewerArea.ContextMenu.Delete = Delete +ViewerArea.ContextMenu.DeleteCluster = Delete cluster +ViewerArea.ContextMenu.DeleteFromFavorites = Delete from favorites +ViewerArea.ContextMenu.DeleteInfobase = Delete infobase +ViewerArea.ContextMenu.DeleteWorkingServer = Delete working server +ViewerArea.ContextMenu.DisconnectOfServer = Disconnect of server +ViewerArea.ContextMenu.Edit = Edit +ViewerArea.ContextMenu.EditCluster = Edit cluster +ViewerArea.ContextMenu.EditInfobase = Edit infobase +ViewerArea.ContextMenu.EditServer = Edit server +ViewerArea.ContextMenu.EditWorkingServer = Edit working server +ViewerArea.ContextMenu.KillConnection = Kill connection +ViewerArea.ContextMenu.KillSession = Kill session +ViewerArea.ContextMenu.LockSessionsNow = Lock sessions now +ViewerArea.ContextMenu.MoveDown = Move down +ViewerArea.ContextMenu.MoveUp = Move up +ViewerArea.ContextMenu.OrderInfobasesBy = Order by... +ViewerArea.ContextMenu.OrderInfobasesByDefault = By default +ViewerArea.ContextMenu.OrderInfobasesByFaforitesAndName = By favorites/name +ViewerArea.ContextMenu.OrderInfobasesByName = By name +ViewerArea.ContextMenu.OrganizeServers = Sort everything +ViewerArea.ContextMenu.RemoveServer = Remove server +ViewerArea.ContextMenu.SessionManage = Session manage +ViewerArea.ContextMenu.ShowConnectionError = Show connection error +ViewerArea.ContextMenu.TerminateAllSessions = Terminate all sessions +ViewerArea.ContextMenu.TerminateUsersSessions = Terminate users sessions +ViewerArea.ContextMenu.Update = Update +ViewerArea.ContextMenu.UpdateInfobases = Update infobases +ViewerArea.ContextMenu.ViewSession = Session info +ViewerArea.DedicatedManagers = Dedicated managers +ViewerArea.DeleteClusterQuestion = Deleting a cluster will delete its settings and the list of registered information databases. Do you really want to delete the cluster? +ViewerArea.DeleteServerQuestion = Do you really want to remove the server from the list? +ViewerArea.Description = Description +ViewerArea.IBPerProcessLimit = IB per process limit +ViewerArea.IPPort = IP Port +ViewerArea.IPPortMainManager = IP Port main manager +ViewerArea.InfobasesCount = Infobases (%s) +ViewerArea.MainMenu.About = About +ViewerArea.MainMenu.ConnectAllServers = Connect to all servers +ViewerArea.MainMenu.DisonnectAllServers = Disconnect from all servers +ViewerArea.MainMenu.FindServers = Find Servers +ViewerArea.MainMenu.OpenSettings = Settings +ViewerArea.MainMenu.Servers = Servers +ViewerArea.MainMenu.Service = Service +ViewerArea.MainServer = Main server +ViewerArea.Memory = Memory, Kb +ViewerArea.MemoryExceeded = Memory exceeded, sec +ViewerArea.NotUsed = Not used +ViewerArea.PID = PID +ViewerArea.Port = Port +ViewerArea.ProcessIsRunning = The process is running +ViewerArea.ProcessIsStopped = The process is stopped +ViewerArea.RangeIPPort = Range IP Port +ViewerArea.SleepAfter = Sleep after +ViewerArea.StartedAt = Started At -WorkingServerDialog.ComputerName = Computer name -WorkingServerDialog.ConnectionsPerWorkingProcessLimit = Connections per working\r\nprocess limit -WorkingServerDialog.CriticalProcessesTotalMemory = Critical processes\r\ntotal memory (byte) -WorkingServerDialog.IPPort = IP port -WorkingServerDialog.IPPortMainClusterManager = IP port main cluster manager -WorkingServerDialog.InfobasesPerWorkingProcessLimit = Infobases per\r\nworking process limit -WorkingServerDialog.IsDedicatedManagers = Is dedicated managers -WorkingServerDialog.IsMainServer = Is main server -WorkingServerDialog.Megabytes = \ Mb -WorkingServerDialog.Minutes = \ Min -WorkingServerDialog.PortRange = Port range -WorkingServerDialog.SafeCallMemoryLimit = Safe call memory\r\nlimit (byte) -WorkingServerDialog.SafeWorkingProcessesMemoryLimit = Safe working processes\r\nmemory limit (byte) -WorkingServerDialog.ServerName = Server name -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryLabel = Temporary allowed processes\r\ntotal memory (byte) -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitLabel = Temporary allowed processes\r\ntotal memory time limit (second) -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitToolTip = Temporary allowed processes total memory time limit -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryToolTip = Temporary allowed processes total memory -WorkingServerDialog.WorkingProcessMemoryLimit = Working process\r\nmemory limit (byte) -WorkingServerDialog.WorkingProcessesParameters = Working processes parameters +WorkingServerDialog.ComputerName = Computer name +WorkingServerDialog.ConnectionsPerWorkingProcessLimit = Connections per working\r\nprocess limit +WorkingServerDialog.CriticalProcessesTotalMemory = Critical processes\r\ntotal memory (byte) +WorkingServerDialog.IPPort = IP port +WorkingServerDialog.IPPortMainClusterManager = IP port main cluster manager +WorkingServerDialog.InfobasesPerWorkingProcessLimit = Infobases per\r\nworking process limit +WorkingServerDialog.IsDedicatedManagers = Is dedicated managers +WorkingServerDialog.IsMainServer = Is main server +WorkingServerDialog.Megabytes = \ Mb +WorkingServerDialog.Minutes = \ Min +WorkingServerDialog.PortRange = Port range +WorkingServerDialog.SafeCallMemoryLimit = Safe call memory\r\nlimit (byte) +WorkingServerDialog.SafeWorkingProcessesMemoryLimit = Safe working processes\r\nmemory limit (byte) +WorkingServerDialog.ServerName = Server name +WorkingServerDialog.TemporaryAllowedProcessesTotalMemory = Temporary allowed processes\r\ntotal memory (byte) +WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimit = Temporary allowed processes\r\ntotal memory time limit (second) +WorkingServerDialog.TitleDialog = Working server parameters +WorkingServerDialog.WorkingProcessMemoryLimit = Working process\r\nmemory limit (byte) +WorkingServerDialog.WorkingProcessesParameters = Working processes parameters diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages_ru_RU.properties b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages_ru_RU.properties index 004cbf8..dd80728 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages_ru_RU.properties +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibraryUI/messages_ru_RU.properties @@ -2,206 +2,221 @@ #Eclipse messages class #Thu Sep 09 18:06:08 MSK 2021 -AboutDialog.Autor = \u0410\u0432\u0442\u043E\u0440:\r\n\u042F\u043D\u044B\u0433\u0438\u043D \u0421\u0435\u0440\u0433\u0435\u0439 (\u0433. \u0422\u0443\u043B\u0430) -AboutDialog.Description = \u0423\u0442\u0438\u043B\u0438\u0442\u0430 \u0434\u043B\u044F \u0430\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432 1\u0421 -AboutDialog.Email = E-mail:\r\nyanyginsa@gmail.com -AboutDialog.GitHub = \u041F\u0440\u043E\u0435\u043A\u0442 \u043D\u0430 GitHub:\r\nhttps://github.com/YanSergey/OneS_ClusterAdmin -AboutDialog.MainTitle = OneS Cluster Admin -AboutDialog.Telegram = Telegram:\r\nhttps://t.me/YanSergey +AboutDialog.Autor = \u0410\u0432\u0442\u043E\u0440:\r\n\u042F\u043D\u044B\u0433\u0438\u043D \u0421\u0435\u0440\u0433\u0435\u0439 (\u0433. \u0422\u0443\u043B\u0430) +AboutDialog.CurrentVersion = \u0432\u0435\u0440\u0441\u0438\u044F %s +AboutDialog.CurrentVersionIsLatest = (\u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0430 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u044F\u044F \u0432\u0435\u0440\u0441\u0438\u044F) +AboutDialog.CurrentVersionIsOld = (\u043F\u043E\u0441\u043B\u0435\u0434\u043D\u044F\u044F \u0432\u0435\u0440\u0441\u0438\u044F %s, \u0441\u043A\u0430\u0447\u0430\u0442\u044C) +AboutDialog.CurrentVersionIsUnknown = (\u043F\u043E\u0441\u043B\u0435\u0434\u043D\u044F\u044F \u0432\u0435\u0440\u0441\u0438\u044F \u043D\u0435 \u043F\u0440\u043E\u0432\u0435\u0440\u044F\u043B\u0430\u0441\u044C, \u043F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C) +AboutDialog.Description = \u0423\u0442\u0438\u043B\u0438\u0442\u0430 \u0434\u043B\u044F \u0430\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u044F \u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432 1\u0421 +AboutDialog.Email_Description = E-mail:\r\n%s +AboutDialog.GitHub_Description = \u041F\u0440\u043E\u0435\u043A\u0442 \u043D\u0430 GitHub:\r\n%s +AboutDialog.MainTitle = OneS Cluster Admin +AboutDialog.Telegram_Description = Telegram:\r\n%s +AboutDialog.TitleDialog = \u041E \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0435 -ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors = \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0435 \u043E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u0438\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430 \u043E\u0448\u0438\u0431\u043E\u043A \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrorsWithLineBreak = \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0435 \u043E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u0438\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430\r\n\u043E\u0448\u0438\u0431\u043E\u043A \u0441\u0435\u0440\u0432\u0435\u0440\u0430 (%) -ClusterDialog.AllowedAmountOfMemory = \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438 -ClusterDialog.AllowedAmountOfMemoryWithLineBreak = \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043E\u0431\u044A\u0435\u043C\r\n\u043F\u0430\u043C\u044F\u0442\u0438 (\u041A\u0431) -ClusterDialog.ClusterName = \u0418\u043C\u044F \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 -ClusterDialog.ClusterRecyclingKillByMemoryWithDump = \u0417\u0430\u043F\u0438\u0441\u044B\u0432\u0430\u0442\u044C \u0434\u0430\u043C\u043F \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u043F\u0440\u0438 \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u0438 \u043A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0433\u043E \u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 -ClusterDialog.ComputerName = \u0418\u043C\u044F \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 -ClusterDialog.FaultToleranceLevel = \u0423\u0440\u043E\u0432\u0435\u043D\u044C \u043E\u0442\u043A\u0430\u0437\u043E\u0443\u0441\u0442\u043E\u0439\u0447\u0438\u0432\u043E\u0441\u0442\u0438 -ClusterDialog.ForceShutdownOfProblematicProcesses = \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0437\u0430\u0432\u0435\u0440\u0448\u0430\u0442\u044C \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u043D\u044B\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B -ClusterDialog.IPPort = IP \u041F\u043E\u0440\u0442 -ClusterDialog.IntervalExceedingAllowedAmountOfMemory = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0433\u043E \u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 -ClusterDialog.IntervalExceedingAllowedAmountOfMemoryWithLineBreak = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0433\u043E\r\n\u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 (\u0441\u0435\u043A\u0443\u043D\u0434) -ClusterDialog.LoadBalancingMode = \u0420\u0435\u0436\u0438\u043C \u0440\u0430\u0441\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F \u043D\u0430\u0433\u0440\u0443\u0437\u043A\u0438 -ClusterDialog.RestartInterval = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A\u0430 (\u0441\u0435\u043A\u0443\u043D\u0434) -ClusterDialog.RestartWorkProcesses = \u041F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A\u0430\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B -ClusterDialog.ShutDownProcessesStopAfter = \u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B \u043E\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0442\u044C \u0447\u0435\u0440\u0435\u0437 -ClusterDialog.ShutDownProcessesStopAfterSecond = \u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B\r\n\u043E\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0442\u044C \u0447\u0435\u0440\u0435\u0437 (\u0441\u0435\u043A\u0443\u043D\u0434) +ClusterDialog.AcceptableDeviationOfTheNumberOfServerErrors = \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0435 \u043E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u0438\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u0430\r\n\u043E\u0448\u0438\u0431\u043E\u043A \u0441\u0435\u0440\u0432\u0435\u0440\u0430 (%) +ClusterDialog.ClusterName = \u0418\u043C\u044F \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 +ClusterDialog.ClusterRecyclingKillByMemoryWithDump = \u0417\u0430\u043F\u0438\u0441\u044B\u0432\u0430\u0442\u044C \u0434\u0430\u043C\u043F \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u0430 \u043F\u0440\u0438 \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u0438 \u043A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0433\u043E \u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 +ClusterDialog.ComputerName = \u0418\u043C\u044F \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 +ClusterDialog.FaultToleranceLevel = \u0423\u0440\u043E\u0432\u0435\u043D\u044C \u043E\u0442\u043A\u0430\u0437\u043E\u0443\u0441\u0442\u043E\u0439\u0447\u0438\u0432\u043E\u0441\u0442\u0438 +ClusterDialog.ForceShutdownOfProblematicProcesses = \u041F\u0440\u0438\u043D\u0443\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0437\u0430\u0432\u0435\u0440\u0448\u0430\u0442\u044C \u043F\u0440\u043E\u0431\u043B\u0435\u043C\u043D\u044B\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B +ClusterDialog.IPPort = IP \u041F\u043E\u0440\u0442 +ClusterDialog.LoadBalancingMode = \u0420\u0435\u0436\u0438\u043C \u0440\u0430\u0441\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F \u043D\u0430\u0433\u0440\u0443\u0437\u043A\u0438 +ClusterDialog.LoadBalancingModeMemoryPriority = \u041F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442 \u043F\u043E \u043F\u0430\u043C\u044F\u0442\u0438 +ClusterDialog.LoadBalancingModePerformancePriority = \u041F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442 \u043F\u043E \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0438 +ClusterDialog.ShutDownProcessesStopAfter = \u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B\r\n\u043E\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0442\u044C \u0447\u0435\u0440\u0435\u0437 (\u0441\u0435\u043A\u0443\u043D\u0434) +ClusterDialog.TitleDialog = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 +ClusterDialog.WorkingProcessesAllowedAmountOfMemory = \u0414\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043E\u0431\u044A\u0435\u043C\r\n\u043F\u0430\u043C\u044F\u0442\u0438 (\u041A\u0431) +ClusterDialog.WorkingProcessesIntervalExceedingAllowedAmountOfMemory = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0433\u043E\r\n\u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 (\u0441\u0435\u043A\u0443\u043D\u0434) +ClusterDialog.WorkingProcessesRestart = \u041F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A\u0430\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B +ClusterDialog.WorkingProcessesRestartInterval = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A\u0430 (\u0441\u0435\u043A\u0443\u043D\u0434) -Dialogs.AppearedInFifteen = \u041F\u043E\u044F\u0432\u0438\u043B\u0441\u044F \u0432 8.3.15 -Dialogs.Apply = \u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C -Dialogs.ClearTheDatabase = \u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445, \u0443\u0431\u0440\u0430\u0432 \u0438\u0437 \u043D\u0435\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B -Dialogs.ConnectionOnly = \u0422\u043E\u043B\u044C\u043A\u043E \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 -Dialogs.Constantly = \u041F\u043E\u0441\u0442\u043E\u044F\u043D\u043D\u043E -Dialogs.DeleteTheEntireDatabase = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445 \u0446\u0435\u043B\u0438\u043A\u043E\u043C -Dialogs.DeprecatedInFifteen = \u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0432 8.3.15 -Dialogs.Disable = \u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043E -Dialogs.DropInfobaseDescription = \u041F\u0440\u0438 \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0438 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B \u043C\u043E\u0436\u043D\u043E \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043E\u0434\u043D\u043E \u0438\u0437 3-\u0445 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439 \u043D\u0430\u0434 \u0431\u0430\u0437\u043E\u0439 \u0434\u0430\u043D\u043D\u044B\u0445, \u0432 \u043A\u043E\u0442\u043E\u0440\u043E\u0439 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u0441\u044F \u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B: -Dialogs.LeaveDatabaseUnchanged = \u041E\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445 \u0438 \u0435\u0435 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0431\u0435\u0437 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 -Dialogs.MemoryPriority = \u041F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442 \u043F\u043E \u043F\u0430\u043C\u044F\u0442\u0438 -Dialogs.Password = \u041F\u0430\u0440\u043E\u043B\u044C -Dialogs.PerformancePriority = \u041F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442 \u043F\u043E \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0438 -Dialogs.Reset = \u0421\u0431\u0440\u043E\u0441 -Dialogs.ResetToPROF = \u0421\u0431\u0440\u043E\u0441 \u043D\u0430 \u041F\u0420\u041E\u0424 -Dialogs.SecurityLevel = \u0417\u0430\u0449\u0438\u0449\u0435\u043D\u043D\u043E\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 -Dialogs.Username = \u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F +Dialogs.AppearedInFifteen = \u041F\u043E\u044F\u0432\u0438\u043B\u0441\u044F \u0432 8.3.15 +Dialogs.Apply = \u041F\u0440\u0438\u043C\u0435\u043D\u0438\u0442\u044C +Dialogs.ConnectionOnly = \u0422\u043E\u043B\u044C\u043A\u043E \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 +Dialogs.Constantly = \u041F\u043E\u0441\u0442\u043E\u044F\u043D\u043D\u043E +Dialogs.DeprecatedInFifteen = \u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0432 8.3.15 +Dialogs.Disable = \u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043E +Dialogs.MemoryPriority = \u041F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442 \u043F\u043E \u043F\u0430\u043C\u044F\u0442\u0438 (\u0443\u0434\u0430\u043B\u0438\u0442\u044C) +Dialogs.Password = \u041F\u0430\u0440\u043E\u043B\u044C +Dialogs.PerformancePriority = \u041F\u0440\u0438\u043E\u0440\u0438\u0442\u0435\u0442 \u043F\u043E \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0438 (\u0443\u0434\u0430\u043B\u0438\u0442\u044C) +Dialogs.Reset = \u0421\u0431\u0440\u043E\u0441 +Dialogs.ResetToPROF = \u0421\u0431\u0440\u043E\u0441 \u043D\u0430 \u041F\u0420\u041E\u0424 +Dialogs.SecurityLevel = \u0417\u0430\u0449\u0438\u0449\u0435\u043D\u043D\u043E\u0435 \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 +Dialogs.Username = \u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F InfobaseDialog.AllowDistributeLicense = \u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C \u0432\u044B\u0434\u0430\u0447\u0443 \u043B\u0438\u0446\u0435\u043D\u0437\u0438\u0439\r\n\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u043C 1\u0421:\u041F\u0440\u0435\u0434\u043F\u0440\u0438\u044F\u0442\u0438\u044F +InfobaseDialog.ClearTheDatabase = \u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445, \u0443\u0431\u0440\u0430\u0432 \u0438\u0437 \u043D\u0435\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B InfobaseDialog.CreateDatabaseIfNotAvailable = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445 \u0432 \u0441\u043B\u0443\u0447\u0430\u0435 \u0435\u0435 \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0438\u044F InfobaseDialog.DBMSType = \u0422\u0438\u043F \u0421\u0423\u0411\u0414 InfobaseDialog.DatabaseDBName = \u0411\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445 InfobaseDialog.DatabaseDBPassword = \u041F\u0430\u0440\u043E\u043B\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0411\u0414 InfobaseDialog.DatabaseDBUser = \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u0411\u0414 InfobaseDialog.DateOffset = \u0421\u043C\u0435\u0449\u0435\u043D\u0438\u0435 \u0434\u0430\u0442 -InfobaseDialog.DeniedFrom = \u041D\u0430\u0447\u0430\u043B\u043E (yyyy-mm-dd hh:mm:ss): -InfobaseDialog.DeniedMessage = \u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 -InfobaseDialog.DeniedParameter = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438 -InfobaseDialog.DeniedTo = \u041A\u043E\u043D\u0435\u0446 (yyyy-mm-dd hh:mm:ss): +InfobaseDialog.DeleteTheEntireDatabase = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445 \u0446\u0435\u043B\u0438\u043A\u043E\u043C InfobaseDialog.Description = \u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 +InfobaseDialog.DropInfobaseDescription = \u041F\u0440\u0438 \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0438 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B \u043C\u043E\u0436\u043D\u043E \u0432\u044B\u0431\u0440\u0430\u0442\u044C \u043E\u0434\u043D\u043E \u0438\u0437 3-\u0445 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439 \u043D\u0430\u0434 \u0431\u0430\u0437\u043E\u0439 \u0434\u0430\u043D\u043D\u044B\u0445, \u0432 \u043A\u043E\u0442\u043E\u0440\u043E\u0439 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u0441\u044F \u0434\u0430\u043D\u043D\u044B\u0435 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u043E\u0439 \u0431\u0430\u0437\u044B: InfobaseDialog.ExternalSessionManagement = \u0412\u043D\u0435\u0448\u043D\u0435\u0435 \u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u0430\u043C\u0438 -InfobaseDialog.IBMDB2 = IBMDB2 InfobaseDialog.InfobaseName = \u0418\u043C\u044F +InfobaseDialog.LeaveDatabaseUnchanged = \u041E\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0431\u0430\u0437\u0443 \u0434\u0430\u043D\u043D\u044B\u0445 \u0438 \u0435\u0435 \u0441\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0431\u0435\u0437 \u0438\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u0439 InfobaseDialog.Locale = \u042F\u0437\u044B\u043A (\u0421\u0442\u0440\u0430\u043D\u0430) -InfobaseDialog.MSSQLServer = MSSQLServer -InfobaseDialog.OracleDatabase = OracleDatabase -InfobaseDialog.PermissionCode = \u041A\u043E\u0434 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F -InfobaseDialog.PostgreSQL = PostgreSQL InfobaseDialog.RequiredUseOfExternalManagement = \u041E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0432\u043D\u0435\u0448\u043D\u0435\u0433\u043E \u0443\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u044F InfobaseDialog.SafeModeSecurityProfile = \u041F\u0440\u043E\u0444\u0438\u043B\u044C \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u0438\r\n\u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0433\u043E \u0440\u0435\u0436\u0438\u043C\u0430 InfobaseDialog.SecurityProfile = \u041F\u0440\u043E\u0444\u0438\u043B\u044C \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u0438 InfobaseDialog.ServerDBName = \u0421\u0435\u0440\u0432\u0435\u0440 \u0431\u0430\u0437 \u0434\u0430\u043D\u043D\u044B\u0445 InfobaseDialog.SessionsDenied = \u0411\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0430 \u043D\u0430\u0447\u0430\u043B\u0430 \u0441\u0435\u0430\u043D\u0441\u043E\u0432 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0430 +InfobaseDialog.SessionsDeniedFrom = \u041D\u0430\u0447\u0430\u043B\u043E (yyyy-mm-dd hh:mm:ss): +InfobaseDialog.SessionsDeniedMessage = \u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 +InfobaseDialog.SessionsDeniedParameter = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440 \u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438 +InfobaseDialog.SessionsDeniedTo = \u041A\u043E\u043D\u0435\u0446 (yyyy-mm-dd hh:mm:ss): +InfobaseDialog.SessionsPermissionCode = \u041A\u043E\u0434 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u044F InfobaseDialog.SheduledJobsDenied = \u0411\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0430 \u0440\u0435\u0433\u043B\u0430\u043C\u0435\u043D\u0442\u043D\u044B\u0445 \u0437\u0430\u0434\u0430\u043D\u0438\u0439 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0430 +InfobaseDialog.TitleDialog = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B +InfobaseDialog.TitleDropInfobaseParameters = \u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B InfobaseDialog.YouNeedToEnter = \u043D\u0443\u0436\u043D\u043E \u0437\u0430\u043F\u043E\u043B\u043D\u0438\u0442\u044C -InfobaseDialog.en_US = en_US -InfobaseDialog.ru_RU = ru_RU -ServerDialog.AgentParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0430\u0433\u0435\u043D\u0442\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -ServerDialog.AutoconnectAtStartup = \u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0430\u0442\u044C\u0441\u044F \u043F\u0440\u0438 \u0441\u0442\u0430\u0440\u0442\u0435 -ServerDialog.CentralServerAdminstrator = \u0410\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0430\u0442\u043E\u0440 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -ServerDialog.ConnectParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F -ServerDialog.Credentials = \u0423\u0447\u0435\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 -ServerDialog.Description = \u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 -ServerDialog.Host = \u0425\u043E\u0441\u0442 -ServerDialog.ID = ID -ServerDialog.LocalRASParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0433\u043E RAS -ServerDialog.Name = \u0418\u043C\u044F -ServerDialog.Password = \u041F\u0430\u0440\u043E\u043B\u044C -ServerDialog.Port = \u041F\u043E\u0440\u0442 -ServerDialog.RemoteRASParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0443\u0434\u0430\u043B\u0435\u043D\u043D\u043E\u0433\u043E RAS -ServerDialog.SaveCredentials = \u0421\u043E\u0445\u0440\u0430\u043D\u044F\u0442\u044C \u0443\u0447\u0435\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 -ServerDialog.Type = \u0422\u0438\u043F -ServerDialog.UseLocalRAS = \u0417\u0430\u043F\u0443\u0441\u043A\u0430\u0442\u044C \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439 RAS -ServerDialog.UseRemoteRAS = \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0443\u0434\u0430\u043B\u0435\u043D\u043D\u044B\u0439 RAS -ServerDialog.User = \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C -ServerDialog.Username = \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C -ServerDialog.V8Version = \u0412\u0435\u0440\u0441\u0438\u044F V8 +ServerDialog.AgentParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0430\u0433\u0435\u043D\u0442\u0430 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +ServerDialog.AutoconnectAtStartup = \u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0430\u0442\u044C\u0441\u044F \u043F\u0440\u0438 \u0441\u0442\u0430\u0440\u0442\u0435 +ServerDialog.CentralServerAdminstrator = \u0410\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0430\u0442\u043E\u0440 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +ServerDialog.ClusterName = \u0418\u043C\u044F \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 +ServerDialog.ClustersCredentialsGroup = \u0414\u0430\u043D\u043D\u044B\u0435 \u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u043A \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430\u043C +ServerDialog.ConnectParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F +ServerDialog.Credentials = \u0414\u0430\u043D\u043D\u044B\u0435 \u0434\u043E\u0441\u0442\u0443\u043F\u0430 +ServerDialog.Description = \u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 +ServerDialog.Host = \u0425\u043E\u0441\u0442 +ServerDialog.ID = ID +ServerDialog.InfobaseName = \u0418\u043C\u044F \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B +ServerDialog.InfobasesCredentialsGroup = \u0414\u0430\u043D\u043D\u044B\u0435 \u0434\u043E\u0441\u0442\u0443\u043F\u0430 \u043A \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0430\u043C +ServerDialog.LocalRASParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0437\u0430\u043F\u0443\u0441\u043A\u0430 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u043E\u0433\u043E RAS +ServerDialog.Password = \u041F\u0430\u0440\u043E\u043B\u044C +ServerDialog.Port = \u041F\u043E\u0440\u0442 +ServerDialog.RemoteRASParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0443\u0434\u0430\u043B\u0435\u043D\u043D\u043E\u0433\u043E RAS +ServerDialog.SaveCredentialsName = \u0422\u043E\u043B\u044C\u043A\u043E \u0438\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F +ServerDialog.SaveCredentialsNamePass = \u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u0438 \u043F\u0430\u0440\u043E\u043B\u044C +ServerDialog.SaveCredentialsNone = \u041D\u0435 \u0441\u043E\u0445\u0440\u0430\u043D\u044F\u0442\u044C +ServerDialog.SaveCredentialsVariant = \u0412\u0430\u0440\u0438\u0430\u043D\u0442 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u0434\u0430\u043D\u043D\u044B\u0445 \u0434\u043E\u0441\u0442\u0443\u043F\u0430 +ServerDialog.SetNewUserPassword = \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u043D\u043E\u0432\u044B\u0439 \u043B\u043E\u0433\u0438\u043D/\u043F\u0430\u0440\u043E\u043B\u044C +ServerDialog.ShowPasswordModeToolTipText = \u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C/\u0441\u043A\u0440\u044B\u0442\u044C \u043F\u0430\u0440\u043E\u043B\u0438 +ServerDialog.TitleDialog = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0441\u0435\u0440\u0432\u0435\u0440\u0430 1\u0421:\u041F\u0440\u0435\u0434\u043F\u0440\u0438\u044F\u0442\u0438\u0435 +ServerDialog.UseLocalRAS = \u0417\u0430\u043F\u0443\u0441\u043A\u0430\u0442\u044C \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439 RAS +ServerDialog.UseRemoteRAS = \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0443\u0434\u0430\u043B\u0435\u043D\u043D\u044B\u0439 RAS +ServerDialog.Username = \u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F +ServerDialog.V8Version = \u0412\u0435\u0440\u0441\u0438\u044F V8 -SettingsDialog.English = \u0410\u043D\u0433\u043B\u0438\u0439\u0441\u043A\u0438\u0439 -SettingsDialog.ExpandClusters = \u041A\u043B\u0430\u0441\u0442\u0435\u0440\u044B -SettingsDialog.ExpandInfobases = \u0418\u043D\u0444\u043E\u0431\u0430\u0437\u044B -SettingsDialog.ExpandNodesInTree = \u0420\u0430\u0437\u0432\u043E\u0440\u0430\u0447\u0438\u0432\u0430\u0442\u044C \u0443\u0437\u043B\u044B \u0432 \u0434\u0435\u0440\u0435\u0432\u0435 -SettingsDialog.ExpandServers = \u0421\u0435\u0440\u0432\u0435\u0440\u0430 -SettingsDialog.ExpandWorkingProcesses = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B -SettingsDialog.ExpandWorkingServers = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -SettingsDialog.Highlight = \u041F\u043E\u0434\u0441\u0432\u0435\u0447\u0438\u0432\u0430\u043D\u0438\u0435 -SettingsDialog.HighlightDuration = \u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u043F\u043E\u0434\u0441\u0432\u0435\u0442\u043A\u0438 (\u0441\u0435\u043A) -SettingsDialog.HighlightNewItems = \u041F\u043E\u0434\u0441\u0432\u0435\u0447\u0438\u0432\u0430\u0442\u044C \u043D\u043E\u0432\u044B\u0435 \u0441\u0442\u0440\u043E\u043A\u0438 -SettingsDialog.Locale = \u042F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 (\u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A) -SettingsDialog.ReadClipboard = \u0427\u0438\u0442\u0430\u0442\u044C \u0431\u0443\u0444\u0435\u0440 \u043E\u0431\u043C\u0435\u043D\u0430 -SettingsDialog.Russian = \u0420\u0443\u0441\u0441\u043A\u0438\u0439 -SettingsDialog.ShadowSleepSessions = \u0417\u0430\u0442\u0435\u043D\u044F\u0442\u044C \u0441\u043F\u044F\u0446\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u044B -SettingsDialog.ShowInfo = \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F -SettingsDialog.ShowInfobaseDescription = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B -SettingsDialog.ShowLocalRASConnectInfo = \u041E \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0438 \u0447\u0435\u0440\u0435\u0437 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439 RAS -SettingsDialog.ShowNodesInTree = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0443\u0437\u043B\u044B \u0432 \u0434\u0435\u0440\u0435\u0432\u0435 -SettingsDialog.ShowServerDescription = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -SettingsDialog.ShowServerVersion = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0432\u0435\u0440\u0441\u0438\u044E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -SettingsDialog.ShowWorkingProcesses = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B -SettingsDialog.ShowWorkingServers = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -SettingsDialog.System = \u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 +SettingsDialog.CheckUpdate = \u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0442\u044C \u043E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u044F +SettingsDialog.ExpandClusters = \u041A\u043B\u0430\u0441\u0442\u0435\u0440\u044B +SettingsDialog.ExpandInfobases = \u0418\u043D\u0444\u043E\u0431\u0430\u0437\u044B +SettingsDialog.ExpandNodesInTree = \u0420\u0430\u0437\u0432\u043E\u0440\u0430\u0447\u0438\u0432\u0430\u0442\u044C \u0443\u0437\u043B\u044B \u0432 \u0434\u0435\u0440\u0435\u0432\u0435 +SettingsDialog.ExpandServers = \u0421\u0435\u0440\u0432\u0435\u0440\u0430 +SettingsDialog.ExpandWorkingProcesses = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B +SettingsDialog.ExpandWorkingServers = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +SettingsDialog.Highlight = \u041F\u043E\u0434\u0441\u0432\u0435\u0447\u0438\u0432\u0430\u043D\u0438\u0435 +SettingsDialog.HighlightDuration = \u0414\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u043F\u043E\u0434\u0441\u0432\u0435\u0442\u043A\u0438 (\u0441\u0435\u043A) +SettingsDialog.HighlightNewItems = \u041F\u043E\u0434\u0441\u0432\u0435\u0447\u0438\u0432\u0430\u0442\u044C \u043D\u043E\u0432\u044B\u0435 \u0441\u0442\u0440\u043E\u043A\u0438 +SettingsDialog.Locale = \u042F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 (\u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A) +SettingsDialog.LocaleEnglish = \u0410\u043D\u0433\u043B\u0438\u0439\u0441\u043A\u0438\u0439 +SettingsDialog.LocaleRussian = \u0420\u0443\u0441\u0441\u043A\u0438\u0439 +SettingsDialog.LocaleSystem = \u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 +SettingsDialog.ReadClipboard = \u0427\u0438\u0442\u0430\u0442\u044C \u0431\u0443\u0444\u0435\u0440 \u043E\u0431\u043C\u0435\u043D\u0430 (\u043F\u0440\u0438 \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u0438 \u0441\u0435\u0440\u0432\u0435\u0440\u0430) +SettingsDialog.RowSortDirection = \u041D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u043A\u0438 \u0441\u0442\u0440\u043E\u043A +SettingsDialog.RowSortDirectionAsPrevious = \u041A\u0430\u043A \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0430\u044F +SettingsDialog.RowSortDirectionAscending = \u041F\u043E \u0443\u0431\u044B\u0432\u0430\u043D\u0438\u044E +SettingsDialog.RowSortDirectionDescending = \u041F\u043E \u0432\u043E\u0437\u0440\u0430\u0441\u0442\u0430\u043D\u0438\u044E +SettingsDialog.ShadowSleepSessions = \u0417\u0430\u0442\u0435\u043D\u044F\u0442\u044C \u0441\u043F\u044F\u0446\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u044B +SettingsDialog.ShowInfo = \u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u0430\u044F \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F +SettingsDialog.ShowInfobaseDescription = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B +SettingsDialog.ShowLocalRASConnectInfo = \u041E \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0438 \u0447\u0435\u0440\u0435\u0437 \u043B\u043E\u043A\u0430\u043B\u044C\u043D\u044B\u0439 RAS +SettingsDialog.ShowNodesInTree = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0443\u0437\u043B\u044B \u0432 \u0434\u0435\u0440\u0435\u0432\u0435 +SettingsDialog.ShowServerDescription = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +SettingsDialog.ShowServerVersion = \u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0432\u0435\u0440\u0441\u0438\u044E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +SettingsDialog.ShowWorkingProcesses = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B +SettingsDialog.ShowWorkingServers = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +SettingsDialog.TitleDialog = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u043F\u0440\u0438\u043B\u043E\u0436\u0435\u043D\u0438\u044F +SettingsDialog.WatchSessions = \u0426\u0432\u0435\u0442 \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0435\u043C\u044B\u0445 \u0441\u0435\u0441\u0441\u0438\u0439 -ViewerArea.About = \u041E \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0435 -ViewerArea.Active = \u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0439 -ViewerArea.AddServer = \u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.ConnPerProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0439 \u043D\u0430 \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 -ViewerArea.ConnectToAllServers = \u041F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043A\u043E \u0432\u0441\u0435\u043C \u0441\u0435\u0440\u0432\u0435\u0440\u0430\u043C -ViewerArea.ConnectToServer = \u041F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043A \u0441\u0435\u0440\u0432\u0435\u0440\u0443 -ViewerArea.Connections = \u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F -ViewerArea.ConnectionsCount = \u0421\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u044F (%s) -ViewerArea.CreateCluster = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440 -ViewerArea.CreateInfobase = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 -ViewerArea.CreateNewInfobaseUsingThis = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u043D\u043E\u0432\u0443\u044E \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044F \u044D\u0442\u0443 -ViewerArea.CreateWorkingServer = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.DedicatedManagers = \u041C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 \u043F\u043E\u0434 \u043A\u0430\u0436\u0434\u044B\u0439 \u0441\u0435\u0440\u0432\u0438\u0441 -ViewerArea.DeleteCluster = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440 -ViewerArea.DeleteClusterQuestion = \u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 \u043F\u0440\u0438\u0432\u0435\u0434\u0435\u0442 \u043A \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u044E \u0435\u0433\u043E \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0438 \u0441\u043F\u0438\u0441\u043A\u0430 \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0445 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u044B\u0445 \u0431\u0430\u0437. \u0412\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440? -ViewerArea.DeleteInfobase = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 -ViewerArea.DeleteWorkingServer = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.Description = \u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 -ViewerArea.DisconnectOfServer = \u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043E\u0442 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -ViewerArea.DisonnectFromAllServers = \u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043E\u0442 \u0432\u0441\u0435\u0445 \u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432 -ViewerArea.EditCluster = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440 -ViewerArea.EditInfobase = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 -ViewerArea.EditServer = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.EditWorkingServer = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.FindNewServers = \u041D\u0430\u0439\u0442\u0438 \u043D\u043E\u0432\u044B\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u044B -ViewerArea.IBPerProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0418\u0411 \u043D\u0430 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 -ViewerArea.IPPort = IP \u043F\u043E\u0440\u0442 -ViewerArea.IPPortMainManager = IP \u043F\u043E\u0440\u0442 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -ViewerArea.InfobasesCount = \u0418\u043D\u0444\u043E\u0431\u0430\u0437\u044B (%s) -ViewerArea.KillConnection = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 -ViewerArea.KillSession = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0435\u0430\u043D\u0441 -ViewerArea.LockSessionsNow = \u041D\u0435\u043C\u0435\u0434\u043B\u0435\u043D\u043D\u043E \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0430\u043D\u0441\u044B -ViewerArea.Locks = \u0411\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438 -ViewerArea.LocksCount = \u0411\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u043A\u0438 (%s) -ViewerArea.MainServer = \u0426\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u044B\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.Memory = \u041F\u0430\u043C\u044F\u0442\u044C, \u041A\u0431 -ViewerArea.MemoryExceeded = \u041F\u0430\u043C\u044F\u0442\u044C \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0430, \u0441 -ViewerArea.NotUsed = \u041D\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0441\u044F -ViewerArea.OpenSettings = \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 -ViewerArea.PID = PID -ViewerArea.Port = \u041F\u043E\u0440\u0442 -ViewerArea.ProcessIsRunning = \u041F\u0440\u043E\u0446\u0435\u0441\u0441 \u0437\u0430\u043F\u0443\u0449\u0435\u043D -ViewerArea.ProcessIsStopped = \u041F\u0440\u043E\u0446\u0435\u0441\u0441 \u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D -ViewerArea.RangeIPPort = \u0414\u0438\u0430\u043F\u0430\u0437\u043E\u043D IP \u043F\u043E\u0440\u0442\u043E\u0432 -ViewerArea.RemoveServer = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.Server = \u0421\u0435\u0440\u0432\u0435\u0440 -ViewerArea.Servers = \u0421\u0435\u0440\u0432\u0435\u0440\u044B -ViewerArea.Service = \u0421\u0435\u0440\u0432\u0438\u0441 -ViewerArea.Session = \u0421\u0435\u0430\u043D\u0441\u044B -ViewerArea.SessionManage = \u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u0430\u043C\u0438 -ViewerArea.Sessions = \u0421\u0435\u0430\u043D\u0441\u044B -ViewerArea.SessionsCount = \u0421\u0435\u0430\u043D\u0441\u044B (%s) -ViewerArea.ShowConnectionError = \u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043E\u0448\u0438\u0431\u043A\u0443 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F -ViewerArea.SleepAfter = \u0423\u0441\u043D\u0443\u0442\u044C \u0447\u0435\u0440\u0435\u0437 -ViewerArea.StartedAt = \u0412\u0440\u0435\u043C\u044F \u0437\u0430\u043F\u0443\u0441\u043A\u0430 -ViewerArea.TerminateAllSessions = \u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044C \u0432\u0441\u0435 \u0441\u0435\u0430\u043D\u0441\u044B -ViewerArea.TerminateUsersSessions = \u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u044B -ViewerArea.Update = \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C -ViewerArea.UpdateInfobases = \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B -ViewerArea.ViewSession = \u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u0441\u0435\u0441\u0441\u0438\u0438 -ViewerArea.WorkingProcesses = \u0420\u0430\u0431\u043E\u0447\u0438\u0439 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 -ViewerArea.WorkingProcessesCount = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u044B (%s) -ViewerArea.WorkingServers = \u0420\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 -ViewerArea.WorkingServersCount = \u0420\u0430\u0431\u043E\u0447\u0438\u0435 \u0441\u0435\u0440\u0432\u0435\u0440\u044B (%s) +ViewerArea.Active = \u0410\u043A\u0442\u0438\u0432\u043D\u044B\u0439 +ViewerArea.ColumnServer = \u0421\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ConnPerProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0439 \u043D\u0430 \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 +ViewerArea.ContextMenu.AddInFavorites = \u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0432 \u0438\u0437\u0431\u0440\u0430\u043D\u043D\u043E\u0435 +ViewerArea.ContextMenu.AddServer = \u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ContextMenu.ConnectToServer = \u041F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043A \u0441\u0435\u0440\u0432\u0435\u0440\u0443 +ViewerArea.ContextMenu.CopyInfobase = \u0421\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 +ViewerArea.ContextMenu.Create = \u0421\u043E\u0437\u0434\u0430\u0442\u044C +ViewerArea.ContextMenu.CreateCluster = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440 +ViewerArea.ContextMenu.CreateInfobase = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 +ViewerArea.ContextMenu.CreateWorkingServer = \u0421\u043E\u0437\u0434\u0430\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ContextMenu.Delete = \u0423\u0434\u0430\u043B\u0438\u0442\u044C +ViewerArea.ContextMenu.DeleteCluster = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440 +ViewerArea.ContextMenu.DeleteFromFavorites = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0438\u0437 \u0438\u0437\u0431\u0440\u0430\u043D\u043D\u043E\u0433\u043E +ViewerArea.ContextMenu.DeleteInfobase = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 +ViewerArea.ContextMenu.DeleteWorkingServer = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ContextMenu.DisconnectOfServer = \u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043E\u0442 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +ViewerArea.ContextMenu.Edit = \u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C +ViewerArea.ContextMenu.EditCluster = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440 +ViewerArea.ContextMenu.EditInfobase = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u0443 +ViewerArea.ContextMenu.EditServer = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ContextMenu.EditWorkingServer = \u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0440\u0430\u0431\u043E\u0447\u0438\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ContextMenu.KillConnection = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 +ViewerArea.ContextMenu.KillSession = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0435\u0430\u043D\u0441 +ViewerArea.ContextMenu.LockSessionsNow = \u041D\u0435\u043C\u0435\u0434\u043B\u0435\u043D\u043D\u043E \u0437\u0430\u0431\u043B\u043E\u043A\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0435\u0430\u043D\u0441\u044B +ViewerArea.ContextMenu.MoveDown = \u041F\u0435\u0440\u0435\u043C\u0435\u0441\u0442\u0438\u0442\u044C \u0432\u043D\u0438\u0437 +ViewerArea.ContextMenu.MoveUp = \u041F\u0435\u0440\u0435\u043C\u0435\u0441\u0442\u0438\u0442\u044C \u0432\u0432\u0435\u0440\u0445 +ViewerArea.ContextMenu.OrderInfobasesBy = \u041F\u043E\u0440\u044F\u0434\u043E\u043A \u043F\u043E... +ViewerArea.ContextMenu.OrderInfobasesByDefault = \u041F\u043E-\u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E +ViewerArea.ContextMenu.OrderInfobasesByFaforitesAndName = \u041F\u043E \u0438\u0437\u0431\u0440\u0430\u043D\u043D\u043E\u043C\u0443/\u0438\u043C\u0435\u043D\u0438 +ViewerArea.ContextMenu.OrderInfobasesByName = \u041F\u043E \u0438\u043C\u0435\u043D\u0438 +ViewerArea.ContextMenu.OrganizeServers = \u041E\u0442\u0441\u043E\u0440\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0432\u0441\u0435 +ViewerArea.ContextMenu.RemoveServer = \u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.ContextMenu.SessionManage = \u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u0430\u043C\u0438 +ViewerArea.ContextMenu.ShowConnectionError = \u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u043E\u0448\u0438\u0431\u043A\u0443 \u043F\u043E\u0434\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u044F +ViewerArea.ContextMenu.TerminateAllSessions = \u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044C \u0432\u0441\u0435 \u0441\u0435\u0430\u043D\u0441\u044B +ViewerArea.ContextMenu.TerminateUsersSessions = \u0417\u0430\u0432\u0435\u0440\u0448\u0438\u0442\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u0441\u0435\u0430\u043D\u0441\u044B +ViewerArea.ContextMenu.Update = \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C +ViewerArea.ContextMenu.UpdateInfobases = \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0438\u043D\u0444\u043E\u0431\u0430\u0437\u044B +ViewerArea.ContextMenu.ViewSession = \u0418\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u044F \u043E \u0441\u0435\u0441\u0441\u0438\u0438 +ViewerArea.DedicatedManagers = \u041C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 \u043F\u043E\u0434 \u043A\u0430\u0436\u0434\u044B\u0439 \u0441\u0435\u0440\u0432\u0438\u0441 +ViewerArea.DeleteClusterQuestion = \u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 \u043F\u0440\u0438\u0432\u0435\u0434\u0435\u0442 \u043A \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u044E \u0435\u0433\u043E \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A \u0438 \u0441\u043F\u0438\u0441\u043A\u0430 \u0437\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0445 \u0438\u043D\u0444\u043E\u0440\u043C\u0430\u0446\u0438\u043E\u043D\u043D\u044B\u0445 \u0431\u0430\u0437. \u0412\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u043A\u043B\u0430\u0441\u0442\u0435\u0440? +ViewerArea.DeleteServerQuestion = \u0412\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043B\u044C\u043D\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0435\u0440\u0432\u0435\u0440 \u0438\u0437 \u0441\u043F\u0438\u0441\u043A\u0430? +ViewerArea.Description = \u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 +ViewerArea.IBPerProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0418\u0411 \u043D\u0430 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 +ViewerArea.IPPort = IP \u043F\u043E\u0440\u0442 +ViewerArea.IPPortMainManager = IP \u043F\u043E\u0440\u0442 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +ViewerArea.InfobasesCount = \u0418\u043D\u0444\u043E\u0431\u0430\u0437\u044B (%s) +ViewerArea.MainMenu.About = \u041E \u043F\u0440\u043E\u0433\u0440\u0430\u043C\u043C\u0435 +ViewerArea.MainMenu.ConnectAllServers = \u041F\u043E\u0434\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043A\u043E \u0432\u0441\u0435\u043C \u0441\u0435\u0440\u0432\u0435\u0440\u0430\u043C +ViewerArea.MainMenu.DisonnectAllServers = \u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043E\u0442 \u0432\u0441\u0435\u0445 \u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432 +ViewerArea.MainMenu.FindServers = \u041D\u0430\u0439\u0442\u0438 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +ViewerArea.MainMenu.OpenSettings = \u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 +ViewerArea.MainMenu.Servers = \u0421\u0435\u0440\u0432\u0435\u0440\u0430 +ViewerArea.MainMenu.Service = \u0421\u0435\u0440\u0432\u0438\u0441 +ViewerArea.MainServer = \u0426\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u044B\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 +ViewerArea.Memory = \u041F\u0430\u043C\u044F\u0442\u044C, \u041A\u0431 +ViewerArea.MemoryExceeded = \u041F\u0430\u043C\u044F\u0442\u044C \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0430, \u0441 +ViewerArea.NotUsed = \u041D\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442\u0441\u044F +ViewerArea.PID = PID +ViewerArea.Port = \u041F\u043E\u0440\u0442 +ViewerArea.ProcessIsRunning = \u041F\u0440\u043E\u0446\u0435\u0441\u0441 \u0437\u0430\u043F\u0443\u0449\u0435\u043D +ViewerArea.ProcessIsStopped = \u041F\u0440\u043E\u0446\u0435\u0441\u0441 \u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D +ViewerArea.RangeIPPort = \u0414\u0438\u0430\u043F\u0430\u0437\u043E\u043D IP \u043F\u043E\u0440\u0442\u043E\u0432 +ViewerArea.SleepAfter = \u0423\u0441\u043D\u0443\u0442\u044C \u0447\u0435\u0440\u0435\u0437 +ViewerArea.StartedAt = \u0412\u0440\u0435\u043C\u044F \u0437\u0430\u043F\u0443\u0441\u043A\u0430 -WorkingServerDialog.ComputerName = \u0418\u043C\u044F \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 -WorkingServerDialog.ConnectionsPerWorkingProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0439\r\n\u043D\u0430 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 -WorkingServerDialog.CriticalProcessesTotalMemory = \u041A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0439 \u043E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438\r\n\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0431\u0430\u0439\u0442) -WorkingServerDialog.IPPort = IP \u043F\u043E\u0440\u0442 -WorkingServerDialog.IPPortMainClusterManager = IP \u043F\u043E\u0440\u0442 \u0433\u043B\u0430\u0432\u043D\u043E\u0433\u043E \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u0430 \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 -WorkingServerDialog.InfobasesPerWorkingProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0418\u0411 \u043D\u0430 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 -WorkingServerDialog.IsDedicatedManagers = \u041C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 \u043F\u043E\u0434 \u043A\u0430\u0436\u0434\u044B\u0439 \u0441\u0435\u0440\u0432\u0438\u0441 -WorkingServerDialog.IsMainServer = \u0426\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u044B\u0439 \u0441\u0435\u0440\u0432\u0435\u0432\u0440 -WorkingServerDialog.Megabytes = \ \u041C\u0431 -WorkingServerDialog.Minutes = \ \u041C\u0438\u043D -WorkingServerDialog.PortRange = \u0414\u0438\u0430\u043F\u0430\u0437\u043E\u043D \u043F\u043E\u0440\u0442\u043E\u0432 -WorkingServerDialog.SafeCallMemoryLimit = \u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439 \u0440\u0430\u0441\u0445\u043E\u0434 \u043F\u0430\u043C\u044F\u0442\u0438\r\n\u0437\u0430 \u043E\u0434\u0438\u043D \u0432\u044B\u0437\u043E\u0432 (\u0431\u0430\u0439\u0442) -WorkingServerDialog.SafeWorkingProcessesMemoryLimit = \u041C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u043E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438\r\n\u0440\u0430\u0431\u043E\u0447\u0438\u0445 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0431\u0430\u0439\u0442) -WorkingServerDialog.ServerName = \u0418\u043C\u044F \u0441\u0435\u0440\u0432\u0435\u0440\u0430 -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryLabel = \u0412\u0440\u0435\u043C\u0435\u043D\u043D\u043E \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043E\u0431\u044A\u0435\u043C\r\n\u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0431\u0430\u0439\u0442) -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitLabel = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0433\u043E\r\n\u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0441\u0435\u043A\u0443\u043D\u0434) -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimitToolTip = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0433\u043E \u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 -WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryToolTip = \u0412\u0440\u0435\u043C\u0435\u043D\u043D\u043E \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 -WorkingServerDialog.WorkingProcessMemoryLimit = \u041E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438 \u0440\u0430\u0431\u043E\u0447\u0438\u0445 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432,\r\n\u0434\u043E \u043A\u043E\u0442\u043E\u0440\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440 \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044F\r\n\u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u043C (\u0431\u0430\u0439\u0442) -WorkingServerDialog.WorkingProcessesParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0440\u0430\u0431\u043E\u0447\u0438\u0445 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 +WorkingServerDialog.ComputerName = \u0418\u043C\u044F \u043A\u043E\u043C\u043F\u044C\u044E\u0442\u0435\u0440\u0430 +WorkingServerDialog.ConnectionsPerWorkingProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0441\u043E\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0439\r\n\u043D\u0430 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 +WorkingServerDialog.CriticalProcessesTotalMemory = \u041A\u0440\u0438\u0442\u0438\u0447\u0435\u0441\u043A\u0438\u0439 \u043E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438\r\n\u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0431\u0430\u0439\u0442) +WorkingServerDialog.IPPort = IP \u043F\u043E\u0440\u0442 +WorkingServerDialog.IPPortMainClusterManager = IP \u043F\u043E\u0440\u0442 \u0433\u043B\u0430\u0432\u043D\u043E\u0433\u043E \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u0430 \u043A\u043B\u0430\u0441\u0442\u0435\u0440\u0430 +WorkingServerDialog.InfobasesPerWorkingProcessLimit = \u041A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u0418\u0411 \u043D\u0430 \u043F\u0440\u043E\u0446\u0435\u0441\u0441 +WorkingServerDialog.IsDedicatedManagers = \u041C\u0435\u043D\u0435\u0434\u0436\u0435\u0440 \u043F\u043E\u0434 \u043A\u0430\u0436\u0434\u044B\u0439 \u0441\u0435\u0440\u0432\u0438\u0441 +WorkingServerDialog.IsMainServer = \u0426\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u044B\u0439 \u0441\u0435\u0440\u0432\u0435\u0440 +WorkingServerDialog.Megabytes = \ \u041C\u0431 +WorkingServerDialog.Minutes = \ \u041C\u0438\u043D +WorkingServerDialog.PortRange = \u0414\u0438\u0430\u043F\u0430\u0437\u043E\u043D \u043F\u043E\u0440\u0442\u043E\u0432 +WorkingServerDialog.SafeCallMemoryLimit = \u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439 \u0440\u0430\u0441\u0445\u043E\u0434 \u043F\u0430\u043C\u044F\u0442\u0438\r\n\u0437\u0430 \u043E\u0434\u0438\u043D \u0432\u044B\u0437\u043E\u0432 (\u0431\u0430\u0439\u0442) +WorkingServerDialog.SafeWorkingProcessesMemoryLimit = \u041C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u043E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438\r\n\u0440\u0430\u0431\u043E\u0447\u0438\u0445 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0431\u0430\u0439\u0442) +WorkingServerDialog.ServerName = \u0418\u043C\u044F \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +WorkingServerDialog.TemporaryAllowedProcessesTotalMemory = \u0412\u0440\u0435\u043C\u0435\u043D\u043D\u043E \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u044B\u0439 \u043E\u0431\u044A\u0435\u043C\r\n\u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0431\u0430\u0439\u0442) +WorkingServerDialog.TemporaryAllowedProcessesTotalMemoryTimeLimit = \u0418\u043D\u0442\u0435\u0440\u0432\u0430\u043B \u043F\u0440\u0435\u0432\u044B\u0448\u0435\u043D\u0438\u044F \u0434\u043E\u043F\u0443\u0441\u0442\u0438\u043C\u043E\u0433\u043E\r\n\u043E\u0431\u044A\u0435\u043C\u0430 \u043F\u0430\u043C\u044F\u0442\u0438 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 (\u0441\u0435\u043A\u0443\u043D\u0434) +WorkingServerDialog.TitleDialog = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0440\u0430\u0431\u043E\u0447\u0435\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440\u0430 +WorkingServerDialog.WorkingProcessMemoryLimit = \u041E\u0431\u044A\u0435\u043C \u043F\u0430\u043C\u044F\u0442\u0438 \u0440\u0430\u0431\u043E\u0447\u0438\u0445 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432,\r\n\u0434\u043E \u043A\u043E\u0442\u043E\u0440\u043E\u0433\u043E \u0441\u0435\u0440\u0432\u0435\u0440 \u0441\u0447\u0438\u0442\u0430\u0435\u0442\u0441\u044F\r\n\u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u043C (\u0431\u0430\u0439\u0442) +WorkingServerDialog.WorkingProcessesParameters = \u041F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B \u0440\u0430\u0431\u043E\u0447\u0438\u0445 \u043F\u0440\u043E\u0446\u0435\u0441\u0441\u043E\u0432 diff --git a/clusterAdminLibrary/src/main/resources/icons/favorites.png b/clusterAdminLibrary/src/main/resources/icons/favorites.png new file mode 100644 index 0000000000000000000000000000000000000000..9c663e57d49898eba0297e40f47a2711b9b388ce GIT binary patch literal 677 zcmV;W0$TlvP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0y;@VK~y+TW1uOh z%T6w9FUy<^h?=kftD&#GpfocJ8(0wo!#{?dhhM*W{`T*==TG0=eDd)16(&aJ zgHu+nyvbOan#!)J%K9$YSCETOKnAFmoq^%cPX>nn|Dc+ofD!0hkbywz+n0L`+xLF? zf8fANMdoAY&i&Ppmi?$Ie$Pvo?KV(>FiXfh>?L!31|qG;Q6wb;n|C?471nrPWkd*yx`c`vxq=E za^d<3PBw!Viqb!Pgv3;_8u04bb%tpxcsd(rZYTz61_6|4{PmA(-K+OJK+Vv=`~M4w ze?Ztk@cyd+!`qK6>!4gPKr!I=ubQTxDSRyp@6B6A*tt4>m|zk{cMd z|8=0s!2rd8|NsAKNCHXPCTPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!TU{2F<6L=Y`H5|skVq1NMx9MA(zV^w%hF~J&ZUJ zu-onY;c&QAtJR##J_@!v(FjVV63pjw z$mjE5Hk%=tOscSzj}C|90Tn=J4VbvhWHMl}SU|XaJRU{(5U-ZI;+)c1wmjKhL)R3r68BfK{y}IpMLDRlscqR-I?tc!_2dwm}R;z93VG$<+ zI13j@aw(NcN4;MECZ>OjlYaqkVemyle@p%c0Qe5tL+p%6E*kOx0000Px#1ZP1_K>z@;j|==^1poj532;bRa{vGizyJUazyWI3i3tDz0y9ZOK~zXf?UPMN z6k!<0|2wX(1S^V%B&&@~LQo?LBJdK_B{~INI+Ro-MA4y$5;}+{A%dcygHQ)g9y&!B z2^DoKp*3o$pmr5qcZ)S0T|ZWx{?E)i12yyR6m%%)2S1+YeTR9Tc|QjK`L{TDf2x93 zs^KpYQBeyEZe{3}lr~U#XPiEueGd;eWEi!SZNTC?8J^L&J>lmY?O>C)&d`scqK+=A zD=yU1Gfo;zSc7*emg9|zfrK@vqSxu7J^GOa+DprBb6A6RdVrpzo%Ax51D9O3Z$Isz zTEY(bBtyS5!U~;oQu{VVofIc{$ahulBWwlR=_M-HQVMQVNQ&4=;5?N^yZH5dL67f{ zlf&1n_HETH%%3+Rj}45b*I~!LF71UVhwqS$6@J`85@v1)#rzPk^Z`c6{l9)6Ujwr+ zhSwjfkc;C2Lr64$bIelD*ylh07*qoM6N<$ Ef`vCJ0RR91 literal 0 HcmV?d00001 diff --git a/clusterAdminLibrary/src/main/resources/icons/infobase_favorite_left.png b/clusterAdminLibrary/src/main/resources/icons/infobase_favorite_left.png new file mode 100644 index 0000000000000000000000000000000000000000..5a8ca2c2f27c11b1e259e71c39c45e3229c648bf GIT binary patch literal 661 zcmV;G0&4wPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!2kdb!2!6DYwZ940xC&FK~zXf?UYSu z6G0Tm|4m{lNUEV~E43sbMS`UsDtHm}&?1N@51u?I6a_!odhjB6 zlG0lb3Ldm*TCixfwhg9j4gtG$O~^Lu|Lu;2usazMJqZ5b$D5fY?`7WXEdKLvap38~ z8X8s8U!qAxElikVxIhomPU_MHI!vz)A8Maw)Y7m3lkZ@7K{t2{K`gqLMc(++AQ2UH zoTR$sLV}*~hvAqCOsLq1cPfTrDj+Q!qTjt)J!N{G#=V&aQ-M9Sk4hVk(#!Os8lR#4 zw1;Xj9r7`T`~D0LmA6M|r!jws0Uq)_H4b3ffxM!F^b3`QTa_}-)AMvY)neMgBL->F z4O);j^7A)xC(b_UU$@C|9IQ_!Lvxu59AU^(-R*UT63=3&RnWWtRA??!i+0n~R4!Xh z78EOV^zN>5tRpdlZEYn?PmaqC4`ABCLx#gtTJ@5;kN3s1bDt*AR9ix{Jc~@qPcfBW zK_#B%Uv9ycR0bP2w|NgtJGe=!^f-M$v-Yxu7V9>;lh0R^3tgR2bho}jt9=X0UrTD$ zP=K%B7(*|Wb12H%!0Tog9hWfsd6G?&Pm#i{pfEFrZ^?5=cV$*9H*8TOa-(6w2K@#hiBL{Q4GJ0x0000DNk~Le0000G0000G2nGNE03Y-JVUZy;e*+Rp zL_t(IPjypEXjE4i{?B9XYbMT}J1>(-bQ+SF#`l9%No;%;X|WYobbDBLWeMA?uj1V_i0h5ext(;X{oO3UDDke@gIejpA{P zkx&OPLUkqjP!aBOUo?Du8KLt0g6my4v3qcJB2tpP{;>#rQ*w4c88^NkE6)EucyEHM zZpRD_Y(+PO1g7p#^!?X_Z-T3wVPqi)iNO#{F^Sf;y z8DID0v`<@XqW?X^3aWG#e~z*D+>nh4KB5uSzq8HkJlvCvT^{~-?pYa)2BpzQ$-(2@ z?J2ak?1@pGqKpKfBL)BL^QquE*>-U#s_H+6F+M2>-L7e7uBUBf`o@d$sydfj3BlV9 zzSu0M#_wEx;GVJ!T#V{uw-d!)VJ5hXDWDZ9`5S~FC0PIya~1eyf4Be@PmNwMgrbR* z+uEO=oRe;A0@r6N%%5Fi0m5Jj4iVCN;HXVB{aaOwg%IW(5Pw}|957amL#kgG$Jl&i zqdSybpEtI)XSMxKl&%#LS!IvCq@0Ti4(eB=6d8bb&Xyn%5qR-cYLz?k<-uIZZtF|0 z8JTuEQf3W(lB>{XfByygYnSy>*R3vEQR5OpYWnXtLwQ3Pz`FTkcTdZ7-$0vbKSmCr zs}B$mlgc-@pvlBk8BU{Pr@v55g@z0B*?Qe4*_ezQCajmzre*&jT zL_t(YOYM|TNEBfdz~9X5&Z;Zw?wZ!F8s=F3p%Re|4Gb;9NCWo}5m834DP$BS<)77A&1^xpO&t@*UB_>FGy5If+*!9SLG**i`^)!+_r3Yx zKYtyD>X_6V5KO2VPU?TOpuR_U z5+q&&i8rw_wRNZ;h{*rgT@fS->Nhslb{~4wH{G6@_7ggSTI3Irm|E&{N?E7Yzm&u}|9Z0Ap_kE*{!< zzBZ%Np2`ZU3e1vBeD``5n=q$sSrjoxgokfK)sOOe67nuL)SWsp%@wq2zDmeIRe9bG zo0a9;9xt3}>s~mW%(F~Qe@V(U%%`A4VRQ%WC{>y{ z)UI`+J{tZS8r$RKGcaw{i#A}?ppI&tw!R5!MUWlEnUYK_Xy%~g;)s$oK|5K?ZzSd& z;D}Ue8dCYJagjGMBEx{X8de3O0{47)Q!2zW7OaZDqF;he-RvorvyLiH zpxc`c1cz|EZ~<(oEL`dc4BdYzmC;h2E!Xr{&Q_;?xOFaT|GUXm5Hl};$!vjKe>=DZ zOUwrG{^Ym_+j*E7>4z^Pub?1Xdvs&-#|`jDgZbbr1n2yKYf7V=F?>yp$aR?OZB|a0 zlhzqKzYMOFWmsAvLg1TQBmG|a{lsjzla}iI_8nxUaiuQ1xd=BX>a#Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0fk9KK~y+TV;FG2 z2&GYgf>(Pel!*@3KG;_I56T7utOf*DuKmx+!^`mh|9^(pZ$B~o2a5gs^@HL5{U>Zd z1AaqPK>!n!MghNm|7G~_ED%=Pv?*%)dbV5*QYzz~UeR1Xx*^ z{}>r+EH^gO-^9tw0~JL8W;S*PX$AT9lG2h(85tRWL4_HZp)|w0o4cPeOIls#Z-Vb`E;|Ai1Om7LAn@wyj$7Pvwr}_ac)kBaeFrmu ziQyl^r+4qNZfz)D0TzG)6azru#pP|Md6gWv`S^IPL56?~U<9UwFCX4_-dJ1E2~`FM zSYzSsoA(tjpTAfIasvo|{rF+k_pje7!IEeIYf1zG1+O*^aS8D~AQyc3^ugu9wyGac mDdGVzYK1`<%B2NhU;qH7^_dZDGM9${0000Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!TW(204cR z|J1nU?bd#{y%(wi0kFD2SVXWxTv8(JKadT=-24JzoZMXPU`aH9;R3^`saaC8(yjlX zW`F(m6G$>LaBy(g@G987cyoQ{S+E2YpctSNHqlpJL3ZIkMrOFnAO?V30yKn^!-GrK z=FGdByY7GmfdH;h)vwD$O;v6=8wVRR8!M*ISXr1DSlL)vM8rf^DtdPqK!p(o{QmQo z<=pujk!Md`^!xt#3se*V{{H&O@btmMz~@h&NB{r-pA9MubQc!jQMB?u6FV1}{p!s} zFwOG+H^Yl(FW4SztNaZXfC5an0s$iH)t4?6=tHyeZo xVr&5m0$7a&ro>Pv6CJDthQU85dr$xd1_0HmT9vfM|F-}D002ovPDHLkV1oL9wCex> literal 0 HcmV?d00001 diff --git a/clusterAdminLibrary/src/main/resources/icons/server_up_24.png b/clusterAdminLibrary/src/main/resources/icons/server_connected_24.png similarity index 100% rename from clusterAdminLibrary/src/main/resources/icons/server_up_24.png rename to clusterAdminLibrary/src/main/resources/icons/server_connected_24.png diff --git a/clusterAdminLibrary/src/main/resources/icons/server_down_24.png b/clusterAdminLibrary/src/main/resources/icons/server_disconnect_24.png similarity index 100% rename from clusterAdminLibrary/src/main/resources/icons/server_down_24.png rename to clusterAdminLibrary/src/main/resources/icons/server_disconnect_24.png diff --git a/clusterAdminLibrary/src/main/resources/icons/sort.png b/clusterAdminLibrary/src/main/resources/icons/sort.png new file mode 100644 index 0000000000000000000000000000000000000000..9acbbb01c57175221c3eee17d42e2cfc60f2850a GIT binary patch literal 505 zcmVPx#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D0gg#TK~y+TjgrkP zgi#cS?@T^6mQvCb#h6%=k_}@qrfeoDt1-lsjbhVvRfjKgaQlTNEeocV%DXm@=_(bB z^kA(L8|9U{3)oi5N#z>Hu%wmP&^1Qp31eI)LbD|AJ76Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!TD zc5o6Wv0YRwA}Uf9o_c!j?Q5XPCrA!l&b^28JAW^{d=X^*DA8zC9F0cr_WS)gJ>Sw1 z=?p|sd@vXc_aqYY`zQYeaJgL0-EQ|;uh-lBem_{PRv-|1y&ezCr zP=HFM;x@Hf%@pU@g|+aWvhO>c4o)T$OeT{!o6V4hh3$5mm!He!c=`Q)9|M5^Qp+D1 z`?v)%e4-MsGntHNx7(pqDgkW+XzDN=4j~?o0}T+0#UgCC+dKunV%*a;2C27OlgVTW z27{o}>3{|b>-8FHwHgctgI^RdLzUgh$n%dB4u_BD^LdoOb6V>enb@3u(0R~mwO^~% g>hHgvuS5X;0K+2J099RJga7~l07*qoM6N<$g5s+9*Z=?k literal 0 HcmV?d00001 diff --git a/clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/ConfigTest.java b/clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/ConfigTest.java new file mode 100644 index 0000000..d6682d3 --- /dev/null +++ b/clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/ConfigTest.java @@ -0,0 +1,81 @@ +package ru.yanygin.clusterAdminLibrary; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import org.junit.jupiter.api.Test; + +class ConfigTest { + + @Test + void testReadConfig() { + + Config simpleConfig = new Config(); + + // проверка чтения конфига из текущего каталога + Config defaultPathConfig = Config.readConfig(); + assertEquals(simpleConfig.getConfigPath(), defaultPathConfig.getConfigPath()); + Config nullConfig = Config.readConfig(null); + assertEquals(simpleConfig.getConfigPath(), nullConfig.getConfigPath()); + Config blankPathConfig = Config.readConfig(""); + assertEquals(simpleConfig.getConfigPath(), blankPathConfig.getConfigPath()); + + // проверка чтения пустого конфига (создание нового) + // assertEquals(simpleConfig.getLocale(), blankPathConfig.getLocale()); + // assertEquals(simpleConfig.getServers(), blankPathConfig.getServers()); + + // проверка чтения несуществующего конфига (создание нового) + Config notExistConfig = Config.readConfig("src\\test\\resources\\not_exist_config.json"); + + assertNotEquals(simpleConfig.getConfigPath(), notExistConfig.getConfigPath()); + assertEquals(simpleConfig.getLocale(), notExistConfig.getLocale()); + assertEquals(simpleConfig.getServers(), notExistConfig.getServers()); + + // проверка миграции конфига с версии 0.2.0 на 0.3.0 + Config config020 = Config.readConfig("src\\test\\resources\\config_0.2.0.json"); + Config config030 = Config.readConfig("src\\test\\resources\\config_0.2.0_convert_0.3.0.json"); + + config020 + .getServers() + .forEach( + (server020Key, server020) -> { + Server server030 = config030.getServers().get(server020Key); + + // проверка миграции варианта хранения кредов + assertEquals( + server020.getSaveCredentialsVariant(), server030.getSaveCredentialsVariant()); + + // проврка миграции кредов агента + UserPassPair agent020Creds = server020.getAgentCredential(); + UserPassPair agent030Creds = server030.getAgentCredential(); + assertEquals(agent020Creds.getDescription(), agent030Creds.getDescription()); + assertEquals(agent020Creds.getUsername(), agent030Creds.getUsername()); + assertEquals(agent020Creds.getPassword(), agent030Creds.getPassword()); + + // проврка миграции кредов кластера + server020 + .getAllClustersCredentials() + .forEach( + (uuid, creds020) -> { + UserPassPair creds030 = server030.getClusterCredentials(uuid); + assertEquals(creds020.getDescription(), creds030.getDescription()); + assertEquals(creds020.getUsername(), creds030.getUsername()); + assertEquals(creds020.getPassword(), creds030.getPassword()); + }); + + }); + } + + @Test + void testCreateNewServer() { + + Config emptyConfig = new Config(); + + Server server = emptyConfig.createNewServer(); + + assertEquals("Server", server.getAgentHost()); + assertEquals("1540", server.getAgentPortAsString()); + assertEquals("Server", server.getRasHost()); + assertEquals("1545", server.getRasPortAsString()); + } +} diff --git a/clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/InvocationTest.java b/clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/InvocationTest.java deleted file mode 100644 index cf5f4e7..0000000 --- a/clusterAdminLibrary/src/test/java/ru/yanygin/clusterAdminLibrary/InvocationTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) 2004-2005 SLF4J.ORG - * Copyright (c) 2004-2005 QOS.CH - * - * All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY - * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER - * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF - * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - */ - -package ru.yanygin.clusterAdminLibrary; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; - -import junit.framework.TestCase; - - -/** - * Test whether invoking the SLF4J API causes problems or not. - * - * @author Ceki Gulcu - * - */ -public class InvocationTest extends TestCase { - - public InvocationTest (String arg0) { - super(arg0); - } - - protected void setUp() throws Exception { - super.setUp(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - public void test1() { -// Logger logger = LoggerFactory.getLogger("test1"); -// logger.debug("Hello world."); - } - - public void test2() { -// Integer i1 = new Integer(1); -// Integer i2 = new Integer(2); -// Integer i3 = new Integer(3); -// Exception e = new Exception("This is a test exception."); -// Logger logger = LoggerFactory.getLogger("test2"); -// -// logger.debug("Hello world 1."); -// logger.debug("Hello world {}", i1); -// logger.debug("val={} val={}", i1, i2); -// logger.debug("val={} val={} val={}", new Object[]{i1, i2, i3}); -// -// logger.debug("Hello world 2", e); -// logger.info("Hello world 2."); -// -// -// logger.warn("Hello world 3."); -// logger.warn("Hello world 3", e); -// -// -// logger.error("Hello world 4."); -// logger.error("Hello world {}", new Integer(3)); -// logger.error("Hello world 4.", e); - } - - public void testNull() { -// Logger logger = LoggerFactory.getLogger("testNull"); -// logger.debug(null); -// logger.info(null); -// logger.warn(null); -// logger.error(null); -// -// Exception e = new Exception("This is a test exception."); -// logger.debug(null, e); -// logger.info(null, e); -// logger.warn(null, e); -// logger.error(null, e); - } - - public void testMarker() { -// Logger logger = LoggerFactory.getLogger("testMarker"); -// Marker blue = MarkerFactory.getMarker("BLUE"); -// logger.debug(blue, "hello"); -// logger.info(blue, "hello"); -// logger.warn(blue, "hello"); -// logger.error(blue, "hello"); -// -// logger.debug(blue, "hello {}", "world"); -// logger.info(blue, "hello {}", "world"); -// logger.warn(blue, "hello {}", "world"); -// logger.error(blue, "hello {}", "world"); -// -// logger.debug(blue, "hello {} and {} ", "world", "universe"); -// logger.info(blue, "hello {} and {} ", "world", "universe"); -// logger.warn(blue, "hello {} and {} ", "world", "universe"); -// logger.error(blue, "hello {} and {} ", "world", "universe"); - } -} diff --git a/clusterAdminLibrary/src/test/resources/config_0.2.0.json b/clusterAdminLibrary/src/test/resources/config_0.2.0.json new file mode 100644 index 0000000..8963c1f --- /dev/null +++ b/clusterAdminLibrary/src/test/resources/config_0.2.0.json @@ -0,0 +1,391 @@ +{ + "ExpandServers": true, + "ExpandClustersTree": true, + "ExpandInfobasesTree": true, + "ShowWorkingServersTree": false, + "ExpandWorkingServersTree": false, + "ShowWorkingProcessesTree": false, + "ExpandWorkingProcessesTree": false, + "ShowServerDescription": true, + "ShowServerVersion": true, + "ShowInfobaseDescription": true, + "ShowLocalRasConnectInfo": true, + "Locale": "ru-RU", + "ShadowSleepSessions": true, + "HighlightNewItems": true, + "HighlightNewItemsDuration": 60, + "ReadClipboard": true, + "Servers": { + "server2:1340": { + "Description": "Платформа 13", + "AgentHost": "server1c", + "AgentPort": 1340, + "RasHost": "server1c", + "RasPort": 1345, + "UseLocalRas": false, + "LocalRasPort": 1345, + "LocalRasV8version": "", + "Autoconnect": false, + "SaveCredentials": true, + "AgentUser": "AgentAdmin", + "AgentPassword": "321", + "ClustersCredentials": { + "701453f0-c23f-4ce4-9e50-1771be85fd68": [ + "Cluster_Admin_1340", + "123", + "Локальный кластер (1340)" + ] + } + } + }, + "SessionColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49 + ], + "Width": [ + 140, + 76, + 63, + 93, + 113, + 113, + 80, + 173, + 54, + 51, + 41, + 126, + 113, + 118, + 132, + 129, + 185, + 174, + 173, + 134, + 129, + 147, + 144, + 137, + 170, + 173, + 142, + 137, + 111, + 0, + 0, + 115, + 98, + 0, + 108, + 0, + 0, + 0, + 0, + 0, + 114, + 117, + 122, + 106, + 199, + 196, + 196, + 191, + 171, + 189 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 24, + "SortDirection": -1 + }, + "ConnectionColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "Width": [ + 165, + 82, + 52, + 84, + 171, + 70, + 93, + 131 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "SortDirection": 0 + }, + "LockColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8 + ], + "Width": [ + 352, + 79, + 90, + 83, + 86, + 171, + 86, + 38, + 120 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "SortDirection": 0 + }, + "WPColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "Width": [ + 87, + 68, + 104, + 71, + 62, + 46, + 75, + 80, + 49, + 86, + 117, + 83, + 104, + 130, + 106, + 132, + 219, + 130 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "SortDirection": 0 + }, + "WSColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14 + ], + "Width": [ + 160, + 79, + 60, + 135, + 141, + 0, + 0, + 0, + 0, + 0, + 81, + 0, + 0, + 48, + 41 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "SortDirection": 0 + } +} \ No newline at end of file diff --git a/clusterAdminLibrary/src/test/resources/config_0.2.0_convert_0.3.0.json b/clusterAdminLibrary/src/test/resources/config_0.2.0_convert_0.3.0.json new file mode 100644 index 0000000..92bf03c --- /dev/null +++ b/clusterAdminLibrary/src/test/resources/config_0.2.0_convert_0.3.0.json @@ -0,0 +1,400 @@ +{ + "ConfigVersion": "0.3.0", + "CheckingUpdate": false, + "ExpandServers": true, + "ExpandClustersTree": true, + "ExpandInfobasesTree": true, + "ShowWorkingServersTree": false, + "ExpandWorkingServersTree": false, + "ShowWorkingProcessesTree": false, + "ExpandWorkingProcessesTree": false, + "ShowServerDescription": true, + "ShowServerVersion": true, + "ShowInfobaseDescription": true, + "ShowLocalRasConnectInfo": true, + "Locale": "ru-RU", + "ShadeSleepingSessions": false, + "HighlightNewItems": true, + "HighlightNewItemsDuration": 60, + "ReadClipboard": true, + "RowSortDirection": "DISABLE", + "InfobasesSortDirection": "DISABLE", + "Servers": { + "server2:1340": { + "Description": "Платформа 13", + "AgentHost": "server1c", + "AgentPort": 1340, + "RasHost": "server1c", + "RasPort": 1345, + "UseLocalRas": false, + "LocalRasPort": 1345, + "LocalRasV8version": "", + "Autoconnect": false, + "SaveCredentialsVariant": "NAMEPASS", + "AgentCredential": { + "Username": "AgentAdmin", + "Password": "321", + "Description": "" + }, + "ClustersCredentialsV3": { + "701453f0-c23f-4ce4-9e50-1771be85fd68": { + "Username": "Cluster_Admin_1340", + "Password": "123", + "Description": "Локальный кластер (1340)" + } + }, + "InfobasesCredentials": [], + "FavoriteInfobases": [] + } + }, + "SessionColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 46, + 47, + 48, + 49 + ], + "Width": [ + 140, + 76, + 63, + 93, + 113, + 113, + 80, + 173, + 54, + 51, + 41, + 126, + 113, + 118, + 132, + 129, + 185, + 174, + 173, + 134, + 129, + 147, + 144, + 137, + 170, + 173, + 142, + 137, + 111, + 0, + 0, + 115, + 98, + 0, + 108, + 0, + 0, + 0, + 0, + 0, + 114, + 117, + 122, + 106, + 199, + 196, + 196, + 191, + 171, + 189 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 24, + "RowSortDirection": "DISABLE" + }, + "ConnectionColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "Width": [ + 165, + 82, + 52, + 84, + 171, + 70, + 93, + 131 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "RowSortDirection": "DISABLE" + }, + "LockColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8 + ], + "Width": [ + 352, + 79, + 90, + 83, + 86, + 171, + 86, + 38, + 120 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "RowSortDirection": "DISABLE" + }, + "WPColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17 + ], + "Width": [ + 87, + 68, + 104, + 71, + 62, + 46, + 75, + 80, + 49, + 86, + 117, + 83, + 104, + 130, + 106, + 132, + 219, + 130 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "RowSortDirection": "DISABLE" + }, + "WSColumnProperties": { + "Order": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14 + ], + "Width": [ + 160, + 79, + 60, + 135, + 141, + 0, + 0, + 0, + 0, + 0, + 81, + 0, + 0, + 48, + 41 + ], + "Visible": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "SortColumn": 0, + "RowSortDirection": "DISABLE" + } +} \ No newline at end of file From e84230350358248e252bd68cc180f3534e6f4b44 Mon Sep 17 00:00:00 2001 From: YanSergey Date: Tue, 23 Aug 2022 13:16:18 +0300 Subject: [PATCH 6/6] =?UTF-8?q?=D0=BE=D0=BF=D1=80=D0=B5=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=20=D1=81=D0=BA=D0=B0=D1=87?= =?UTF-8?q?=D0=B8=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BF=D0=BE=D1=81=D0=BB?= =?UTF-8?q?=D0=B5=D0=B4=D0=BD=D0=B5=D0=B9=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/ru/yanygin/clusterAdminLibrary/Config.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java index c514914..6e93885 100644 --- a/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java +++ b/clusterAdminLibrary/src/main/java/ru/yanygin/clusterAdminLibrary/Config.java @@ -272,7 +272,6 @@ public void run() { /** Узнать последнюю версию из релизов GitHub. */ public void readUpstreamVersion() { - // final URL url = new URL("https://api.github.com/repos/YanSergey/OneS_ClusterAdmin/tags"); URL url; HttpURLConnection conn; try { @@ -335,9 +334,7 @@ public void readUpstreamVersion() { break; } } - // currentVersion.compareTo(Version.parse(lastTagName)) = 1 - // return Version.parse(lastTagName); - latestVersion = Version.parse("0.4.0"); // TODO del + latestVersion = Version.parse(lastTagName); } /** @@ -379,11 +376,9 @@ private String selectFileToSave(Shell parentShell) { } private boolean downloadReleaseToFile(String fname) { - // String link = downloadLatestVersionUrl; - String link = "https://speedtest.selectel.ru/10MB"; // TODO это для теста, удалить! try { - Request.Get(link).execute().saveContent(new File(fname)); + Request.Get(latestVersionUrl).execute().saveContent(new File(fname)); } catch (IOException e) { e.printStackTrace(); return false;