repo-reorg-2020: moved sts4-relevant commons bundles from https://github.com/spring-projects/eclipse-integration-commons/releases/tag/REPO-REORG-2020 into sts4 repo

This commit is contained in:
Martin Lippert
2020-09-29 11:55:31 +02:00
parent e4d16e82cb
commit 8edfab1a16
467 changed files with 45732 additions and 18 deletions

View File

@@ -40,14 +40,42 @@
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.boot.ls">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.core">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.frameworks.core">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.frameworks.test.util">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.frameworks.ui">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.jdk_tools">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.livexp">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.tests.util">
<category name="deps"/>
</bundle>
<bundle id="org.springsource.ide.eclipse.commons.ui">
<category name="deps"/>
</bundle>
<bundle id="io.projectreactor.reactor-core">
<category name="deps"/>
</bundle>
@@ -65,7 +93,7 @@
</bundle>
<bundle id="org.eclipse.lsp4e.jdt">
<category name="Uncategorized"/>
<category name="deps"/>
</bundle>
<bundle id="org.eclipse.lsp4j">

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.springsource.ide.eclipse.commons.boot.ls</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,314 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nullReference=warning
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
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_assignment=0
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
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_multiple_fields=16
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_selector_in_method_invocation=16
org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
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.blank_lines_after_imports=1
org.eclipse.jdt.core.formatter.blank_lines_after_package=1
org.eclipse.jdt.core.formatter.blank_lines_before_field=1
org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
org.eclipse.jdt.core.formatter.blank_lines_before_method=1
org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
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_type_declarations=1
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_method_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.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.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=false
org.eclipse.jdt.core.formatter.comment.indent_root_tags=false
org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=do not insert
org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert
org.eclipse.jdt.core.formatter.comment.line_length=80
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.format_guardian_clause_on_one_line=false
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_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=false
org.eclipse.jdt.core.formatter.indentation.size=4
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_at_end_of_file_if_missing=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=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=insert
org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert
org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=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_binary_operator=insert
org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=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_superinterfaces=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_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=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_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_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_semicolon_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=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_binary_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=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_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_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=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not 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=do not 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_superinterfaces=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_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=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_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_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_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_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_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.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_imple_if_on_one_line=false
org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
org.eclipse.jdt.core.formatter.lineSplit=120
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_at_beginning_of_method_body=0
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
org.eclipse.jdt.core.formatter.tabulation.char=tab
org.eclipse.jdt.core.formatter.tabulation.size=4
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true

View File

@@ -0,0 +1,56 @@
eclipse.preferences.version=1
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
formatter_profile=_SpringSource Tool Suite
formatter_settings_version=11
sp_cleanup.add_default_serial_version_id=true
sp_cleanup.add_generated_serial_version_id=false
sp_cleanup.add_missing_annotations=true
sp_cleanup.add_missing_deprecated_annotations=true
sp_cleanup.add_missing_methods=false
sp_cleanup.add_missing_nls_tags=false
sp_cleanup.add_missing_override_annotations=true
sp_cleanup.add_missing_override_annotations_interface_methods=false
sp_cleanup.add_serial_version_id=false
sp_cleanup.always_use_blocks=true
sp_cleanup.always_use_parentheses_in_expressions=false
sp_cleanup.always_use_this_for_non_static_field_access=false
sp_cleanup.always_use_this_for_non_static_method_access=false
sp_cleanup.convert_to_enhanced_for_loop=true
sp_cleanup.correct_indentation=false
sp_cleanup.format_source_code=false
sp_cleanup.format_source_code_changes_only=false
sp_cleanup.make_local_variable_final=false
sp_cleanup.make_parameters_final=false
sp_cleanup.make_private_fields_final=true
sp_cleanup.make_type_abstract_if_missing_method=false
sp_cleanup.make_variable_declarations_final=true
sp_cleanup.never_use_blocks=false
sp_cleanup.never_use_parentheses_in_expressions=true
sp_cleanup.on_save_use_additional_actions=true
sp_cleanup.organize_imports=true
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
sp_cleanup.remove_private_constructors=true
sp_cleanup.remove_trailing_whitespaces=true
sp_cleanup.remove_trailing_whitespaces_all=true
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
sp_cleanup.remove_unnecessary_casts=true
sp_cleanup.remove_unnecessary_nls_tags=true
sp_cleanup.remove_unused_imports=false
sp_cleanup.remove_unused_local_variables=false
sp_cleanup.remove_unused_private_fields=true
sp_cleanup.remove_unused_private_members=false
sp_cleanup.remove_unused_private_methods=true
sp_cleanup.remove_unused_private_types=true
sp_cleanup.sort_members=false
sp_cleanup.sort_members_all=false
sp_cleanup.use_blocks=true
sp_cleanup.use_blocks_only_for_return_and_throw=false
sp_cleanup.use_parentheses_in_expressions=false
sp_cleanup.use_this_for_non_static_field_access=false
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
sp_cleanup.use_this_for_non_static_method_access=false
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true

View File

@@ -0,0 +1,4 @@
#Fri Oct 19 17:41:16 PDT 2007
eclipse.preferences.version=1
project.repository.kind=jira
project.repository.url=https\://jira.springsource.com

View File

@@ -0,0 +1,3 @@
#Fri Oct 19 17:41:16 PDT 2007
commit.comment.template=${task.key}\: ${task.description}
eclipse.preferences.version=1

View File

@@ -0,0 +1,13 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Spring Tool Suite Common UI Components
Bundle-SymbolicName: org.springsource.ide.eclipse.commons.boot.ls;singleton:=true
Bundle-Version: 4.8.1.qualifier
Bundle-Vendor: Pivotal Software, Inc.
Require-Bundle: org.eclipse.core.resources,
org.springsource.ide.eclipse.commons.livexp
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-ActivationPolicy: lazy
Automatic-Module-Name: org.springsource.ide.eclipse.commons.boot.ls
Export-Package: org.springsource.ide.eclipse.commons.boot.ls.remoteapps
Import-Package: org.eclipse.core.runtime

View File

@@ -0,0 +1,22 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>About Eclipse Integration Commons</title>
<meta name="author" content="Pivotal">
</head>
<body>
<h2>About Eclipse Integration Commons</h2>
<p>June 30, 2015</p>
<h3>Abstract</h3>
<p>The Eclipse Integration Commons project provides components that help
other projects to implement Eclipse-based tooling.</p>
<h3>License</h3>
<p>Pivotal Software, Inc. (“Pivotal”) makes available all content
in this download ("Content"). Unless otherwise indicated below, the
Content is provided to you under the terms and conditions of the Eclipse
Public License Version 1.0 ("EPL"). A copy of the EPL is available in
the file called license.txt. For purposes of the EPL, "Program" will
mean the Content.</p>
</body>
</html>

View File

@@ -0,0 +1,8 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
about.html,\
plugin.xml
src.includes = about.html

View File

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension-point id="org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder.Contributor" name="org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder.Contributor" schema="schema/org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder.Contributor.exsd"/>
</plugin>

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot.ide</groupId>
<artifactId>org.springframework.boot.ide.servers</artifactId>
<version>4.8.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>org.springsource.ide.eclipse.commons.boot.ls</artifactId>
<packaging>eclipse-plugin</packaging>
<name>org.springsource.ide.eclipse.commons.boot.ls</name>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-p2-plugin</artifactId>
<version>${tycho-version}</version>
<executions>
<execution>
<id>second-generate-p2-metadata</id>
<goals>
<goal>p2-metadata</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,102 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
<schema targetNamespace="org.springsource.ide.eclipse.commons.boot.ls" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
<appinfo>
<meta.schema plugin="org.springsource.ide.eclipse.commons.boot.ls" id="org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder.Contributor" name="org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder.Contributor"/>
</appinfo>
<documentation>
[Enter description of this extension point.]
</documentation>
</annotation>
<element name="extension">
<annotation>
<appinfo>
<meta.element />
</appinfo>
</annotation>
<complexType>
<sequence minOccurs="1" maxOccurs="unbounded">
<element ref="injection"/>
</sequence>
<attribute name="point" type="string" use="required">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="id" type="string">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="name" type="string">
<annotation>
<documentation>
</documentation>
<appinfo>
<meta.attribute translatable="true"/>
</appinfo>
</annotation>
</attribute>
</complexType>
</element>
<element name="injection">
<complexType>
<attribute name="class" type="string" use="required">
<annotation>
<documentation>
</documentation>
<appinfo>
<meta.attribute kind="java" basedOn=":org.springsource.ide.eclipse.commons.boot.ls.remoteapps.RemoteBootAppsDataHolder$Contributor"/>
</appinfo>
</annotation>
</attribute>
</complexType>
</element>
<annotation>
<appinfo>
<meta.section type="since"/>
</appinfo>
<documentation>
[Enter the first release in which this extension point appears.]
</documentation>
</annotation>
<annotation>
<appinfo>
<meta.section type="examples"/>
</appinfo>
<documentation>
[Enter extension point usage example here.]
</documentation>
</annotation>
<annotation>
<appinfo>
<meta.section type="apiinfo"/>
</appinfo>
<documentation>
[Enter API information here.]
</documentation>
</annotation>
<annotation>
<appinfo>
<meta.section type="implementation"/>
</appinfo>
<documentation>
[Enter information about supplied implementation of this extension point.]
</documentation>
</annotation>
</schema>

View File

@@ -0,0 +1,42 @@
/*******************************************************************************
* Copyright (c) 2020 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.boot.ls.remoteapps;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.springsource.ide.eclipse.commons.livexp.util.Log;
public class ExentionPointLoader {
@SuppressWarnings("unchecked")
public static <T> List<T> load(Class<T> contributionType) {
String extensionPointId = contributionType.getCanonicalName();
List<T> constributions = new ArrayList<>();
for (IConfigurationElement ce : Platform.getExtensionRegistry().getConfigurationElementsFor(extensionPointId)) {
try {
Object contribution = ce.createExecutableExtension("class");
if (!contributionType.isInstance(contribution)) {
throw new IllegalStateException("Invalid contribution to extension point "+extensionPointId);
} else {
constributions.add((T) contribution);
}
} catch (Exception e) {
Log.log(e);
}
}
return constributions;
}
}

View File

@@ -0,0 +1,260 @@
/*******************************************************************************
* Copyright (c) 2017, 2020 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.boot.ls.remoteapps;
import java.util.List;
import java.util.function.Supplier;
import org.springsource.ide.eclipse.commons.livexp.core.LiveSets;
import org.springsource.ide.eclipse.commons.livexp.core.ObservableSet;
/**
* A RemoteAppsDataHolder provides the means to connect providers of RemoteAppData
* with consumers of RemoteAppData. At present there is one consumer and three producers.
* <p>
* The single consumer is the Spring Boot Language Server eclipse plugin. It uses remote app data
* to scrape live (hover, bean etc.) information from remote boot processes.
* <p>
* The three producers of the information are:
* <p>
* a) the "Remote Boot Apps" preferences page (which is defined in the language server
* plugin and allows for users to manually enter information.
* <p>
* b) the BootDashBoard cloudfoundry plugin, which contributes information automatically
* when boot apps are deployed to cf from boot dash with JMX tunnelling enabled.
* c) BootDashBoard itself via GenericRemoteAppElement framework. This provides remote app
* data automatically, for elements that support JMX connections.
* <p>
* Note: it would be more logical if this class was defined inside boot.ls plugin, (since it
* is the (only) consumer of the data). But because of how
* STS 4 and STS 3 components are currently being built, it is not possible for STS 3 components
* to depend directly on STS 4 components. It is however possible for STS 4 to depend on
* STS 3 components. I.e. boot.ls can depend on boot.dashboard but not vice-versa.
* This is why {@link RemoteBootAppsDataHolder}
* 'extension point' is defined here, allowing boot.dash and spring.boot.ls to both access
* the api and contribute and/or consume remote-app data.
*
* @author Kris De Volder
*/
public class RemoteBootAppsDataHolder {
private static RemoteBootAppsDataHolder DEFAULT;
public synchronized static RemoteBootAppsDataHolder getDefault() {
if (DEFAULT==null) {
DEFAULT = new RemoteBootAppsDataHolder(() -> ExentionPointLoader.load(RemoteBootAppsDataHolder.Contributor.class));
}
return DEFAULT;
}
/**
* Json serialization-friendly data class
*/
public static class RemoteAppData {
private String jmxurl;
private String host;
private String urlScheme = "https";
private String port = "443";
private boolean keepChecking = true;
//keepChecking defaults to true. Boot dash automatic remote apps should override this explicitly.
//Reason. All other 'sources' of remote apps are 'manual' and we want them to default to
//'keepChecking' even if the user doesn't set this to true manually.
private String processId = null;
private String processName = null;
public RemoteAppData() {
}
public RemoteAppData(String jmxurl, String host) {
super();
this.jmxurl = jmxurl;
this.host = host;
}
public String getJmxurl() {
return jmxurl;
}
public void setJmxurl(String jmxurl) {
this.jmxurl = jmxurl;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUrlScheme() {
return urlScheme;
}
public void setUrlScheme(String urlScheme) {
this.urlScheme = urlScheme;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public boolean isKeepChecking() {
return keepChecking;
}
public void setKeepChecking(boolean keepChecking) {
this.keepChecking = keepChecking;
}
public String getProcessId() {
return processId;
}
public void setProcessId(String processId) {
this.processId = processId;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((host == null) ? 0 : host.hashCode());
result = prime * result + ((jmxurl == null) ? 0 : jmxurl.hashCode());
result = prime * result + (keepChecking ? 1231 : 1237);
result = prime * result + ((port == null) ? 0 : port.hashCode());
result = prime * result + ((processId == null) ? 0 : processId.hashCode());
result = prime * result + ((urlScheme == null) ? 0 : urlScheme.hashCode());
result = prime * result + ((processId == null) ? 0 : processId.hashCode());
result = prime * result + ((processName == null) ? 0 : processName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RemoteAppData other = (RemoteAppData) obj;
if (host == null) {
if (other.host != null) {
return false;
}
} else if (!host.equals(other.host)) {
return false;
}
if (jmxurl == null) {
if (other.jmxurl != null) {
return false;
}
} else if (!jmxurl.equals(other.jmxurl)) {
return false;
}
if (keepChecking != other.keepChecking) {
return false;
}
if (port == null) {
if (other.port != null) {
return false;
}
} else if (!port.equals(other.port)) {
return false;
}
if (processId == null) {
if (other.processId != null) {
return false;
}
} else if (!processId.equals(other.processId)) {
return false;
}
if (processName == null) {
if (other.processName != null) {
return false;
}
} else if (!processName.equals(other.processName)) {
return false;
}
if (urlScheme == null) {
if (other.urlScheme != null) {
return false;
}
} else if (!urlScheme.equals(other.urlScheme)) {
return false;
}
return true;
}
@Override
public String toString() {
return "RemoteAppData [jmxurl=" + jmxurl + ", host=" + host + ", urlScheme=" + urlScheme + ", port=" + port
+ ", keepChecking=" + keepChecking + ", processId=" + processId + ", processName=" + processName + "]";
}
}
/**
* A producer of remote RemoteAppData can contribute its data by injecting a bean
* that implements this interface (via {@link SimpleDIContext}.
*/
public interface Contributor {
ObservableSet<RemoteAppData> getRemoteApps();
}
/**
* Computes the union of all Contributors.
*/
private final ObservableSet<RemoteAppData> union;
public RemoteBootAppsDataHolder(Supplier<List<Contributor>> contributions) {
union = union(contributions.get());
}
public static ObservableSet<RemoteAppData> union(List<Contributor> contributors) {
if (contributors.isEmpty()) {
return LiveSets.emptySet(RemoteAppData.class);
} else if (contributors.size()==1) {
return contributors.get(0).getRemoteApps();
} else {
ObservableSet<RemoteAppData> union = contributors.get(0).getRemoteApps();
for (int i = 1; i < contributors.size(); i++) {
union = LiveSets.union(union, contributors.get(i).getRemoteApps());
}
return union;
}
}
/**
* A consumer of RemoteAppData uses this method to obtain data
* and/or listen for changes to the data.
*/
public ObservableSet<RemoteAppData> getRemoteApps() {
return union;
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.springsource.ide.eclipse.commons.core</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
<filteredResources>
<filter>
<id>1373409305025</id>
<name></name>
<type>14</type>
<matcher>
<id>org.eclipse.ui.ide.multiFilter</id>
<arguments>1.0-projectRelativePath-matches-false-false-target</arguments>
</matcher>
</filter>
</filteredResources>
</projectDescription>

View File

@@ -0,0 +1,357 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
org.eclipse.jdt.core.compiler.annotation.nonnull.secondary=
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary=
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullable.secondary=
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
org.eclipse.jdt.core.compiler.problem.deadCode=warning
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
org.eclipse.jdt.core.compiler.problem.nullReference=warning
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning
org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled
org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
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_assignment=0
org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
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_multiple_fields=16
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_selector_in_method_invocation=16
org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
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.blank_lines_after_imports=1
org.eclipse.jdt.core.formatter.blank_lines_after_package=1
org.eclipse.jdt.core.formatter.blank_lines_before_field=1
org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
org.eclipse.jdt.core.formatter.blank_lines_before_method=1
org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
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_type_declarations=1
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_method_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.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.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=false
org.eclipse.jdt.core.formatter.comment.indent_root_tags=false
org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=do not insert
org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert
org.eclipse.jdt.core.formatter.comment.line_length=80
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.format_guardian_clause_on_one_line=false
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_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=false
org.eclipse.jdt.core.formatter.indentation.size=4
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_at_end_of_file_if_missing=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=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=insert
org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert
org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=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_binary_operator=insert
org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=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_superinterfaces=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_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=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_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_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_semicolon_in_for=insert
org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=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_binary_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=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_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_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=do not insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not 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=do not 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_superinterfaces=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_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=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_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_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_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_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_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.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_imple_if_on_one_line=false
org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
org.eclipse.jdt.core.formatter.lineSplit=120
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_at_beginning_of_method_body=0
org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
org.eclipse.jdt.core.formatter.tabulation.char=tab
org.eclipse.jdt.core.formatter.tabulation.size=4
org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false
org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true

View File

@@ -0,0 +1,56 @@
eclipse.preferences.version=1
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
formatter_profile=_SpringSource Tool Suite
formatter_settings_version=11
sp_cleanup.add_default_serial_version_id=true
sp_cleanup.add_generated_serial_version_id=false
sp_cleanup.add_missing_annotations=true
sp_cleanup.add_missing_deprecated_annotations=true
sp_cleanup.add_missing_methods=false
sp_cleanup.add_missing_nls_tags=false
sp_cleanup.add_missing_override_annotations=true
sp_cleanup.add_missing_override_annotations_interface_methods=false
sp_cleanup.add_serial_version_id=false
sp_cleanup.always_use_blocks=true
sp_cleanup.always_use_parentheses_in_expressions=false
sp_cleanup.always_use_this_for_non_static_field_access=false
sp_cleanup.always_use_this_for_non_static_method_access=false
sp_cleanup.convert_to_enhanced_for_loop=true
sp_cleanup.correct_indentation=false
sp_cleanup.format_source_code=false
sp_cleanup.format_source_code_changes_only=false
sp_cleanup.make_local_variable_final=false
sp_cleanup.make_parameters_final=false
sp_cleanup.make_private_fields_final=true
sp_cleanup.make_type_abstract_if_missing_method=false
sp_cleanup.make_variable_declarations_final=true
sp_cleanup.never_use_blocks=false
sp_cleanup.never_use_parentheses_in_expressions=true
sp_cleanup.on_save_use_additional_actions=true
sp_cleanup.organize_imports=true
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
sp_cleanup.remove_private_constructors=true
sp_cleanup.remove_trailing_whitespaces=true
sp_cleanup.remove_trailing_whitespaces_all=true
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
sp_cleanup.remove_unnecessary_casts=false
sp_cleanup.remove_unnecessary_nls_tags=true
sp_cleanup.remove_unused_imports=false
sp_cleanup.remove_unused_local_variables=false
sp_cleanup.remove_unused_private_fields=true
sp_cleanup.remove_unused_private_members=false
sp_cleanup.remove_unused_private_methods=true
sp_cleanup.remove_unused_private_types=true
sp_cleanup.sort_members=false
sp_cleanup.sort_members_all=false
sp_cleanup.use_blocks=true
sp_cleanup.use_blocks_only_for_return_and_throw=false
sp_cleanup.use_parentheses_in_expressions=false
sp_cleanup.use_this_for_non_static_field_access=false
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
sp_cleanup.use_this_for_non_static_method_access=false
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true

View File

@@ -0,0 +1,4 @@
#Fri Oct 19 17:41:16 PDT 2007
eclipse.preferences.version=1
project.repository.kind=jira
project.repository.url=https\://jira.springsource.com

View File

@@ -0,0 +1,3 @@
#Fri Oct 19 17:41:16 PDT 2007
commit.comment.template=${task.key}\: ${task.description}
eclipse.preferences.version=1

View File

@@ -0,0 +1,40 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: SpringSource Tool Suite (Core)
Bundle-SymbolicName: org.springsource.ide.eclipse.commons.core;singleton:=true
Bundle-Version: 4.8.1.qualifier
Bundle-Activator: org.springsource.ide.eclipse.commons.internal.core.CorePlugin
Bundle-Vendor: Pivotal Software, Inc.
Require-Bundle: org.eclipse.core.resources,
org.eclipse.mylyn.commons.net;bundle-version="[3.3.0,4.0.0)",
org.eclipse.equinox.p2.core;resolution:=optional,
org.eclipse.equinox.p2.repository;resolution:=optional,
org.eclipse.jdt.core,
org.eclipse.jdt.launching,
org.eclipse.wst.common.project.facet.core,
org.apache.commons.collections,
org.apache.log4j,
org.eclipse.platform,
org.springsource.ide.eclipse.commons.frameworks.core;bundle-version="3.5.0",
org.springsource.ide.eclipse.commons.jdk_tools;resolution:=optional,
org.eclipse.text,
org.springsource.ide.eclipse.commons.livexp,
org.eclipse.debug.core,
org.eclipse.jface
Bundle-ActivationPolicy: lazy
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Export-Package: org.springsource.ide.eclipse.commons.core,
org.springsource.ide.eclipse.commons.core.preferences,
org.springsource.ide.eclipse.commons.core.process,
org.springsource.ide.eclipse.commons.core.pstore,
org.springsource.ide.eclipse.commons.core.templates,
org.springsource.ide.eclipse.commons.core.util,
org.springsource.ide.eclipse.commons.internal.core,
org.springsource.ide.eclipse.commons.internal.core.commandhistory,
org.springsource.ide.eclipse.commons.internal.core.net
Import-Package: org.eclipse.core.runtime,
org.eclipse.core.runtime.jobs,
org.eclipse.core.runtime.preferences,
org.eclipse.osgi.util,
org.osgi.framework,
org.osgi.service.prefs

View File

@@ -0,0 +1,22 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>About Eclipse Integration Commons</title>
<meta name="author" content="Pivotal">
</head>
<body>
<h2>About Eclipse Integration Commons</h2>
<p>June 30, 2015</p>
<h3>Abstract</h3>
<p>The Eclipse Integration Commons project provides components that help
other projects to implement Eclipse-based tooling.</p>
<h3>License</h3>
<p>Pivotal Software, Inc. (“Pivotal”) makes available all content
in this download ("Content"). Unless otherwise indicated below, the
Content is provided to you under the terms and conditions of the Eclipse
Public License Version 1.0 ("EPL"). A copy of the EPL is available in
the file called license.txt. For purposes of the EPL, "Program" will
mean the Content.</p>
</body>
</html>

View File

@@ -0,0 +1,7 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
about.html,\
plugin.xml
src.includes = about.html

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.4"?>
<plugin>
<extension-point id="com.springsource.sts.core.resources" name="External STS Resources" schema="schema/resources.exsd"/>
</plugin>

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot.ide</groupId>
<artifactId>org.springframework.boot.ide.servers</artifactId>
<version>4.8.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>org.springsource.ide.eclipse.commons.core</artifactId>
<packaging>eclipse-plugin</packaging>
<name>org.springsource.ide.eclipse.commons.core</name>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-p2-plugin</artifactId>
<version>${tycho-version}</version>
<executions>
<execution>
<id>second-generate-p2-metadata</id>
<goals>
<goal>p2-metadata</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-compiler-plugin</artifactId>
<configuration>
<extraClasspathElements>
<extraClasspathElement>
<groupId>jdk</groupId>
<artifactId>tools.jar</artifactId>
<version>${java.version}</version>
<scope>system</scope>
<systemPath>${java.home}/../lib/tools.jar</systemPath>
</extraClasspathElement>
</extraClasspathElements>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,160 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- Schema file written by PDE -->
<schema targetNamespace="com.springsource.sts.core" xmlns="http://www.w3.org/2001/XMLSchema">
<annotation>
<appinfo>
<meta.schema plugin="com.springsource.sts.core" id="resources" name="References to external resources"/>
</appinfo>
<documentation>
[Enter description of this extension point.]
</documentation>
</annotation>
<element name="extension">
<annotation>
<appinfo>
<meta.element />
</appinfo>
</annotation>
<complexType>
<choice minOccurs="1" maxOccurs="unbounded">
<element ref="propertyDefinition"/>
<element ref="url"/>
</choice>
<attribute name="point" type="string" use="required">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="id" type="string">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="name" type="string">
<annotation>
<documentation>
</documentation>
<appinfo>
<meta.attribute translatable="true"/>
</appinfo>
</annotation>
</attribute>
</complexType>
</element>
<element name="url">
<complexType>
<attribute name="id" type="string" use="required">
<annotation>
<documentation>
</documentation>
<appinfo>
<meta.attribute kind="identifier" basedOn="com.springsource.sts.core.resources/@id"/>
</appinfo>
</annotation>
</attribute>
<attribute name="value" type="string" use="required">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
</complexType>
</element>
<element name="propertyDefinition">
<complexType>
<attribute name="id" type="string">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="type" type="string">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="defaultValue" type="string">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="label" type="string">
<annotation>
<documentation>
</documentation>
<appinfo>
<meta.attribute translatable="true"/>
</appinfo>
</annotation>
</attribute>
<attribute name="userConfigurable" type="boolean">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
<attribute name="multiValue" type="boolean">
<annotation>
<documentation>
</documentation>
</annotation>
</attribute>
</complexType>
</element>
<annotation>
<appinfo>
<meta.section type="since"/>
</appinfo>
<documentation>
[Enter the first release in which this extension point appears.]
</documentation>
</annotation>
<annotation>
<appinfo>
<meta.section type="examples"/>
</appinfo>
<documentation>
[Enter extension point usage example here.]
</documentation>
</annotation>
<annotation>
<appinfo>
<meta.section type="apiinfo"/>
</appinfo>
<documentation>
[Enter API information here.]
</documentation>
</annotation>
<annotation>
<appinfo>
<meta.section type="implementation"/>
</appinfo>
<documentation>
[Enter information about supplied implementation of this extension point.]
</documentation>
</annotation>
</schema>

View File

@@ -0,0 +1,56 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
import org.springsource.ide.eclipse.commons.internal.core.commandhistory.CommandHistory;
/**
* Provides access to {@link ICommandHistory} implementations.
* @author Christian Dupuis
* @author Kris De Volder
* @since 2.5.0
*/
public class CommandHistoryProvider {
private static final Map<String, ICommandHistory> COMMAND_HISTORIES = new HashMap<String, ICommandHistory>();
public static synchronized ICommandHistory getCommandHistory(String historyId, String natureId) {
String key = getKey(historyId, natureId);
if (COMMAND_HISTORIES.containsKey(key)) {
return COMMAND_HISTORIES.get(key);
}
else {
try {
CommandHistory commandHistory = new CommandHistory(historyId, natureId, true);
COMMAND_HISTORIES.put(key, commandHistory);
return commandHistory;
}
catch (CoreException e) {
CorePlugin.log(
"Warning: couldn't get persistent command history, using non-persistent history instead", e);
return new CommandHistory(historyId, natureId);
}
}
}
private static String getKey(String historyId, String natureId) {
Assert.isNotNull(historyId);
Assert.isNotNull(natureId);
return new StringBuilder().append(historyId).append("_").append(natureId).toString();
}
}

View File

@@ -0,0 +1,59 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.util.Properties;
import org.eclipse.core.runtime.Assert;
/**
* @author Steffen Pingel
*/
public class CoreUtil {
/**
* Replaces placeholders in <code>text</code> with values from
* <code>properties</code>. Placeholders use the following format:
* <code>${key}</code>. If the key is not found in <code>properties</code>
* the placeholder is retained.
*
* @param text the text
* @param properties key value pairs for substitution
* @return the substituted text
*/
public static String substitute(String text, Properties properties) {
Assert.isNotNull(text);
Assert.isNotNull(properties);
String[] segments = text.split("\\$\\{");
StringBuffer sb = new StringBuffer(text.length());
sb.append(segments[0]);
for (int i = 1; i < segments.length; i++) {
String segment = segments[i];
String substitution = null;
int brace = segment.indexOf('}');
if (brace > 0) {
String keyword = segment.substring(0, brace);
substitution = properties.getProperty(keyword);
}
if (substitution != null) {
sb.append(substitution);
sb.append(segment.substring(brace + 1));
}
else {
sb.append("${");
sb.append(segment);
}
}
return sb.toString();
}
}

View File

@@ -0,0 +1,92 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.Serializable;
/**
* @author Andrew Eisenberg
* @author Christian Dupuis
* @author Kris De Volder
* @since 2.5.0
*/
public class Entry implements Serializable {
private static final long serialVersionUID = 1L;
private final String command;
private final String project;
public Entry(String command, String project) {
super();
this.command = command;
this.project = project;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Entry other = (Entry) obj;
if (command == null) {
if (other.command != null) {
return false;
}
}
else if (!command.equals(other.command)) {
return false;
}
if (project == null) {
if (other.project != null) {
return false;
}
}
else if (!project.equals(other.project)) {
return false;
}
return true;
}
public String getCommand() {
return command;
}
public String getMenuLabel() {
return getCommand().trim() + " (" + getProject().trim() + ")";
}
public String getProject() {
return project;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((command == null) ? 0 : command.hashCode());
result = prime * result + ((project == null) ? 0 : project.hashCode());
return result;
}
@Override
public String toString() {
return "Entry(" + command + ", " + project + ")";
}
}

View File

@@ -0,0 +1,192 @@
/*******************************************************************************
* Copyright (c) 2012, 2018 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.FileChannel;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.Bundle;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* @author Steffen Pingel
* @author Leo Dos Santos
* @author Christian Dupuis
* @author Kris De Volder
*/
public class FileUtil {
private static final int MAX_FILE_SIZE = 1024 * 1024;
public static final int BUFFER_SIZE = 4096;
public static void copyDirectory(File sourceDirectory, File targetDirectory, IProgressMonitor monitor)
throws CoreException {
File[] files = sourceDirectory.listFiles();
if (files != null) {
for (File sourceFile : files) {
File targetFile = new File(targetDirectory, sourceFile.getName());
if (sourceFile.isDirectory()) {
targetFile.mkdir();
copyDirectory(sourceFile, targetFile, monitor);
}
else {
copyFile(sourceFile, targetFile, monitor);
}
}
}
}
public static void copyFile(File sourceFile, File targetFile, IProgressMonitor monitor) throws CoreException {
try {
monitor.beginTask("Copying file", (int) sourceFile.length());
FileInputStream in = new FileInputStream(sourceFile);
try {
writeToFile(in, targetFile, monitor);
}
finally {
in.close();
}
}
catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Could not copy file from "
+ sourceFile + " to " + targetFile, e));
}
finally {
monitor.done();
}
}
public static void writeToFile(InputStream in, File targetFile, IProgressMonitor monitor)
throws FileNotFoundException, IOException {
FileOutputStream out = new FileOutputStream(targetFile);
try {
int len;
byte[] buffer = new byte[BUFFER_SIZE];
while ((len = in.read(buffer)) > 0) {
Policy.checkCancelled(monitor);
out.write(buffer, 0, len);
monitor.worked(len);
}
}
finally {
out.close();
}
}
public static File getFile(Bundle bundle, String filename) throws CoreException {
URL url = bundle.getResource(filename);
if (url == null) {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Could not locate file: "
+ filename, new FileNotFoundException()));
}
try {
return new File(FileLocator.toFileURL(url).getPath());
}
catch (Exception e) {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Could not locate file: "
+ filename, e));
}
}
public static File getFile(Plugin plugin, String filename) throws CoreException {
return getFile(plugin.getBundle(), filename);
}
public static String readFile(File sourceFile, IProgressMonitor monitor) throws CoreException {
long length = sourceFile.length();
if (length > MAX_FILE_SIZE) {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "File \"" + sourceFile
+ "\" is too large"));
}
try {
monitor.beginTask("Reading file", (int) length);
FileReader in = new FileReader(sourceFile);
try {
StringBuilder sb = new StringBuilder((int) length);
int len;
char[] buffer = new char[BUFFER_SIZE];
while ((len = in.read(buffer)) > 0) {
Policy.checkCancelled(monitor);
sb.append(buffer, 0, len);
monitor.worked(len);
}
return sb.toString();
}
finally {
in.close();
}
}
catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Could not read file \""
+ sourceFile + "\"", e));
}
finally {
monitor.done();
}
}
private static String[] BINARY_EXTENSIONS = new String[] { "jar", "gif", "jpg", "jpeg", ".class", "png" };
public static void copy(File source, File target) throws IOException {
FileInputStream sourceOutStream = new FileInputStream(source);
FileOutputStream targetOutStream = new FileOutputStream(target);
FileChannel sourceChannel = sourceOutStream.getChannel();
FileChannel targetChannel = targetOutStream.getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
sourceChannel.close();
targetChannel.close();
sourceOutStream.close();
targetOutStream.close();
}
public static boolean isBinaryFile(File file) {
String extension = FileUtil.getExtension(file);
if (extension != null) {
for (String binaryExtension : BINARY_EXTENSIONS) {
if (binaryExtension.equals(extension)) {
return true;
}
}
}
return false;
}
public static String getExtension(File file) {
String fileName = file.getName();
int extensionIndex = fileName.lastIndexOf('.');
if (extensionIndex == -1) {
return null;
}
return fileName.substring(extensionIndex + 1);
}
}

View File

@@ -0,0 +1,175 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.osgi.util.NLS;
import org.springsource.ide.eclipse.commons.core.util.IOUtil;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
import org.springsource.ide.eclipse.commons.internal.core.net.HttpClientTransportService;
import org.springsource.ide.eclipse.commons.internal.core.net.ITransportService;
import org.springsource.ide.eclipse.commons.internal.core.net.P2TransportService;
/**
* Provides helper methods for downloading files.
* @author Steffen Pingel
*/
public class HttpUtil {
private static ITransportService transport;
public static IStatus download(String url, File archiveFile, File targetDirectory, IProgressMonitor monitor) {
return download(url, archiveFile, targetDirectory, null, monitor);
}
public static IStatus download(String url, File archiveFile, File targetDirectory, String prefix,
IProgressMonitor monitor) {
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
SubMonitor progress = SubMonitor.convert(monitor, 100);
targetDirectory.mkdirs();
// download archive file
try {
try {
OutputStream out = new BufferedOutputStream(new FileOutputStream(archiveFile));
try {
HttpUtil.download(new URI(url), out, progress.newChild(70));
}
catch (CoreException e) {
return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, NLS.bind(
"I/O error while retrieving data: {0}", e.getMessage()), e);
}
catch (URISyntaxException e) {
return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, NLS.bind("Invalid URL: {0}", url), e);
}
finally {
out.close();
}
}
catch (IOException e) {
return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "I/O error while retrieving data", e);
}
// extract archive file
try {
URL fileUrl = archiveFile.toURI().toURL();
ZipFileUtil.unzip(fileUrl, targetDirectory, prefix, progress.newChild(30));
if (targetDirectory.listFiles().length <= 0) {
String message = NLS.bind("Zip file {0} appears to be empty", archiveFile);
return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, message);
}
}
catch (IOException e) {
return new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error while extracting archive", e);
}
}
finally {
archiveFile.delete();
}
return Status.OK_STATUS;
}
public static void download(URI uri, OutputStream out, IProgressMonitor monitor) throws CoreException {
String protocol = uri.getScheme();
if ("file".equals(protocol)) {
// Yes. it is a bit strange that HttpUtil knows how to read from
// file url. But it is just easier that
// way. Don't need to special case file urls in other places.
// We should consider renaming this class but it has the potential
// of breaking a lot of dependencies.
File f = new File(uri);
FileInputStream contents = null;
try {
contents = new FileInputStream(f);
byte[] buf = new byte[40 * 1024];
int read;
while ((read = contents.read(buf)) >= 0) {
// read = -1 means EOF
// read == 0 probably is impossible but handle it anyway.
if (read > 0) {
out.write(buf, 0, read);
}
}
}
catch (IOException e) {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, e.getMessage(), e));
}
finally {
try {
if (contents != null) {
contents.close();
}
}
catch (IOException e) {
}
}
}
else {
getTransport().download(uri, out, monitor);
}
}
public static long getLastModified(URI location, IProgressMonitor monitor) throws CoreException {
return getTransport().getLastModified(location, monitor);
}
public static synchronized ITransportService getTransport() {
if (transport == null) {
if (Platform.isRunning()) {
try {
transport = new P2TransportService();
}
catch (ClassNotFoundException e) {
// fall back to HttpClientTransport
}
}
if (transport == null) {
transport = new HttpClientTransportService();
}
}
return transport;
}
public static InputStream stream(URI uri, IProgressMonitor monitor) throws CoreException {
return getTransport().stream(uri, monitor);
}
public static void ping(URI uri) throws MalformedURLException, IOException, CoreException {
URLConnection connection = uri.toURL().openConnection();
connection.setConnectTimeout(500);
InputStream input = connection.getInputStream();
IOUtil.consume(input);
}
}

View File

@@ -0,0 +1,41 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.util.List;
/**
* @author Christian Dupuis
* @author Kris De Volder
* @since 2.5.0
*/
public interface ICommandHistory {
/**
* The default value for maxSize.
*/
int DEFAULT_MAX_SIZE = 100;
void add(Entry entry);
void clear();
Entry getLast();
List<Entry> getRecentValid(int limit);
boolean isEmpty();
int size();
Iterable<Entry> validEntries();
}

View File

@@ -0,0 +1,944 @@
// COPIED from spring-ide org.springframework.ide.eclipse.core.java.JdtUtils
/*******************************************************************************
* Copyright (c) 2012 - 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeParameter;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.launching.JavaRuntime;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* Utility class that provides several helper methods for working with Eclipse's
* JDT.
* @author Christian Dupuis
* @author Martin Lippert
* @author Leo Dos Santos
* @since 2.0
*/
public class JdtUtils {
public static final String CLASS_FILE_EXTENSION = ".class";
public static final String GROOVY_FILE_EXTENSION = ".groovy";
public static final String JAVA_FILE_EXTENSION = ".java";
private static final String AJDT_CLASS = "org.eclipse.ajdt.core.javaelements.AJCompilationUnitManager";
private static final String AJDT_NATURE = "org.eclipse.ajdt.ui.ajnature";
private static final String CLASSPATH_FILENAME = ".classpath";
private static final boolean IS_AJDT_PRESENT = isAjdtPresent();
/** Suffix for array class names: "[]" */
private static final String ARRAY_SUFFIX = "[]";
/**
* Creates specified Java project.
*/
public static IJavaProject createJavaProject(String projectName, IProgressMonitor monitor) throws CoreException {
IProject project = SpringCoreUtils.createProject(projectName, null, monitor);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (!project.hasNature(JavaCore.NATURE_ID)) {
SpringCoreUtils.addProjectNature(project, JavaCore.NATURE_ID, monitor);
}
IJavaProject jproject = JavaCore.create(project);
// append JRE entry
jproject.setRawClasspath(new IClasspathEntry[] { getJreVariableEntry() }, monitor);
jproject.setOutputLocation(project.getFullPath(), monitor);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
return jproject;
}
/**
* Checks if the given <code>type</code> implements/extends
* <code>className</code>.
*/
// public static boolean doesImplement(IResource resource, IType type,
// String className) {
// if (resource == null || type == null || className == null) {
// return false;
// }
// if (className.startsWith("java.") || className.startsWith("javax.")) {
// try {
// ClassLoader cls = getClassLoader(resource.getProject(), null);
// Class<?> typeClass = cls.loadClass(type.getFullyQualifiedName('$'));
// Class<?> interfaceClass = cls.loadClass(className);
// return typeClass.equals(interfaceClass) ||
// interfaceClass.isAssignableFrom(typeClass);
// }
// catch (Throwable e) {
// // ignore this and fall back to JDT does implement checks
// }
// }
// return doesImplementWithJdt(resource, type, className);
// }
// public static IType getAjdtType(IProject project, String className) {
// IJavaProject javaProject = getJavaProject(project);
// if (IS_AJDT_PRESENT && javaProject != null && className != null) {
//
// try {
// IType type = null;
//
// // First look for the type in the project
// if (isAjdtProject(project)) {
// type = AjdtUtils.getAjdtType(project, className);
// if (type != null) {
// return type;
// }
// }
//
// // Then look for the type in the referenced Java projects
// for (IProject refProject : project.getReferencedProjects()) {
// if (isAjdtProject(refProject)) {
// type = AjdtUtils.getAjdtType(refProject, className);
// if (type != null) {
// return type;
// }
// }
// }
// }
// catch (CoreException e) {
// StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
// "Error getting Java type '"
// + className + "'", e));
// }
// }
// return null;
// }
public static List<IJavaProject> getAllDependingJavaProjects(IJavaProject project) {
List<IJavaProject> javaProjects = new ArrayList<IJavaProject>();
IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
if (model != null) {
try {
String[] names = project.getRequiredProjectNames();
IJavaProject[] projects = model.getJavaProjects();
for (IJavaProject project2 : projects) {
for (String name2 : names) {
String name = project2.getProject().getName();
if (name.equals(name2)) {
javaProjects.add(project2);
}
}
}
}
catch (JavaModelException exception) {
}
}
return javaProjects;
}
/**
* Creates a Set of {@link URL}s from the OSGi bundle class path manifest
* entry.
*/
// public static Set<URL> getBundleClassPath(String bundleId) {
// Set<URL> paths = new HashSet<URL>();
// try {
// Bundle bundle = Platform.getBundle(bundleId);
// if (bundle != null) {
// String bundleClassPath = (String) bundle.getHeaders()
// .get(org.osgi.framework.Constants.BUNDLE_CLASSPATH);
// if (bundleClassPath != null) {
// String[] classPathEntries =
// StringUtils.delimitedListToStringArray(bundleClassPath, ",");
// for (String classPathEntry : classPathEntries) {
// if (".".equals(classPathEntry.trim())) {
// paths.add(FileLocator.toFileURL(bundle.getEntry("/")));
// }
// else {
// paths.add(FileLocator.toFileURL(new URL(bundle.getEntry("/"), "/" +
// classPathEntry.trim())));
// }
// }
// }
// else {
// paths.add(FileLocator.toFileURL(bundle.getEntry("/")));
// }
// }
// }
// catch (MalformedURLException e) {
// StatusHandler
// .log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
// "An error occurred getting classpath", e));
// }
// catch (IOException e) {
// StatusHandler
// .log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
// "An error occurred getting classpath", e));
// }
// return paths;
// }
/**
* @since 2.6.0
*/
public static IJavaElement getByHandle(String handle) {
// if (IS_AJDT_PRESENT) {
// return AjdtUtils.getByHandle(handle);
// }
// else {
return JavaCore.create(handle);
// }
}
/**
* Create a {@link ClassLoader} from the class path configuration of the
* given <code>project</code>.
* @param project the {@link IProject}
* @param useParentClassLoader true if the current OSGi class loader should
* be used as parent class loader for the constructed class loader.
* @return {@link ClassLoader} instance constructed from the
* <code>project</code>'s build path configuration
*/
// public static ClassLoader getClassLoader(IProject project, ClassLoader
// parentClassLoader) {
// return ProjectClassLoaderCache.getClassLoader(project,
// parentClassLoader);
// }
//
// public static void removeClassLoaderEntryFromCache(IProject project) {
// ProjectClassLoaderCache.removeClassLoaderEntryFromCache(project);
// }
//
// public static IMethod getConstructor(IType type, Class[] parameterTypes)
// {
// String[] parameterTypesAsString =
// getParameterTypesAsStringArray(parameterTypes);
// return getConstructor(type, parameterTypesAsString);
// }
// public static IMethod getConstructor(IType type, String[] parameterTypes)
// {
// try {
// Set<IMethod> methods = Introspector.getAllConstructors(type);
// for (IMethod method : methods) {
// if (method.getParameterTypes().length == parameterTypes.length) {
// String[] methodParameterTypes = getParameterTypesAsStringArray(method);
// if (Arrays.deepEquals(parameterTypes, methodParameterTypes)) {
// return method;
// }
// }
// }
// }
// catch (JavaModelException e) {
// }
// return null;
// }
// public static IField getField(IType type, String fieldName, String
// parameterType) {
// try {
// Set<IField> methods = Introspector.getAllFields(type);
// for (IField field : methods) {
// if (field.getElementName().equals(fieldName)) {
// return field;
// }
// }
// }
// catch (JavaModelException e) {
// }
// return null;
// }
/**
* Returns a flat list of all interfaces and super types for the given
* {@link IType}.
*/
// public static List<String> getFlatListOfClassAndInterfaceNames(IType
// parameterType, IType type) {
// List<String> requiredTypes = new ArrayList<String>();
// if (parameterType != null) {
// do {
// try {
// requiredTypes.add(parameterType.getFullyQualifiedName());
// String[] interfaceNames = parameterType.getSuperInterfaceNames();
// for (String interfaceName : interfaceNames) {
// if (interfaceName != null) {
// if (type.isBinary()) {
// requiredTypes.add(interfaceName);
// }
// String resolvedName = resolveClassName(interfaceName, type);
// if (resolvedName != null) {
// requiredTypes.add(resolvedName);
// }
// }
// }
// parameterType = Introspector.getSuperType(parameterType);
// }
// catch (JavaModelException e) {
// }
// } while (parameterType != null &&
// !parameterType.getFullyQualifiedName().equals(Object.class.getName()));
// }
// return requiredTypes;
// }
/**
* Returns the corresponding Java project or <code>null</code> a for given
* project.
* @param project the project the Java project is requested for
* @return the requested Java project or <code>null</code> if the Java
* project is not defined or the project is not accessible
*/
public static IJavaProject getJavaProject(IProject project) {
if (project.isAccessible()) {
try {
if (project.hasNature(JavaCore.NATURE_ID)) {
return (IJavaProject) project.getNature(JavaCore.NATURE_ID);
}
}
catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"Error getting Java project for project '" + project.getName() + "'", e));
}
}
return null;
}
public static IJavaProject getJavaProject(IResource config) {
IJavaProject project = JavaCore.create(config.getProject());
return project;
}
/**
* Returns the corresponding Java type for given full-qualified class name.
* @param project the JDT project the class belongs to
* @param className the full qualified class name of the requested Java type
* @return the requested Java type or null if the class is not defined or
* the project is not accessible
*/
public static IType getJavaType(IProject project, String className) {
IJavaProject javaProject = JdtUtils.getJavaProject(project);
if (className != null) {
// For inner classes replace '$' by '.'
int pos = className.lastIndexOf('$');
if (pos > 0) {
className = className.replace('$', '.');
}
try {
IType type = null;
// First look for the type in the Java project
if (javaProject != null) {
// TODO CD not sure why we need
type = javaProject.findType(className, new NullProgressMonitor());
// type = javaProject.findType(className);
if (type != null) {
return type;
}
}
// Then look for the type in the referenced Java projects
for (IProject refProject : project.getReferencedProjects()) {
IJavaProject refJavaProject = JdtUtils.getJavaProject(refProject);
if (refJavaProject != null) {
type = refJavaProject.findType(className);
if (type != null) {
return type;
}
}
}
// fall back and try to locate the class using AJDT
// TODO: uncomment this call
// return getAjdtType(project, className);
}
catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error getting Java type '"
+ className + "'", e));
}
}
return null;
}
public static final IType getJavaTypeForMethodReturnType(IMethod method, IType contextType) {
try {
return JdtUtils.getJavaTypeFromSignatureClassName(method.getReturnType(), contextType);
}
catch (JavaModelException e) {
}
return null;
}
public static IType getJavaTypeFromSignatureClassName(String className, IType contextType) {
if (contextType == null || className == null) {
return null;
}
try {
return JdtUtils.getJavaType(contextType.getJavaProject().getProject(),
JdtUtils.resolveClassNameBySignature(className, contextType));
}
catch (IllegalArgumentException e) {
// do Nothing
}
return null;
}
@SuppressWarnings("unchecked")
public static final List<IType> getJavaTypesForMethodParameterTypes(IMethod method, IType contextType) {
if (method == null || method.getParameterTypes() == null || method.getParameterTypes().length == 0) {
return Collections.EMPTY_LIST;
}
List<IType> parameterTypes = new ArrayList<IType>(method.getParameterTypes().length);
String[] parameterTypeNames = method.getParameterTypes();
for (String parameterTypeName : parameterTypeNames) {
parameterTypes.add(JdtUtils.getJavaTypeFromSignatureClassName(parameterTypeName, contextType));
}
return parameterTypes;
}
public static IClasspathEntry getJreVariableEntry() {
return JavaRuntime.getDefaultJREContainerEntry();
}
public static int getLineNumber(IJavaElement element) {
if (element != null && element instanceof IMethod) {
try {
IMethod method = (IMethod) element;
int lines = 0;
if (method.getDeclaringType() != null && method.getDeclaringType().getCompilationUnit() != null) {
String targetsource = method.getDeclaringType().getCompilationUnit().getSource();
if (targetsource != null) {
String sourceuptomethod = targetsource.substring(0, method.getNameRange().getOffset());
char[] chars = new char[sourceuptomethod.length()];
sourceuptomethod.getChars(0, sourceuptomethod.length(), chars, 0);
for (char element0 : chars) {
if (element0 == '\n') {
lines++;
}
}
return new Integer(lines + 1);
}
}
}
catch (JavaModelException e) {
}
}
else if (element != null && element instanceof IType && ((IType) element).getCompilationUnit() != null) {
try {
IType type = (IType) element;
int lines = 0;
String targetsource = type.getCompilationUnit().getSource();
if (targetsource != null) {
String sourceuptomethod = targetsource.substring(0, type.getNameRange().getOffset());
char[] chars = new char[sourceuptomethod.length()];
sourceuptomethod.getChars(0, sourceuptomethod.length(), chars, 0);
for (char element0 : chars) {
if (element0 == '\n') {
lines++;
}
}
return new Integer(lines + 1);
}
}
catch (JavaModelException e) {
}
}
else if (element != null && element instanceof IField) {
try {
IField type = (IField) element;
int lines = 0;
ICompilationUnit cu = type.getCompilationUnit();
if (cu != null) {
String targetsource = cu.getSource();
if (targetsource != null) {
String sourceuptomethod = targetsource.substring(0, type.getNameRange().getOffset());
char[] chars = new char[sourceuptomethod.length()];
sourceuptomethod.getChars(0, sourceuptomethod.length(), chars, 0);
for (char element0 : chars) {
if (element0 == '\n') {
lines++;
}
}
return new Integer(lines + 1);
}
}
}
catch (JavaModelException e) {
}
}
return new Integer(-1);
}
// public static IMethod getMethod(IType type, String methodName, Class[]
// parameterTypes) {
// String[] parameterTypesAsString =
// getParameterTypesAsStringArray(parameterTypes);
// return getMethod(type, methodName, parameterTypesAsString);
// }
// public static IMethod getMethod(IType type, String methodName, String[]
// parameterTypes) {
// int index = methodName.indexOf('(');
// if (index >= 0) {
// methodName = methodName.substring(0, index);
// }
// try {
// Set<IMethod> methods = Introspector.getAllMethods(type);
// for (IMethod method : methods) {
// if (method.getElementName().equals(methodName)
// && method.getParameterTypes().length == parameterTypes.length) {
// String[] methodParameterTypes = getParameterTypesAsStringArray(method);
// if (Arrays.deepEquals(parameterTypes, methodParameterTypes)) {
// return method;
// }
// }
// }
//
// return Introspector.findMethod(type, methodName, parameterTypes.length,
// Public.YES, Static.DONT_CARE);
// }
// catch (JavaModelException e) {
// }
// return null;
// }
public static String getMethodName(IMethod method) {
// Special support Ajdt intertype declarations
String methodName = method.getElementName();
int index = methodName.lastIndexOf('.');
if (index > 0) {
methodName = methodName.substring(index + 1);
}
return methodName;
}
public static String[] getParameterTypesString(IMethod method) {
try {
String[] parameterQualifiedTypes = Signature.getParameterTypes(method.getSignature());
int length = parameterQualifiedTypes == null ? 0 : parameterQualifiedTypes.length;
String[] parameterPackages = new String[length];
for (int i = 0; i < length; i++) {
parameterQualifiedTypes[i] = parameterQualifiedTypes[i].replace('/', '.');
parameterPackages[i] = Signature.getSignatureSimpleName(parameterQualifiedTypes[i]);
}
return parameterPackages;
}
catch (IllegalArgumentException e) {
}
catch (JavaModelException e) {
}
return null;
}
public static String getParentName(IMethod method) {
// Special support Ajdt intertype declarations
String methodName = method.getElementName();
int index = methodName.lastIndexOf('.');
if (index > 0) {
return methodName.substring(0, index);
}
else {
return method.getParent().getElementName();
}
}
// public static IProjectClassLoaderSupport
// getProjectClassLoaderSupport(IProject je, ClassLoader parentClassLoader)
// {
// return new DefaultProjectClassLoaderSupport(je, parentClassLoader);
// }
public static String getPropertyNameFromMethodName(IMethod method) {
// Special support Ajdt intertype declarations
String methodName = method.getElementName();
int index = methodName.lastIndexOf('.');
if (index > 0) {
methodName = methodName.substring(index + 1);
}
String replaceText = methodName.substring("set".length());
if (replaceText != null) {
replaceText = java.beans.Introspector.decapitalize(replaceText);
}
return replaceText;
}
public static String getReturnTypeString(IMethod method, boolean classTypesOnly) {
try {
String qualifiedReturnType = Signature.getReturnType(method.getSignature());
if (!classTypesOnly || qualifiedReturnType.startsWith("L") || qualifiedReturnType.startsWith("Q")) {
return Signature.getSignatureSimpleName(qualifiedReturnType.replace('/', '.'));
}
}
catch (IllegalArgumentException e) {
}
catch (JavaModelException e) {
}
return null;
}
public static IResource getSourceResource(IResource classFile) {
try {
if (isJavaProject(classFile) && classFile.getName().endsWith(CLASS_FILE_EXTENSION)) {
IPath classFilePath = classFile.getFullPath();
String classFileName = null;
IJavaProject project = getJavaProject(classFile);
IPath defaultOutput = project.getOutputLocation();
if (defaultOutput.isPrefixOf(classFilePath)) {
classFileName = classFilePath.removeFirstSegments(defaultOutput.segmentCount()).toString();
}
else {
for (IClasspathEntry entry : project.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath output = entry.getOutputLocation();
if (output != null) {
if (classFilePath.isPrefixOf(output)) {
classFileName = classFilePath.removeFirstSegments(output.segmentCount()).toString();
}
}
}
}
}
if (classFileName != null) {
// Replace file extension
String sourceFileName = classFileName.replace(".class", ".java");
for (IClasspathEntry entry : project.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath path = entry.getPath().append(sourceFileName).removeFirstSegments(1);
IResource resource = project.getProject().findMember(path);
if (resource != null) {
return resource;
}
}
}
}
}
}
catch (JavaModelException e) {
}
return null;
}
public static boolean isAjdtPresent() {
try {
Class.forName(AJDT_CLASS);
return true;
}
catch (ClassNotFoundException e) {
return false;
}
}
/**
* Returns true if given resource's project is a ADJT project.
*/
public static boolean isAjdtProject(IResource resource) {
return SpringCoreUtils.hasNature(resource, AJDT_NATURE);
}
/**
* Determines if the <code>resource</code> under question is the .classpath
* file of a {@link IJavaProject}.
*/
public static boolean isClassPathFile(IResource resource) {
String classPathFileName = resource.getProject().getFullPath().append(CLASSPATH_FILENAME).toString();
return resource.getFullPath().toString().equals(classPathFileName);
}
/**
* Returns true if given resource's project is a Java project.
*/
public static boolean isJavaProject(IResource resource) {
return SpringCoreUtils.hasNature(resource, JavaCore.NATURE_ID);
}
// public static boolean isTypeAjdtElement(IType type) {
// if (IS_AJDT_PRESENT) {
// return AjdtUtils.isTypeAjdtElement(type);
// }
// return false;
// }
public static boolean isTypeGroovyElement(IType type) {
// TODO CD verify following check with Groovy Eclipse
ICompilationUnit cu = type.getCompilationUnit();
if (cu != null && cu.getResource() != null) {
return cu.getResource().getName().endsWith(GROOVY_FILE_EXTENSION);
}
else if (cu != null) {
try {
IResource resource = cu.getUnderlyingResource();
if (resource != null) {
return resource.getName().endsWith(GROOVY_FILE_EXTENSION);
}
}
catch (JavaModelException e) {
// ignore
}
}
return false;
}
public static String resolveClassName(String className, IType type) {
if (className == null || type == null) {
return className;
}
// replace binary $ inner class name syntax with . for source level
className = className.replace('$', '.');
String dotClassName = new StringBuilder().append('.').append(className).toString();
IProject project = type.getJavaProject().getProject();
try {
// Special handling for some well-know classes
if (className.startsWith("java.lang") && getJavaType(project, className) != null) {
return className;
}
// Check if the class is imported
if (!type.isBinary()) {
// Strip className to first segment to support
// ReflectionUtils.MethodCallback
int ix = className.lastIndexOf('.');
String firstClassNameSegment = className;
if (ix > 0) {
firstClassNameSegment = className.substring(0, ix);
}
// Iterate the imports
for (IImportDeclaration importDeclaration : type.getCompilationUnit().getImports()) {
String importName = importDeclaration.getElementName();
// Wildcard imports -> check if the package + className is a
// valid type
if (importDeclaration.isOnDemand()) {
String newClassName = new StringBuilder(importName.substring(0, importName.length() - 1))
.append(className).toString();
if (getJavaType(project, newClassName) != null) {
return newClassName;
}
}
// Concrete import matching .className at the end -> check
// if type exists
else if (importName.endsWith(dotClassName) && getJavaType(project, importName) != null) {
return importName;
}
// Check if className is multi segmented
// (ReflectionUtils.MethodCallback)
// -> check if the first segment
else if (!className.equals(firstClassNameSegment)) {
if (importName.endsWith(firstClassNameSegment)) {
String newClassName = new StringBuilder(importName.substring(0,
importName.lastIndexOf('.') + 1)).append(className).toString();
if (getJavaType(project, newClassName) != null) {
return newClassName;
}
}
}
}
}
// Check if the class is in the same package as the type
String packageName = type.getPackageFragment().getElementName();
String newClassName = new StringBuilder(packageName).append(dotClassName).toString();
if (getJavaType(project, newClassName) != null) {
return newClassName;
}
// Check if the className is sufficient (already fully-qualified)
if (getJavaType(project, className) != null) {
return className;
}
// Check if the class is coming from the java.lang
newClassName = new StringBuilder("java.lang").append(dotClassName).toString();
if (getJavaType(project, newClassName) != null) {
return newClassName;
}
// Fall back to full blown resolution
String[][] fullInter = type.resolveType(className);
if (fullInter != null && fullInter.length > 0) {
return fullInter[0][0] + "." + fullInter[0][1];
}
}
catch (JavaModelException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "An error occurred resolving class name",
e));
}
return className;
}
public static String resolveClassNameBySignature(String className, IType type) {
className = Signature.toString(className).replace('$', '.');
return resolveClassName(className, type);
}
public static void visitTypeAst(IType type, ASTVisitor visitor) {
if (type != null && type.getCompilationUnit() != null) {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(type.getCompilationUnit());
parser.setResolveBindings(true);
ASTNode node = parser.createAST(new NullProgressMonitor());
node.accept(visitor);
}
}
// private static boolean doesImplementWithJdt(IResource resource, IType
// type, String className) {
// IType interfaceType = getJavaType(resource.getProject(), className);
// if (type != null && interfaceType != null) {
// try {
// IType[] subTypes =
// SuperTypeHierarchyCache.getTypeHierarchy(interfaceType)
// .getAllSubtypes(interfaceType);
// if (subTypes != null) {
// for (IType subType : subTypes) {
// if (subType.equals(type)) {
// return true;
// }
// }
// }
// }
// catch (JavaModelException ex) {
// StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
// "An error occurred resolving subtypes", ex));
// }
// }
// return false;
// }
// private static String[] getParameterTypesAsStringArray(Class[]
// parameterTypes) {
// String[] parameterTypesAsString = new String[parameterTypes.length];
// for (int i = 0; i < parameterTypes.length; i++) {
// parameterTypesAsString[i] =
// ClassUtils.getQualifiedName(parameterTypes[i]);
// }
// return parameterTypesAsString;
// }
private static String[] getParameterTypesAsStringArray(IMethod method) {
Set<String> typeParameterNames = new HashSet<String>();
try {
for (ITypeParameter param : method.getDeclaringType().getTypeParameters()) {
typeParameterNames.add(param.getElementName());
}
for (ITypeParameter param : method.getTypeParameters()) {
typeParameterNames.add(param.getElementName());
}
}
catch (JavaModelException e) {
}
String[] parameterTypesAsString = new String[method.getParameterTypes().length];
for (int i = 0; i < method.getParameterTypes().length; i++) {
String parameterTypeString = Signature.getElementType(method.getParameterTypes()[i]);
boolean isArray = !parameterTypeString.equals(method.getParameterTypes()[i]);
String parameterType = resolveClassNameBySignature(parameterTypeString, method.getDeclaringType());
if (typeParameterNames.contains(parameterType)) {
parameterTypesAsString[i] = Object.class.getName() + (isArray ? ARRAY_SUFFIX : "");
}
else {
parameterTypesAsString[i] = parameterType + (isArray ? ARRAY_SUFFIX : "");
}
}
return parameterTypesAsString;
}
// static class DefaultProjectClassLoaderSupport implements
// IProjectClassLoaderSupport {
//
// private ClassLoader classLoader;
//
// private ClassLoader weavingClassLoader;
//
// public DefaultProjectClassLoaderSupport(IProject javaProject, ClassLoader
// parentClassLoader) {
// setupClassLoaders(javaProject, parentClassLoader);
// }
//
// public void executeCallback(IProjectClassLoaderAwareCallback callback)
// throws Throwable {
// try {
// activateWeavingClassLoader();
// callback.doWithActiveProjectClassLoader();
// }
// finally {
// recoverClassLoader();
// }
// }
//
// public ClassLoader getProjectClassLoader() {
// return this.weavingClassLoader;
// }
//
// /**
// * Activates the weaving class loader as thread context classloader.
// * <p>
// * Use {@link #recoverClassLoader()} to recover the original thread
// * context classloader
// */
// private void activateWeavingClassLoader() {
// Thread.currentThread().setContextClassLoader(weavingClassLoader);
// }
//
// private void recoverClassLoader() {
// Thread.currentThread().setContextClassLoader(classLoader);
// }
//
// private void setupClassLoaders(IProject project, ClassLoader
// parentClassLoader) {
// classLoader = Thread.currentThread().getContextClassLoader();
// weavingClassLoader = ProjectClassLoaderCache.getClassLoader(project,
// parentClassLoader);
// }
// }
}

View File

@@ -0,0 +1,118 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 Spring IDE Developers
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spring IDE Developers - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* Some {@link IMarker} helper methods.
* @author Torsten Juergeleit
* @author Christian Dupuis
*/
public final class MarkerUtils {
public static final String ORIGINATING_RESOURCE_KEY = "originatingResource";
public static final String ELEMENT_ID_KEY = "elementId";
public static int getHighestSeverityFromMarkersInRange(IResource resource, String markerId,
int startLine, int endLine) {
int severity = -1;
if (resource != null) {
for (IMarker marker : getAllMarkersInRange(resource, markerId, startLine, endLine)) {
int sev = marker.getAttribute(IMarker.SEVERITY, -1);
if (sev == IMarker.SEVERITY_WARNING) {
severity = sev;
}
else if (sev == IMarker.SEVERITY_ERROR) {
severity = sev;
break;
}
}
}
return severity;
}
public static Set<IMarker> getAllMarkersInRange(IResource resource, String markerId, int startLine, int endLine) {
Set<IMarker> foundMarkers = new HashSet<IMarker>();
if (resource != null) {
try {
IMarker[] markers = resource.findMarkers(markerId, true,
IResource.DEPTH_INFINITE);
for (IMarker marker : markers) {
if (startLine == -1 || isMarkerInRange(marker, startLine, endLine)) {
foundMarkers.add(marker);
}
}
}
catch (CoreException e) {
// ignore
}
}
return foundMarkers;
}
public static boolean isMarkerInRange(IMarker marker, int startLine, int endLine)
throws CoreException {
if (startLine >= 0 && endLine >= startLine && marker.isSubtypeOf(IMarker.TEXT)) {
int line = marker.getAttribute(IMarker.LINE_NUMBER, -1);
return (line >= startLine && line <= endLine);
}
return false;
}
/**
* Removes all {@link IMarker markers} with the given id (including the
* inherited ones) from given {@link IResource} and it's members that if the
* marker has an attribute under the key named
* {@link #ORIGINATING_RESOURCE_KEY} attribute that matches the given
* {@link IResource#getFullPath()}.
*/
public static void deleteAllMarkers(IResource resource, String id) {
if (resource != null && resource.isAccessible()) {
try {
IMarker[] markers = resource.findMarkers(id, true,
IResource.DEPTH_ONE);
for (IMarker marker : markers) {
// if (originatingResourceValue.equals(marker
// .getAttribute(ORIGINATING_RESOURCE_KEY))) {
marker.delete();
// }
}
}
catch (CoreException e) {
CorePlugin.log(e);
}
}
}
/**
* Removes all {@link IMarker markers} with given id (including the
* inherited ones) from given {@link IResource} and it's members.
*/
public static void deleteMarkers(IResource resource, String id) {
if (resource != null && resource.isAccessible()) {
try {
resource.deleteMarkers(id, true, IResource.DEPTH_INFINITE);
}
catch (CoreException e) {
CorePlugin.log(e);
}
}
}
}

View File

@@ -0,0 +1,102 @@
/*******************************************************************************
* Copyright (c) 2006, 2007 Spring IDE Developers
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spring IDE Developers - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* @author Torsten Juergeleit
* @author Christian Dupuis
*/
public final class PatternUtils {
private PatternUtils() {
// Not for instantiation
}
/**
* Creates a pattern element from the pattern string which is either a
* reg-ex expression or of wildcard format ('*' matches any character and
* '?' matches one character).
* @param pattern the search pattern
* @param isCaseSensitive set to <code>true</code> to create a case
* insensitve pattern
* @param isRegexSearch <code>true</code> if the passed string is a reg-ex
* pattern
* @throws PatternSyntaxException
*/
public static Pattern createPattern(String pattern,
boolean isCaseSensitive, boolean isRegexSearch)
throws PatternSyntaxException {
if (!isRegexSearch) {
pattern = toRegExFormat(pattern);
}
if (!isCaseSensitive) {
return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE |
Pattern.UNICODE_CASE | Pattern.MULTILINE);
}
return Pattern.compile(pattern, Pattern.MULTILINE);
}
/**
* Converts wildcard format ('*' and '?') to reg-ex format.
*/
private static String toRegExFormat(String pattern) {
StringBuffer regex = new StringBuffer(pattern.length());
boolean escaped = false;
boolean quoting = false;
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (c == '*' && !escaped) {
if (quoting) {
regex.append("\\E");
quoting = false;
}
regex.append(".*");
escaped = false;
continue;
} else if (c == '?' && !escaped) {
if (quoting) {
regex.append("\\E");
quoting = false;
}
regex.append(".");
escaped = false;
continue;
} else if (c == '\\' && !escaped) {
escaped = true;
continue;
} else if (c == '\\' && escaped) {
escaped = false;
if (quoting) {
regex.append("\\E");
quoting = false;
}
regex.append("\\\\");
continue;
}
if (!quoting) {
regex.append("\\Q");
quoting = true;
}
if (escaped && c != '*' && c != '?' && c != '\\') {
regex.append('\\');
}
regex.append(c);
escaped = c == '\\';
}
if (quoting) {
regex.append("\\E");
}
return regex.toString();
}
}

View File

@@ -0,0 +1,38 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
/**
* @author Steffen Pingel
* @author Leo Dos Santos
* @author Christian Dupuis
*/
public class Policy {
public static boolean TEST_MODE;
static {
String application = System.getProperty("eclipse.application", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (application.length() > 0) {
TEST_MODE = application.endsWith("testapplication") || application.endsWith("uitest"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public static void checkCancelled(IProgressMonitor monitor) {
if (monitor != null && monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
}

View File

@@ -0,0 +1,344 @@
/*******************************************************************************
* Copyright (c) 2012 - 2014 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.osgi.util.NLS;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;
import org.osgi.service.prefs.BackingStoreException;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* Provides access to externalized resources such as urls. Resources are
* specified through an extension point.
*
* @author Steffen Pingel
* @author Christian Dupuis
*/
public class ResourceProvider {
public static final String RECORD_SEPARATOR_PATTERN = "[\\r\\n\\s]";
public static final String FIELD_SEPARATOR = "|";
public static final String FIELD_SEPARATOR_PATTERN = "\\|";
public static final String RECORD_SEPARATOR = "\n";
public static class Property {
public String type;
private String id;
private String label;
private String defaultValue;
private boolean multiValue;
private boolean userConfigurable;
private String contributedValue;
private final ResourceProvider provider;
private Property(ResourceProvider provider) {
this.provider = provider;
}
public String getDefaultValue() {
String value = contributedValue;
if (value == null) {
value = defaultValue;
}
return value;
}
public String getLabel() {
return label;
}
public String getValue() {
String value = provider.getPreferences().get(id, null);
if (value == null) {
value = contributedValue;
}
if (value == null) {
value = defaultValue;
}
return value;
}
public boolean isMultiValue() {
return multiValue;
}
public boolean isUserConfigurable() {
return userConfigurable;
}
public void setValue(String value) {
provider.getPreferences().put(id, value);
try {
provider.getPreferences().flush();
} catch (BackingStoreException e) {
StatusHandler.log(new Status(IStatus.ERROR,
CorePlugin.PLUGIN_ID,
"Error occured while saving preferences", e));
}
}
}
private static class ExtensionPointReader {
private static final String ATTRIBUTE_ID = "id";
private static final String ATTRIBUTE_VALUE = "value";
private static final String ATTRIBUTE_LABEL = "label";
private static final String ATTRIBUTE_TYPE = "type";
private static final String ATTRIBUTE_MULTI_VALUE = "multiValue";
private static final String ATTRIBUTE_DEFAULT_VALUE = "defaultValue";
private static final String ATTRIBUTE_USER_CONFIGURABLE = "userConfigurable";
private static final String ELEMENT_URL = "url";
private static final String ELEMENT_PROPERTY = "propertyDefinition";
private static final String EXTENSION_ID_REFERENCES = "com.springsource.sts.core.resources";
private final Map<String, String> valueByKey = new HashMap<String, String>();
private final Map<String, Property> propertyById = new HashMap<String, Property>();
public void read(ResourceProvider resourceProvider) {
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint extensionPoint = registry
.getExtensionPoint(EXTENSION_ID_REFERENCES);
IExtension[] extensions = extensionPoint.getExtensions();
// read property definitions
for (IExtension extension : extensions) {
IConfigurationElement[] elements = extension
.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (element.getName().compareTo(ELEMENT_PROPERTY) == 0) {
Property p = new Property(resourceProvider);
p.id = element.getAttribute(ATTRIBUTE_ID);
p.label = element.getAttribute(ATTRIBUTE_LABEL);
p.defaultValue = element
.getAttribute(ATTRIBUTE_DEFAULT_VALUE);
p.multiValue = Boolean.parseBoolean(element
.getAttribute(ATTRIBUTE_MULTI_VALUE));
p.userConfigurable = Boolean.parseBoolean(element
.getAttribute(ATTRIBUTE_USER_CONFIGURABLE));
p.type = element.getAttribute(ATTRIBUTE_TYPE);
propertyById.put(p.id, p);
}
}
}
// read contributed definitions
for (IExtension extension : extensions) {
IConfigurationElement[] elements = extension
.getConfigurationElements();
for (IConfigurationElement element : elements) {
if (element.getName().compareTo(ELEMENT_URL) == 0) {
String key = element.getAttribute(ATTRIBUTE_ID);
String value = element.getAttribute(ATTRIBUTE_VALUE);
valueByKey.put(key, value);
Property p = propertyById.get(key);
if (p == null) {
// property was not defined explicitly
p = new Property(resourceProvider);
p.id = key;
p.label = "";
propertyById.put(p.id, p);
}
p.contributedValue = value;
}
}
}
}
}
private final IEclipsePreferences preferences;
private static ResourceProvider instance = new ResourceProvider();
public static ResourceProvider getInstance() {
return instance;
}
public static String getUrl(String key) {
return getUrls(key)[0];
}
public static String[] getUrls(String key) {
String[] urls = parseUrls(key, instance.getValue(key));
String[] defaultUrls = parseUrls(key, instance.getDefaultValue(key));
Set<String> cleanableUrls = new HashSet<>();
for (String url : defaultUrls) {
if (url.startsWith("https:")) {
cleanableUrls.add("http:"+url.substring(6));
} else if (url.startsWith("http:")) {
cleanableUrls.add(url);
}
}
for (int i = 0; i < urls.length; i++) {
String url = urls[i];
if (cleanableUrls.contains(url)) {
urls[i] = "https:"+url.substring(5);
}
}
return urls;
}
private static String[] parseUrls(String key, String value) {
if (value == null) {
throw new RuntimeException(NLS.bind(
"No URL found for key: ''{0}''", key));
}
if (value.isEmpty()) {
return new String[0];
}
// Post process the urls to replace UUID and version number placeholders
if (value.contains("%UUID%")) {
value = value.replace("%UUID%", CorePlugin.getUUID());
}
if (value.contains("%VERSION%") || value.contains("%SHORT_VERSION%")) {
Bundle bundle = CorePlugin.getDefault().getBundle();
Version version = new Version((String) bundle.getHeaders().get(
"Bundle-Version")); //$NON-NLS-1$
value = value.replace("%VERSION%", version.toString());
value = value.replace("%SHORT_VERSION%", version.getMajor() + "."
+ version.getMinor());
}
String[] values = value.split(RECORD_SEPARATOR_PATTERN);
return discardLocationNames(values);
}
private static String[] discardLocationNames(String[] values) {
for (int i = 0; i < values.length; i++) {
String nameUrlString = values[i];
String[] nameUrlStrings = nameUrlString
.split(FIELD_SEPARATOR_PATTERN);
if (nameUrlStrings.length == 2) {
String url = nameUrlStrings[1];
values[i] = url;
}
}
return values;
}
private final Map<String, Property> propertyById;
private final List<PropertyChangeListener> listeners;
private ResourceProvider() {
this.listeners = new CopyOnWriteArrayList<PropertyChangeListener>();
this.preferences = new InstanceScope().getNode(CorePlugin.PLUGIN_ID);
this.preferences
.addPreferenceChangeListener(new IPreferenceChangeListener() {
public void preferenceChange(PreferenceChangeEvent event) {
Property p = propertyById.get(event.getKey());
if (p != null) {
for (PropertyChangeListener listener : listeners) {
listener.propertyChange(new PropertyChangeEvent(
ResourceProvider.this, p.id, event
.getOldValue(), event
.getNewValue()));
}
}
}
});
DefaultScope.INSTANCE.getNode(CorePlugin.PLUGIN_ID).addPreferenceChangeListener(new IPreferenceChangeListener() {
@Override
public void preferenceChange(PreferenceChangeEvent event) {
Property p = propertyById.get(event.getKey());
if (p != null) {
p.defaultValue = (String)event.getNewValue();
}
}
});
ExtensionPointReader reader = new ExtensionPointReader();
reader.read(this);
this.propertyById = reader.propertyById;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.add(listener);
}
public IEclipsePreferences getPreferences() {
return preferences;
}
public Collection<Property> getProperties() {
return Collections.unmodifiableCollection(propertyById.values());
}
public Property getProperty(String id) {
return propertyById.get(id);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
listeners.remove(listener);
}
private String getValue(String key) {
Property p = propertyById.get(key);
return (p != null) ? p.getValue() : null;
}
private String getDefaultValue(String key) {
Property p = propertyById.get(key);
return (p != null) ? p.getDefaultValue() : null;
}
}

View File

@@ -0,0 +1,104 @@
// COPIED from spring-ide org.springframework.ide.eclipse.core.SpringCorePreferences
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.service.prefs.BackingStoreException;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* @author Christian Dupuis
* @since 2.0
*/
public class SpringCorePreferences {
/** The identifier for enablement of project versus workspace settings */
public static final String PROJECT_PROPERTY_ID = "enable.project.preferences";
private final String propertyNamespace;
private final IEclipsePreferences preferences;
private SpringCorePreferences(IProject project, String qualifier) {
this.propertyNamespace = qualifier + '.';
this.preferences = getEclipsePreferences(project, qualifier);
}
// public static SpringCorePreferences getProjectPreferences(IProject
// project) {
// return getProjectPreferences(project, SpringCore.PLUGIN_ID);
// }
public static SpringCorePreferences getProjectPreferences(IProject project, String qualifier) {
return new SpringCorePreferences(project, qualifier);
}
public static SpringCorePreferences getPluginPreferences(String qualifier) {
return new SpringCorePreferences(null, qualifier);
}
private IEclipsePreferences getEclipsePreferences(IProject project, String qualifier) {
IScopeContext context = project!=null
? new ProjectScope(project)
: InstanceScope.INSTANCE;
IEclipsePreferences node = context.getNode(qualifier);
return node;
}
public void putString(String key, String value) {
if (key == null || value == null) {
return;
}
try {
this.preferences.put(propertyNamespace + key, value);
this.preferences.flush();
}
catch (BackingStoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "An error occurred updating preferences",
e));
}
}
public void putBoolean(String key, boolean value) {
if (key == null) {
return;
}
try {
this.preferences.putBoolean(propertyNamespace + key, value);
this.preferences.flush();
}
catch (BackingStoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "An error occurred updating preferences",
e));
}
}
public String getString(String key, String defaultValue) {
return this.preferences.get(propertyNamespace + key, defaultValue);
}
public boolean getBoolean(String key, boolean defaultValue) {
return this.preferences.getBoolean(propertyNamespace + key, defaultValue);
}
public IEclipsePreferences getProjectPreferences() {
return this.preferences;
}
}

View File

@@ -0,0 +1,809 @@
// COPIED from spring-ide org.springframework.ide.eclipse.core.SpringCoreUtils
/*******************************************************************************
* Copyright (c) 2012, 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IPathVariableManager;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.wst.common.project.facet.core.FacetedProjectFramework;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Some helper methods.
* @author Torsten Juergeleit
* @author Christian Dupuis
* @author Martin Lippert
*/
public final class SpringCoreUtils {
/**
* File name of OSGi bundle manifests
* @since 2.0.5
*/
public static String BUNDLE_MANIFEST_FILE = "MANIFEST.MF";
/**
* Folder name of OSGi bundle manifests directories
* @since 2.0.5
*/
public static String BUNDLE_MANIFEST_FOLDER = "META-INF";
/** New placeholder string for Spring 3 EL support */
public static final String EL_PLACEHOLDER_PREFIX = "#{";
/** URL file schema */
public static final String FILE_SCHEME = "file";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static final String PLACEHOLDER_PREFIX = "${";
public static final String PLACEHOLDER_SUFFIX = "}";
public static final String SOURCE_CONTROL_SCHEME = "sourcecontrol";
private static final String DEPLOY_PATH = "deploy-path";
private static boolean DOCUMENT_BUILDER_ERROR = false;
private static final Object DOCUMENT_BUILDER_LOCK = new Object();
private static XPathExpression EXPRESSION;
private static boolean SAX_PARSER_ERROR = false;
private static final Object SAX_PARSER_LOCK = new Object();
private static final String SOURCE_PATH = "source-path";
private static final String XPATH_EXPRESSION = "//project-modules/wb-module/wb-resource";
private static final String SPRING_BUILDER_ID = "org.springframework.ide.eclipse.core.springbuilder";
private static final String MARKER_ID = "org.springframework.ide.eclipse.core.problemmarker";
public static final String NATURE_ID = "org.springframework.ide.eclipse.core.springnature";
static {
try {
XPathFactory newInstance = XPathFactory.newInstance();
XPath xpath = newInstance.newXPath();
EXPRESSION = xpath.compile(XPATH_EXPRESSION);
}
catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
/**
* Adds given builder to specified project.
*/
public static void addProjectBuilder(IProject project, String builderID, IProgressMonitor monitor)
throws CoreException {
IProjectDescription desc = project.getDescription();
ICommand builderCommand = getProjectBuilderCommand(desc, builderID);
if (builderCommand == null) {
// Add a new build spec
ICommand command = desc.newCommand();
command.setBuilderName(builderID);
// Commit the spec change into the project
addProjectBuilderCommand(desc, command);
project.setDescription(desc, monitor);
}
}
/**
* Adds (or updates) a builder in given project description.
*/
public static void addProjectBuilderCommand(IProjectDescription description, ICommand command) throws CoreException {
ICommand[] oldCommands = description.getBuildSpec();
ICommand oldBuilderCommand = getProjectBuilderCommand(description, command.getBuilderName());
ICommand[] newCommands;
if (oldBuilderCommand == null) {
// Add given builder to the end of the builder list
newCommands = new ICommand[oldCommands.length + 1];
System.arraycopy(oldCommands, 0, newCommands, 0, oldCommands.length);
newCommands[oldCommands.length] = command;
}
else {
// Replace old builder with given new one
for (int i = 0, max = oldCommands.length; i < max; i++) {
if (oldCommands[i] == oldBuilderCommand) {
oldCommands[i] = command;
break;
}
}
newCommands = oldCommands;
}
description.setBuildSpec(newCommands);
}
/**
* Adds given nature as first nature to specified project.
*/
public static void addProjectNature(IProject project, String nature, IProgressMonitor monitor) throws CoreException {
if (project != null && nature != null) {
if (!project.hasNature(nature)) {
IProjectDescription desc = project.getDescription();
String[] oldNatures = desc.getNatureIds();
String[] newNatures = new String[oldNatures.length + 1];
newNatures[0] = nature;
if (oldNatures.length > 0) {
System.arraycopy(oldNatures, 0, newNatures, 1, oldNatures.length);
}
desc.setNatureIds(newNatures);
project.setDescription(desc, monitor);
}
}
}
/**
* Triggers a build of the given {@link IProject} instance, but only the
* Spring builder
* @param project the project to build
*/
public static void buildProject(IProject project) {
buildProject(project, SPRING_BUILDER_ID);
}
/**
* Triggers a build of the given {@link IProject} instance with a full build
* and all builders
* @param project the project to build
*/
public static void buildFullProject(IProject project) {
buildProject(project, null);
}
/**
* Triggers a build of the given {@link IProject} instance, but only the
* Spring builder
* @param project the project to build
* @param builderID the ID of the specific builder that should be executed
* on the project
* @since 3.2.0
*/
public static void buildProject(IProject project, String builderID) {
if (ResourcesPlugin.getWorkspace().isAutoBuilding()) {
scheduleBuildInBackground(project, ResourcesPlugin.getWorkspace().getRuleFactory().buildRule(),
new Object[] { ResourcesPlugin.FAMILY_AUTO_BUILD }, builderID);
}
}
/**
* Creates given folder and (if necessary) all of it's parents.
*/
public static void createFolder(IFolder folder, IProgressMonitor monitor) throws CoreException {
if (!folder.exists()) {
IContainer parent = folder.getParent();
if (parent instanceof IFolder) {
createFolder((IFolder) parent, monitor);
}
folder.create(true, true, monitor);
}
}
/**
* Creates specified simple project.
*/
public static IProject createProject(String projectName, IProjectDescription description, IProgressMonitor monitor)
throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(projectName);
if (!project.exists()) {
if (description == null) {
project.create(monitor);
}
else {
project.create(description, monitor);
}
}
else {
project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (!project.isOpen()) {
project.open(monitor);
}
return project;
}
/**
* Finds the first line separator used by the given text.
* @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
* or <code>null</code> if none found
* @since 2.2.2
*/
public static String findLineSeparator(char[] text) {
// find the first line separator
int length = text.length;
if (length > 0) {
char nextChar = text[0];
for (int i = 0; i < length; i++) {
char currentChar = nextChar;
nextChar = i < length - 1 ? text[i + 1] : ' ';
switch (currentChar) {
case '\n':
return "\n"; //$NON-NLS-1$
case '\r':
return nextChar == '\n' ? "\r\n" : "\r"; //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
// not found
return null;
}
/**
* Returns the specified adapter for the given object or <code>null</code>
* if adapter is not supported.
*/
@SuppressWarnings("unchecked")
public static <T> T getAdapter(Object object, Class<T> adapter) {
if (object != null && adapter != null) {
if (adapter.isAssignableFrom(object.getClass())) {
return (T) object;
}
if (object instanceof IAdaptable) {
return (T) ((IAdaptable) object).getAdapter(adapter);
}
}
return null;
}
public static IFile getDeploymentDescriptor(IProject project) {
if (SpringCoreUtils.hasProjectFacet(project, "jst.web")) {
IFile settingsFile = project.getFile(".settings/org.eclipse.wst.common.component");
if (settingsFile.exists()) {
try {
NodeList nodes = (NodeList) EXPRESSION
.evaluate(parseDocument(settingsFile), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
if ("/".equals(element.getAttribute(DEPLOY_PATH))) {
String path = element.getAttribute(SOURCE_PATH);
if (path != null) {
IFile deploymentDescriptor = project.getFile(new Path(path).append("WEB-INF").append(
"web.xml"));
if (deploymentDescriptor.exists()) {
return deploymentDescriptor;
}
}
}
}
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.WARNING, CorePlugin.PLUGIN_ID, 1, e.getMessage(), e));
}
}
}
return null;
}
public static DocumentBuilder getDocumentBuilder() {
try {
DocumentBuilderFactory documentBuilderFactory = getDocumentBuilderFactory();
documentBuilderFactory.setExpandEntityReferences(false);
return documentBuilderFactory.newDocumentBuilder();
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating DocumentBuilder", e));
}
return null;
}
public static DocumentBuilderFactory getDocumentBuilderFactory() {
if (!DOCUMENT_BUILDER_ERROR) {
try {
// this might fail on IBM J9; therefore trying only once and
// then falling back to
// OSGi service reference as it should be
return DocumentBuilderFactory.newInstance();
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
"Error creating DocumentBuilderFactory. Switching to OSGi service reference."));
DOCUMENT_BUILDER_ERROR = true;
}
}
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference reference = bundleContext.getServiceReference(DocumentBuilderFactory.class.getName());
if (reference != null) {
try {
synchronized (DOCUMENT_BUILDER_LOCK) {
return (DocumentBuilderFactory) bundleContext.getService(reference);
}
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"Error creating DocumentBuilderFactory", e));
}
finally {
bundleContext.ungetService(reference);
}
}
return null;
}
/**
* Returns the line separator found in the given text. If it is null, or not
* found return the line delimiter for the given project. If the project is
* null, returns the line separator for the workspace. If still null, return
* the system line separator.
* @since 2.2.2
*/
public static String getLineSeparator(String text, IProject project) {
String lineSeparator = null;
// line delimiter in given text
if (text != null && text.length() != 0) {
lineSeparator = findLineSeparator(text.toCharArray());
if (lineSeparator != null) {
return lineSeparator;
}
}
// line delimiter in project preference
IScopeContext[] scopeContext;
if (project != null) {
scopeContext = new IScopeContext[] { new ProjectScope(project) };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME,
Platform.PREF_LINE_SEPARATOR, null, scopeContext);
if (lineSeparator != null) {
return lineSeparator;
}
}
// line delimiter in workspace preference
scopeContext = new IScopeContext[] { new InstanceScope() };
lineSeparator = Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR,
null, scopeContext);
if (lineSeparator != null) {
return lineSeparator;
}
// system line delimiter
return LINE_SEPARATOR;
}
/**
* Returns specified builder from given project description.
*/
public static ICommand getProjectBuilderCommand(IProjectDescription description, String builderID)
throws CoreException {
ICommand[] commands = description.getBuildSpec();
for (int i = commands.length - 1; i >= 0; i--) {
if (commands[i].getBuilderName().equals(builderID)) {
return commands[i];
}
}
return null;
}
public static IPath getProjectLocation(IProject project) {
return (project.getRawLocation() != null ? project.getRawLocation() : project.getLocation());
}
public static URI getResourceURI(IResource resource) {
if (resource != null) {
URI uri = resource.getRawLocationURI();
if (uri == null) {
uri = resource.getLocationURI();
}
if (uri != null) {
String scheme = uri.getScheme();
if (FILE_SCHEME.equalsIgnoreCase(scheme)) {
return uri;
}
else if (SOURCE_CONTROL_SCHEME.equals(scheme)) {
// special case of Rational Team Concert
IPath path = resource.getLocation();
File file = path.toFile();
if (file.exists()) {
return file.toURI();
}
}
else {
IPathVariableManager variableManager = ResourcesPlugin.getWorkspace().getPathVariableManager();
return variableManager.resolveURI(uri);
}
}
}
return null;
}
public static SAXParser getSaxParser() {
if (!SAX_PARSER_ERROR) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
return parser;
}
catch (Exception e) {
StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
"Error creating SaxParserFactory. Switching to OSGI service reference."));
SAX_PARSER_ERROR = true;
}
}
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference reference = bundleContext.getServiceReference(SAXParserFactory.class.getName());
if (reference != null) {
try {
synchronized (SAX_PARSER_LOCK) {
SAXParserFactory factory = (SAXParserFactory) bundleContext.getService(reference);
return factory.newSAXParser();
}
}
catch (Exception e) {
StatusHandler
.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory", e));
}
finally {
bundleContext.ungetService(reference);
}
}
return null;
}
/**
* Returns a list of all projects with the Spring project nature.
*/
public static Set<IProject> getSpringProjects() {
Set<IProject> projects = new LinkedHashSet<IProject>();
for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
if (isSpringProject(project)) {
projects.add(project);
}
}
return projects;
}
/**
* Returns true if given resource's project has the given nature.
*/
public static boolean hasNature(IResource resource, String natureId) {
if (resource != null && resource.isAccessible()) {
IProject project = resource.getProject();
if (project != null) {
try {
return project.hasNature(natureId);
}
catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID,
"An error occurred inspecting project nature", e));
}
}
}
return false;
}
/**
* Returns <code>true</code> if given text contains a placeholder, e.g.
* <code>${beansRef}</code> .
*/
public static boolean hasPlaceHolder(String text) {
if (text == null || StringUtils.isBlank(text)) {
return false;
}
int pos = text.indexOf(PLACEHOLDER_PREFIX);
int elPos = text.indexOf(EL_PLACEHOLDER_PREFIX);
return ((pos != -1 || elPos != -1) && text.indexOf(PLACEHOLDER_SUFFIX, pos) != -1);
}
public static boolean hasProjectFacet(IResource resource, String facetId) {
if (resource != null && resource.isAccessible()) {
try {
return JdtUtils.isJavaProject(resource)
&& FacetedProjectFramework.hasProjectFacet(resource.getProject(), facetId);
}
catch (CoreException e) {
// TODO CD handle exception
}
}
return false;
}
/**
* Returns true if Eclipse's runtime bundle has the same or a newer than
* given version.
*/
public static boolean isEclipseSameOrNewer(int majorVersion, int minorVersion) {
Bundle bundle = Platform.getBundle(Platform.PI_RUNTIME);
if (bundle != null) {
String versionString = (String) bundle.getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION);
try {
Version version = new Version(versionString);
int major = version.getMajor();
if (major > majorVersion) {
return true;
}
if (major == majorVersion) {
int minor = version.getMinor();
if (minor >= minorVersion) {
return true;
}
}
}
catch (IllegalArgumentException e) {
// ignore this exception as this can't occur in pratice
}
}
return false;
}
/**
* Checks if the given {@link IResource} is a OSGi bundle manifest.
* <p>
* Note: only the name and last segment of the folder name are checked.
* @since 2.0.5
*/
public static boolean isManifest(IResource resource) {
// check if it is a MANIFEST.MF file in META-INF
if (resource != null
// && resource.isAccessible()
&& resource.getType() == IResource.FILE && resource.getName().equals(BUNDLE_MANIFEST_FILE)
&& resource.getParent() != null && resource.getParent().getProjectRelativePath() != null
&& resource.getParent().getProjectRelativePath().lastSegment() != null
&& resource.getParent().getProjectRelativePath().lastSegment().equals(BUNDLE_MANIFEST_FOLDER)) {
// check if the manifest is not in an output folder
IPath filePath = resource.getFullPath();
IJavaProject javaProject = JdtUtils.getJavaProject(resource);
if (javaProject != null) {
try {
IPath defaultOutputLocation = javaProject.getOutputLocation();
if (defaultOutputLocation != null && defaultOutputLocation.isPrefixOf(filePath)) {
return false;
}
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath outputLocation = entry.getOutputLocation();
if (outputLocation != null && outputLocation.isPrefixOf(filePath)) {
return false;
}
}
}
}
catch (JavaModelException e) {
// don't care here
}
return true;
}
else {
// if the project is not a java project -> it is the manifest
return true;
}
}
return false;
}
/**
* Returns true if given resource's project is a Spring project.
*/
public static boolean isSpringProject(IResource resource) {
return hasNature(resource, NATURE_ID);
}
/**
* Returns true if Eclipse's runtime bundle has the same or a newer than
* given version.
*/
public static boolean isVersionSameOrNewer(String versionString, int majorVersion, int minorVersion,
int microVersion) {
return new Version(versionString).compareTo(new Version(majorVersion, minorVersion, microVersion)) >= 0;
}
public static Document parseDocument(IFile deploymentDescriptor) {
try {
if (getResourceURI(deploymentDescriptor) != null) {
return parseDocument(getResourceURI(deploymentDescriptor));
}
return getDocumentBuilder().parse(new InputSource(deploymentDescriptor.getContents()));
}
catch (SAXException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
catch (CoreException e) {
throw new RuntimeException(e);
}
}
public static Document parseDocument(URI deploymentDescriptor) {
try {
return getDocumentBuilder().parse(deploymentDescriptor.toString());
}
catch (SAXException e) {
throw new RuntimeException(e);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Removes given builder from specified project.
*/
public static void removeProjectBuilder(IProject project, String builderID, IProgressMonitor monitor)
throws CoreException {
if (project != null && builderID != null) {
IProjectDescription desc = project.getDescription();
ICommand[] commands = desc.getBuildSpec();
for (int i = commands.length - 1; i >= 0; i--) {
if (commands[i].getBuilderName().equals(builderID)) {
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy(commands, 0, newCommands, 0, i);
System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
// Commit the spec change into the project
desc.setBuildSpec(newCommands);
project.setDescription(desc, monitor);
break;
}
}
}
}
/**
* Removes given nature from specified project.
*/
public static void removeProjectNature(IProject project, String nature, IProgressMonitor monitor)
throws CoreException {
if (project != null && nature != null) {
if (project.exists() && project.hasNature(nature)) {
// first remove all problem markers (including the
// inherited ones) from Spring beans project
if (nature.equals(NATURE_ID)) {
project.deleteMarkers(MARKER_ID, true, IResource.DEPTH_INFINITE);
}
// now remove project nature
IProjectDescription desc = project.getDescription();
String[] oldNatures = desc.getNatureIds();
String[] newNatures = new String[oldNatures.length - 1];
int newIndex = oldNatures.length - 2;
for (int i = oldNatures.length - 1; i >= 0; i--) {
if (!oldNatures[i].equals(nature)) {
newNatures[newIndex--] = oldNatures[i];
}
}
desc.setNatureIds(newNatures);
project.setDescription(desc, monitor);
}
}
}
/**
* Verify that file can safely be modified; eventually checkout the file
* from source code control.
* @return <code>true</code> if resource can be modified
* @since 2.2.9
*/
public static boolean validateEdit(IFile... files) {
for (IFile file : files) {
if (!file.exists()) {
return false;
}
}
IStatus status = ResourcesPlugin.getWorkspace().validateEdit(files, IWorkspace.VALIDATE_PROMPT);
if (status.isOK()) {
return true;
}
return false;
}
private static void scheduleBuildInBackground(final IProject project, ISchedulingRule rule,
final Object[] jobFamilies, final String builderID) {
Job job = new Job("Building workspace") {
@Override
public boolean belongsTo(Object family) {
if (jobFamilies == null || family == null) {
return false;
}
for (Object jobFamilie : jobFamilies) {
if (family.equals(jobFamilie)) {
return true;
}
}
return false;
}
@Override
public IStatus run(IProgressMonitor monitor) {
try {
if (builderID != null) {
project.build(IncrementalProjectBuilder.FULL_BUILD, builderID, null, monitor);
}
else {
project.build(IncrementalProjectBuilder.FULL_BUILD, monitor);
}
return Status.OK_STATUS;
}
catch (CoreException e) {
return new Status(Status.ERROR, CorePlugin.PLUGIN_ID, 1, "Error during build of project ["
+ project.getName() + "]", e);
}
}
};
if (rule != null) {
job.setRule(rule);
}
job.setPriority(Job.BUILD);
job.schedule();
}
}

View File

@@ -0,0 +1,35 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IStatus;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* @author Steffen Pingel
* @author Leo Dos Santos
* @author Christian Dupuis
*/
public class StatusHandler {
public static void log(IStatus status) {
CorePlugin plugin = CorePlugin.getDefault();
if (plugin!=null) {
ILog log = plugin.getLog();
if (log!=null) {
log.log(status);
}
}
}
}

View File

@@ -0,0 +1,191 @@
/*******************************************************************************
* Copyright (c) 2012, 2018 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.springsource.ide.eclipse.commons.core.process.StandardProcessRunner;
import org.springsource.ide.eclipse.commons.core.util.OsUtils;
/**
* @author Steffen Pingel
* @author Leo Dos Santos
* @author Christian Dupuis
* @author Kris De Volder
* @since 2.0
*/
public class ZipFileUtil {
/**
* This Zip utility doesn't know how to extract file permission correctly
* from zip files (does Java ZipEntry even provide this info? It seems
* not!).
* <p>
* To remedy this problem, clients can provide their own logic for setting
* permissions they may care about. A subclass of PermissionSetter is used
* to determine the permission setting logic.
*
* @author Kris De Volder
*
* @since 2.8
*/
public static abstract class PermissionSetter {
/**
* Called after a file was succesfully extracted from the zip archive.
* @throws IOException
*/
public abstract void fileUnzipped(ZipEntry entry, File entryFile) throws IOException;
/**
* A permission setter that does nothing.
*/
public static final PermissionSetter NULL = new PermissionSetter() {
@Override
public void fileUnzipped(ZipEntry entry, File entryFile) {
// Do nothing
}
};
/**
* Creates an executable permission setter based on a list of file
* extensions.
* <p>
* Any file ending with the extension will be made executable.
*/
public static PermissionSetter executableExtensions(final String... exts) {
if (OsUtils.isWindows()) {
// It may be ok to do nothing for windows? (note: not tested!)
return NULL;
}
else {
// Assume we are unix if not Windows (Mac OS X is ok)
return new PermissionSetter() {
@Override
public void fileUnzipped(ZipEntry entry, File entryFile) throws IOException {
for (String ext : exts) {
if (entryFile.getName().endsWith(ext)) {
// This only works with Java 6:
// entryFile.setExecutable(true);
// This only works on Unix:
StandardProcessRunner runner = new StandardProcessRunner();
try {
runner.run(new File("."), "chmod", "a+x", entryFile.toString());
}
catch (InterruptedException e) {
// Restore the interrupted status (see
// https://www.ibm.com/developerworks/java/library/j-jtp05236/index.html)
Thread.currentThread().interrupt();
}
return; // No sense making a file executable
// more than once.
}
}
}
};
}
}
}
private static final int BUFFER_SIZE = 512 * 1024;
public static void unzip(URL source, File targetFile, IProgressMonitor monitor) throws IOException {
unzip(source, targetFile, null, monitor);
}
public static void unzip(URL source, File targetFile, String prefix, IProgressMonitor monitor) throws IOException {
unzip(source, targetFile, prefix, PermissionSetter.NULL, monitor);
}
public static void unzip(URL source, File targetFile, String prefix, PermissionSetter permsetter,
IProgressMonitor monitor) throws IOException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
monitor.beginTask("Extracting " + source.getFile(), IProgressMonitor.UNKNOWN);
byte[] buffer = new byte[BUFFER_SIZE];
ZipInputStream zipIn = new ZipInputStream(source.openStream());
Path normalizedTargetFilePath = targetFile.toPath().normalize();
try {
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
String name = entry.getName();
if (prefix != null && name.startsWith(prefix)) {
name = name.substring(prefix.length());
if (name.length() > 1) {
// cut off separator
name = name.substring(1);
}
}
Policy.checkCancelled(monitor);
monitor.subTask(name);
File entryFile = new File(targetFile, name);
/*
* Ensure the outputdir + name doesn't leave the outputdir.
*/
if (!entryFile.toPath().normalize().startsWith(normalizedTargetFilePath)) {
throw new ZipException("The file " + name
+ " is trying to leave the target output directory of " + targetFile);
}
if (entry.isDirectory()) {
entryFile.mkdirs();
}
else {
entryFile.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(entryFile);
try {
int len;
while ((len = zipIn.read(buffer)) >= 0) {
Policy.checkCancelled(monitor);
out.write(buffer, 0, len);
}
}
finally {
out.close();
}
long modTime = entry.getTime();
if (modTime > 0) {
entryFile.setLastModified(modTime);
}
permsetter.fileUnzipped(entry, entryFile);
}
}
}
finally {
zipIn.close();
}
}
finally {
monitor.done();
}
}
public static void unzip(File zipFile, File unzipDir, IProgressMonitor monitor) throws MalformedURLException, IOException {
unzip(zipFile.toURI().toURL(), unzipDir, monitor);
}
}

View File

@@ -0,0 +1,186 @@
/*******************************************************************************
* Copyright (c) 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.preferences;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.service.prefs.BackingStoreException;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
public class GlobalPreferenceEnhancer {
// JDT ui constants
private static final String JDT_UI_BUNDLE_ID = "org.eclipse.jdt.ui";
// org.eclipse.jdt.ui.PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA
private static final String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA = "content_assist_autoactivation_triggers_java";
// org.eclipse.jdt.ui.PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY
private static final String CODEASSIST_AUTOACTIVATION_DELAY = "content_assist_autoactivation_delay";
// org.eclipse.jdt.ui.PreferenceConstants.EDITOR_ESCAPE_STRINGS
private static final String EDITOR_ESCAPE_STRINGS = "escape¥Strings";
// org.eclipse.jdt.ui.PreferenceConstants.EDITOR_SMART_PASTE
private static final String EDITOR_SMART_PASTE = "smartPaste";
// org.eclipse.jdt.ui.PreferenceConstants.EDITOR_SMART_TAB
private static final String EDITOR_SMART_TAB = "smart_tab";
// org.eclipse.jdt.ui.PreferenceConstants.EDITOR_SMART_BACKSPACE
private static final String EDITOR_SMART_BACKSPACE = "smart_backspace";
// org.eclipse.jdt.ui.PreferenceConstants.EDITOR_SMART_OPENING_BRACE
private static final String EDITOR_SMART_OPENING_BRACE = "smart_opening_brace";
// org.eclipse.jdt.ui.PreferenceConstants.EDITOR_SMART_SEMICOLON
private static final String EDITOR_SMART_SEMICOLON = "smart_semicolon";
// M2E constants
private static final String M2E_CORE_BUNDLE_ID = "org.eclipse.m2e.core";
// org.eclipse.m2e.core.internal.preferences.MavenPreferenceConstants.P_HIDE_FOLDERS_OF_NESTED_PROJECTS
private static final String P_HIDE_FOLDERS_OF_NESTED_PROJECTS = "eclipse.m2.hideFoldersOfNestedProjects";
// org.eclipse.m2e.core.internal.preferences.MavenPreferenceConstants.P_DEFAULT_POM_EDITOR_PAGE
private static final String P_DEFAULT_POM_EDITOR_PAGE = "eclipse.m2.defaultPomEditorPage";
// org.eclipse.m2e.core.internal.preferences.MavenPreferenceConstants.P_UPDATE_INDEXES
private static final String P_UPDATE_INDEXES = "eclipse.m2.updateIndexes";
// jdt core constatnts
private static final String JDT_CORE_BUNDLE_ID = "org.eclipse.jdt.core";
// org.eclipse.jdt.core.JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL
private static final String COMPILER_PB_NON_NLS_STRING_LITERAL = "org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral";
public void enhanceAllPreferences() {
enhanceM2EPreferences();
enhanceJDTPreferences();
}
public void enhanceM2EPreferences() {
IEclipsePreferences m2eCorePrefs = InstanceScope.INSTANCE.getNode(M2E_CORE_BUNDLE_ID);
if (m2eCorePrefs != null) {
m2eCorePrefs.putBoolean(P_HIDE_FOLDERS_OF_NESTED_PROJECTS, true);
m2eCorePrefs.putBoolean(P_DEFAULT_POM_EDITOR_PAGE, true);
m2eCorePrefs.putBoolean(P_UPDATE_INDEXES, false);
try {
m2eCorePrefs.flush();
}
catch (BackingStoreException e) {
handleException(e);
}
}
}
public void enhanceJDTPreferences() {
IEclipsePreferences jdtCorePrefs = InstanceScope.INSTANCE.getNode(JDT_CORE_BUNDLE_ID);
if (jdtCorePrefs != null) {
jdtCorePrefs.put(COMPILER_PB_NON_NLS_STRING_LITERAL, "ignore");
try {
jdtCorePrefs.flush();
}
catch (BackingStoreException e) {
handleException(e);
}
}
IEclipsePreferences jdtUiPrefs = InstanceScope.INSTANCE.getNode(JDT_UI_BUNDLE_ID);
if (jdtUiPrefs != null) {
jdtUiPrefs.putBoolean(EDITOR_SMART_PASTE, true);
jdtUiPrefs.putBoolean(EDITOR_ESCAPE_STRINGS, true);
jdtUiPrefs.putInt(CODEASSIST_AUTOACTIVATION_DELAY, 40);
//jdtUiPrefs.put(CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "_.abcdefghijklmnopqrstuvwxyz");
jdtUiPrefs.putBoolean(EDITOR_SMART_SEMICOLON, true);
jdtUiPrefs.putBoolean(EDITOR_SMART_OPENING_BRACE, true);
jdtUiPrefs.putBoolean(EDITOR_SMART_BACKSPACE, true);
jdtUiPrefs.putBoolean(EDITOR_SMART_TAB, true);
// org.eclipse.jdt.ui.PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS
// disable for now until we figure out the best things to include
// here;
// it is a semi-colon separateted list where each element looks like
// a static import statement
// jdtUiPrefs.put("content_assist_favorite_static_members",
// "org.eclipse.jdt.internal.ui.javaeditor.IJavaEditorActionConstants.*");
try {
jdtUiPrefs.flush();
}
catch (BackingStoreException e) {
handleException(e);
}
}
}
public void undoAll() {
undoJDTEnhance();
undoM2EEnhance();
}
public void undoJDTEnhance() {
IEclipsePreferences jdtCorePrefs = InstanceScope.INSTANCE.getNode(JDT_CORE_BUNDLE_ID);
if (jdtCorePrefs != null) {
jdtCorePrefs.remove(COMPILER_PB_NON_NLS_STRING_LITERAL);
try {
jdtCorePrefs.flush();
}
catch (BackingStoreException e) {
handleException(e);
}
}
IEclipsePreferences jdtUiPrefs = InstanceScope.INSTANCE.getNode(JDT_UI_BUNDLE_ID);
if (jdtUiPrefs != null) {
jdtUiPrefs.remove(EDITOR_SMART_PASTE);
jdtUiPrefs.remove(EDITOR_ESCAPE_STRINGS);
jdtUiPrefs.remove(CODEASSIST_AUTOACTIVATION_DELAY);
jdtUiPrefs.remove(CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA);
jdtUiPrefs.remove(EDITOR_SMART_SEMICOLON);
jdtUiPrefs.remove(EDITOR_SMART_OPENING_BRACE);
jdtUiPrefs.remove(EDITOR_SMART_BACKSPACE);
jdtUiPrefs.remove(EDITOR_SMART_TAB);
try {
jdtUiPrefs.flush();
}
catch (BackingStoreException e) {
handleException(e);
}
}
}
public void undoM2EEnhance() {
IEclipsePreferences m2eCorePrefs = InstanceScope.INSTANCE.getNode(M2E_CORE_BUNDLE_ID);
if (m2eCorePrefs != null) {
m2eCorePrefs.remove(P_HIDE_FOLDERS_OF_NESTED_PROJECTS);
m2eCorePrefs.remove(P_DEFAULT_POM_EDITOR_PAGE);
m2eCorePrefs.remove(P_UPDATE_INDEXES);
try {
m2eCorePrefs.flush();
}
catch (BackingStoreException e) {
handleException(e);
}
}
}
private void handleException(BackingStoreException e) {
CorePlugin.getDefault().getLog()
.log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, e.getLocalizedMessage(), e));
}
}

View File

@@ -0,0 +1,181 @@
/*******************************************************************************
* Copyright (c) 2012, 2020 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.preferences;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* An instance of this class provides a mechanism to retrieve String properties.
* This is similar to a Java system properties. However it has support for reading these
* properties from a fixed url. This allows us to change the properties after release.
* <p>
* Properties in this class can come from several different sources, listed here in
* decreasing order of priority:
*
* 1) Java System properties (set via -Dmy.prop.name=value) in STS.ini
* (properties set this way override anything else).
* 2) default values hard-coded in this class.
* (used only if property was not set via either 1 or 2).
*
* @since 3.4.M1
* @since 3.8.4 : no more reading props from url. Only hard-coded or system props used (too many
* issues with the network accesses blocking UI thread.)
*
* @author Kris De Volder
*/
public class StsProperties {
//Note: there is also a class called 'ResourceProvider'.. which reads various properties
// from eclipse extension points. This is different because the STSProperties themselves
// are read from an external url.
//The ResourceProvider only allows properties to defined by extensions contained in plugins
// installed into the Ecliple platform.
/**
* This class is a singleton. This holds the instance once created.
*/
private static StsProperties instance = null;
public static StsProperties getInstance(IProgressMonitor mon) {
if (instance==null) {
StsProperties newInstance = new StsProperties(mon);
instance = newInstance;
}
return instance;
}
private final Properties props;
private StsProperties(IProgressMonitor mon) {
mon.beginTask("Read Sts Properties", 11);
try {
props = createProperties();
} finally {
mon.done();
}
}
protected Properties createProperties() {
Properties props = new Properties();
// Default properties (guarantees certain properties have a value no
// matter what).
props.put("spring.site.url", "https://spring.io");
props.put("spring.initializr.json.url", "https://start.spring.io");
//Urls used in the dashboard. For each XXX.url=... property, if
// - XXX.url.label is defined that label will be used for the corresponding
// dashboard tab instead of the html page title (title tends to be too long).
// - XXX.url.external is defined that url will always be openened in an external browser.
//Docs
props.put("spring.docs.url", "https://spring.io/docs");
props.put("spring.docs.url.label", "Spring Docs");
props.put("spring.docs.url.external", "false");
//Blog
props.put("spring.blog.url", "https://spring.io/blog");
props.put("spring.blog.url.label", "Blog");
props.put("spring.blog.url.external", "false");
//Tracker:
props.put("sts.tracker.url", "https://github.com/spring-projects/spring-ide/issues");
props.put("sts.tracker.url.label", "Issues");
props.put("sts.tracker.url.external", "true");
//New and Noteworthy
props.put("sts.nan.url", "https://static.springsource.org/sts/nan/latest/NewAndNoteworthy.html");
props.put("sts.nan.url.label", "New and Noteworthy");
props.put("sts.nan.url.external", "false");
//Forum:
props.put("sts.forum.url", "https://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite");
props.put("sts.forum.url.label", "Forum");
props.put("sts.forum.url.external", "false");
//Guides
props.put("spring.guides.url", "https://spring.io/guides");
props.put("spring.guides.url.label", "Guides");
props.put("spring.guides.url.external", "true");
//Spring boot runtime
props.put("spring.boot.install.url", "https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.1.15.RELEASE/spring-boot-cli-2.1.15.RELEASE-bin.zip");
//Discovery url for spring reference app
props.put("spring.reference.app.discovery.url", "https://raw.github.com/kdvolder/spring-reference-apps-meta/master/reference-apps.json");
//Url for webservice that generates typegraph for spring boot jar type content assist
props.put("spring.boot.typegraph.url", "https://aetherial.cfapps.io/boot/typegraph");
//Default version of spring boot, assumed when we need a version but can't determine it from the classpath of the project.
//Typically this should point to the latest version of spring-boot (the one used by spring-initialzr app).
props.put("spring.boot.default.version", "2.1.15.RELEASE");
props.put("spring.boot.cloud.default.version", "2.1.0.RELEASE");
return props;
}
/**
* Procudes names of properties that have explicitly been set, either from properties file
* or by the explicitly provided defaults. More precisely this does not return
* properties simply inherited from Java system properties.
*/
public Collection<String> getExplicitProperties() {
ArrayList<String> keys = new ArrayList<String>();
for (Object string : props.keySet()) {
if (string instanceof String) {
keys.add((String) string);
}
}
return keys;
}
public String get(String key) {
String value = System.getProperty(key);
if (value == null) {
value = props.getProperty(key);
}
return value;
}
public boolean get(String key, boolean deflt) {
String value = get(key);
if (value!=null) {
return Boolean.valueOf(value);
}
return deflt;
}
public static StsProperties getInstance() {
return getInstance(new NullProgressMonitor());
}
public URL url(String prop) {
String s = get(prop);
try {
if (s!=null) {
return new URL(get(prop));
}
} catch (Exception e) {
CorePlugin.log(e);
}
return null;
}
}

View File

@@ -0,0 +1,22 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.process;
/**
* @author Christian Dupuis
* @author Steffen Pingel
* @since 2.5.2
*/
public interface OutputWriter {
void write(String line);
}

View File

@@ -0,0 +1,25 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.process;
import java.io.File;
import java.io.IOException;
/**
* @author Christian Dupuis
* @author Steffen Pingel
* @since 2.5.2
*/
public interface ProcessRunner {
int run(File workingDir, String... command) throws IOException, InterruptedException;
}

View File

@@ -0,0 +1,110 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.process;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;
/**
* @author Christian Dupuis
* @author Steffen Pingel
* @since 2.5.2
*/
public final class StandardProcessRunner implements ProcessRunner {
private static final String[] ENVIRONMENT = new String[] {
String.format("JAVA_HOME=%s", System.getProperty("java.home")),
String.format("PATH=%s", System.getenv("PATH")),
String.format("USERDOMAIN=%s", System.getenv("USERDOMAIN")),
String.format("USERNAME=%s", System.getenv("USERNAME")),
String.format("USERPROFILE=%s", System.getenv("USERPROFILE")) };
private final OutputWriter[] standardOutputWriters;
private final OutputWriter[] standardErrorWriters;
public StandardProcessRunner() {
this(new OutputWriter[0], new OutputWriter[0]);
}
public StandardProcessRunner(OutputWriter standardOutputWriter, OutputWriter standardErrorWriter) {
this(new OutputWriter[] { standardOutputWriter }, new OutputWriter[] { standardErrorWriter });
}
public StandardProcessRunner(OutputWriter[] standardOutputWriters, OutputWriter[] standardErrorWriters) {
this.standardOutputWriters = standardOutputWriters;
this.standardErrorWriters = standardErrorWriters;
}
public int run(File workingDir, String... command) throws IOException, InterruptedException {
Process process;
if (command.length == 1) {
process = Runtime.getRuntime().exec(command[0], ENVIRONMENT, workingDir);
}
else {
process = Runtime.getRuntime().exec(command, ENVIRONMENT, workingDir);
}
CountDownLatch latch = new CountDownLatch(2);
new Thread(new StreamReader(process.getInputStream(), this.standardOutputWriters, latch)).start();
new Thread(new StreamReader(process.getErrorStream(), this.standardErrorWriters, latch)).start();
int returnCode = process.waitFor();
latch.await();
return returnCode;
}
private static final class StreamReader implements Runnable {
private final BufferedReader input;
private final OutputWriter[] outputs;
private final CountDownLatch latch;
public StreamReader(InputStream input, OutputWriter[] outputs, CountDownLatch latch) {
this.input = new BufferedReader(new InputStreamReader(input));
this.outputs = outputs;
this.latch = latch;
}
public void run() {
try {
String line = null;
while ((line = this.input.readLine()) != null) {
for (OutputWriter output : this.outputs) {
output.write(line);
}
}
}
catch (IOException e) {
}
finally {
try {
if (this.input != null) {
this.input.close();
}
}
catch (IOException e) {
}
finally {
this.latch.countDown();
}
}
}
}
}

View File

@@ -0,0 +1,24 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.process;
/**
* @author Christian Dupuis
* @author Steffen Pingel
* @since 2.5.2
*/
public class SystemErrOutputWriter implements OutputWriter {
public void write(String line) {
System.err.println(line);
}
}

View File

@@ -0,0 +1,24 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.process;
/**
* @author Christian Dupuis
* @author Steffen Pingel
* @since 2.5.2
*/
public final class SystemOutOutputWriter implements OutputWriter {
public void write(String line) {
System.out.println(line);
}
}

View File

@@ -0,0 +1,29 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
/**
* An instance of this provides a way to store and retrieve
* properties. The properties are persisted somehow.
* <p>
* This interface is deliberately kept very sparse so as to be
* 'easy' to implement. Its an interface meant for implementors.
* <p>
* If you are a client you can an wrap instance of this interface
* into a {@link PropertyStoreApi} for a more convenient api
* with more operations.
*
* @author Kris De Volder
*/
public interface IPropertyStore {
String get(String key);
void put(String key, String value) throws Exception;
}

View File

@@ -0,0 +1,22 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
/**
* An instance of this provides a way to store and retrieve
* properties associated with some 'scope' object of type T.
* <p>
* The properties are persisted somehow.
*/
public interface IScopedPropertyStore<T> {
String get(T scope, String key);
void put(T scope, String key, String value) throws Exception;
}

View File

@@ -0,0 +1,33 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
import java.util.HashMap;
import java.util.Map;
/**
* @author Kris De Volder
*/
public class InMemoryPropertyStore implements IPropertyStore {
private Map<String, String> props = new HashMap<>();
@Override
public synchronized String get(String key) {
return props.get(key);
}
@Override
public synchronized void put(String key, String value) throws Exception {
props.put(key, value);
}
}

View File

@@ -0,0 +1,40 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
/**
* An abstract base class to create {@link IScopedPropertyStore} that uses
* {@link IEclipsePreferences} to persist properties.
*/
public abstract class PreferenceBasedStore<T> implements IScopedPropertyStore<T> {
protected abstract IEclipsePreferences createPrefs(T element);
@Override
public String get(T p, String k) {
IEclipsePreferences prefs = createPrefs(p);
return prefs.get(k, null);
}
@Override
public void put(T element, String key, String value) throws Exception {
IEclipsePreferences prefs = createPrefs(element);
if (value==null) {
prefs.remove(key);
} else {
prefs.put(key, value);
}
prefs.flush();
}
}

View File

@@ -0,0 +1,194 @@
/*******************************************************************************
* Copyright (c) 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclEntryType;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Properties;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.springsource.ide.eclipse.commons.core.util.OsUtils;
import org.springsource.ide.eclipse.commons.livexp.util.Log;
/**
* Implementation of IPropertyStore backed by a .properties file.
* The properties file is 'private'. I.e. it is created such that only
* the onwer of the file is allowed access to it.
*/
public class PropertyFileStore implements IPropertyStore {
final private File file;
final private Properties props = new Properties();
Job flushProperties = new Job("Save private properties") {
boolean errorLogged = false;
{
setSystem(true);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
createFileIfNeeded(file);
try (OutputStream out = new FileOutputStream(file)) {
props.store(out, "Private properties");
}
} catch (IOException e) {
if (!errorLogged) {
errorLogged = true; //complaining once about failure to store props is enough!
Log.log(e);
}
}
return Status.OK_STATUS;
}
};
protected void createFileIfNeeded(File f) throws IOException {
if (!f.exists()) {
createFile(f);
setPermissions(f);
}
}
protected void setPermissions(File f) throws IOException {
if (OsUtils.isWindows()) {
setWindowsPerissions(f);
} else {
setUnixPermissions(f);
}
}
protected void setWindowsPerissions(File f) throws IOException {
Path file = f.toPath();
AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setPermissions( EnumSet.allOf(AclEntryPermission.class));
// This was here before but it seems not enough to actually allow reading the file:
// builder.setPermissions( EnumSet.of(
// AclEntryPermission.READ_DATA,
// AclEntryPermission.WRITE_DATA,
// AclEntryPermission.APPEND_DATA,
// AclEntryPermission.READ_ACL,
// AclEntryPermission.WRITE_ACL,
// AclEntryPermission.READ_ATTRIBUTES,
// AclEntryPermission.WRITE_ATTRIBUTES,
// AclEntryPermission.READ_NAMED_ATTRS,
// AclEntryPermission.WRITE_NAMED_ATTRS,
// AclEntryPermission.DELETE
// ));
builder.setPrincipal(user);
builder.setType(AclEntryType.ALLOW);
aclAttr.setAcl(Collections.singletonList(builder.build()));
}
protected void setUnixPermissions(File f) throws IOException {
Files.setPosixFilePermissions(file.toPath(), EnumSet.of(
PosixFilePermission.OWNER_READ,
PosixFilePermission.OWNER_WRITE)
);
}
protected void createFile(File f) throws IOException {
if (f.getParentFile() != null) {
f.getParentFile().mkdirs();
}
f.createNewFile();
}
public PropertyFileStore(File file) {
this.file = file;
try {
if (file.exists()) {
try (InputStream in = new FileInputStream(file)) {
props.load(in);
}
}
} catch (IOException e) {
//Log and move on. This is not 'critical'. Maybe the file is corrupt and will be overwritten
// or something else is wrong and we won't be able to persist props. But at least
//props will be working in memory.
Log.log(e);
}
}
@Override
public synchronized String get(String key) {
return props.getProperty(key);
}
@Override
public void put(String key, String value) throws Exception {
Object oldValue = nullPut(key, value);
if (!Objects.equals(oldValue, value)) {
flushProperties.schedule();
}
}
private Object nullPut(String key, String value) {
if (value==null) {
return props.remove(key);
} else {
return props.put(key, value);
}
}
public boolean isEmpty() {
return props.isEmpty();
}
/**
* Blocks the current thread until all dirty data has been written to disk. This meant for testing purposes.
* E.g. a test that wants to check contents of the backing file after performing ops on the store.
*/
public void sync() throws InterruptedException {
flushProperties.join();
}
/**
* Convert the contents currently in the store into a Map. Mainly meant for testing purposes to easily compare
* the map contents to expected contents. Not thread safe. Test code is expected to call this at a time
* when the work on the map is 'done'.
*/
public Map<String,String> asMap() {
Map<String, String> builder = new HashMap<>();
for (Entry<Object, Object> e : props.entrySet()) {
builder.put((String)e.getKey(), (String)e.getValue());
}
return Collections.unmodifiableMap(builder);
}
}

View File

@@ -0,0 +1,104 @@
/*******************************************************************************
* Copyright (c) 2015, 2016 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
import org.springsource.ide.eclipse.commons.core.util.StringUtil;
import org.springsource.ide.eclipse.commons.frameworks.core.util.ArrayEncoder;
import org.springsource.ide.eclipse.commons.livexp.util.Log;
/**
* This is a 'wrapper' for a basic 'IPropertyStore' instance that is used as
* the 'backing store' to persist metadata.
* <p>
* The 'PropertyStoreApi' implements additional convenience methods that encode
* a variety of data types for storing into the backing store.
* <p>
* The idea is that leaves us free to add lots of convenience methods here
* without making the basic IPropertyStore interface bigger and harder to implement.
* <p>
* In other words the responsibility of 'PropertyStoreApi' is 'encoding' and
* 'decoding' data into a storeable format. But it is not concerned with
* how/where this encoded data is persisted.
* <p>
* IPropertyStore's, on the other hand is concerned with how / where the data
* is stored but doesn't deal with encoding data (beyond basic key-value
* pairs).
*
* @author Kris De Volder
*/
public class PropertyStoreApi {
private final IPropertyStore backingStore;
public PropertyStoreApi(IPropertyStore backingStore) {
this.backingStore = backingStore;
}
public String get(String key) {
return backingStore.get(key);
}
public void put(String key, String value) throws Exception {
backingStore.put(key, value);
}
public void put(String key, String[] values) throws Exception {
if (values==null) {
backingStore.put(key, null);
} else {
backingStore.put(key, ArrayEncoder.encode(values));
}
}
public String[] get(String key, String[] dflt) throws Exception {
String encoded = backingStore.get(key);
if (encoded==null) {
return dflt;
} else {
return ArrayEncoder.decode(encoded);
}
}
public boolean get(String key, boolean dflt) {
String string = get(key);
if (StringUtil.hasText(string)) {
try {
return Boolean.parseBoolean(string);
} catch (Exception e) {
Log.log(e);
}
}
return dflt;
}
public int get(String key, int dflt) {
String string = get(key);
if (StringUtil.hasText(string)) {
try {
return Integer.parseInt(string);
} catch (Exception e) {
Log.log(e);
}
}
return dflt;
}
public void put(String id, boolean enable) throws Exception {
put(id, Boolean.toString(enable));
}
public IPropertyStore getBackingStore() {
return backingStore;
}
}

View File

@@ -0,0 +1,133 @@
/*******************************************************************************
* Copyright (c) 2015, 2016 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.pstore;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jface.preference.IPreferenceStore;
import org.springsource.ide.eclipse.commons.livexp.util.Log;
/**
* Provides static helper methods to create IPropertyStore instances,
*/
public class PropertyStores {
private static final String DEFAULT_QUALIFIER = "microservice-metadata";
public static IScopedPropertyStore<IProject> createForProjects() {
return createForProjects(DEFAULT_QUALIFIER);
}
public static IScopedPropertyStore<IProject> createForProjects(String qualifier) {
return new PreferenceBasedStore<IProject>() {
@Override
protected IEclipsePreferences createPrefs(IProject p) {
IEclipsePreferences prefs = new ProjectScope(p).getNode(qualifier);
return prefs;
}
};
}
public static <S> IPropertyStore createForScope(final S scope, final IScopedPropertyStore<S> scopedStore) {
Assert.isNotNull(scopedStore);
return new IPropertyStore() {
@Override
public void put(String key, String value) throws Exception {
scopedStore.put(scope, key, value);
}
@Override
public String get(String key) {
return scopedStore.get(scope, key);
}
};
}
public static PropertyStoreApi createApi(IPropertyStore backingStore) {
return new PropertyStoreApi(backingStore);
}
public static IPropertyStore createSubStore(final String subStoreId, final IPropertyStore backingStore) {
return new IPropertyStore() {
private String subkey(String key) {
return subStoreId+":"+key;
}
@Override
public void put(String key, String value) throws Exception {
backingStore.put(subkey(key), value);
}
@Override
public String get(String key) {
return backingStore.get(subkey(key));
}
};
}
public static IPropertyStore createFor(final ILaunchConfiguration launchConf) {
return new IPropertyStore() {
private static final String prefix = "boot.dash.";
private ILaunchConfiguration conf = launchConf;
@Override
public synchronized void put(String key, String value) throws Exception {
ILaunchConfigurationWorkingCopy wc = conf.getWorkingCopy();
wc.setAttribute(prefix+key, value);
wc.doSave();
}
@Override
public String get(String key) {
try {
return conf.getAttribute(prefix+key,(String)null);
} catch (Exception e) {
Log.log(e);
};
return null;
}
};
}
public static IPropertyStore backedBy(final IPreferenceStore preferenceStore) {
return new IPropertyStore() {
@Override
public void put(String key, String value) throws Exception {
if (value==null) {
preferenceStore.setToDefault(key);
} else {
preferenceStore.setValue(key, value);
}
}
@Override
public String get(String key) {
if (preferenceStore.contains(key)) {
return preferenceStore.getString(key);
}
return null;
}
};
}
public static IPropertyStore createPrivateStore(IPath append) {
return new PropertyFileStore(append.toFile());
}
}

View File

@@ -0,0 +1,155 @@
/*******************************************************************************
* Copyright (c) 2012, 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.templates;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.springsource.ide.eclipse.commons.core.FileUtil;
/**
* @author Terry Denney
* @author Leo Dos Santos
* @author Christian Dupuis
* @author Kaitlin Duck Sherwood
* @author Kris De Volder (Add recursion over directories).
*/
public class TemplateProcessor {
private static Logger logger = Logger.getLogger(TemplateProcessor.class);
protected Map<String, String> replacementContext = new HashMap<String, String>();
// protected SpringVersionProcessor springProcessor;
public TemplateProcessor(Map<String, String> replacementContext) {
this.replacementContext = replacementContext;
}
// public TemplateProcessor(Map<String, String> replacementContext, SpringVersion springVersion) {
// this.replacementContext = replacementContext;
//
// if (springVersion != null && !springVersion.equals(SpringVersion.DEFAULT)) {
// this.springProcessor = new SpringVersionProcessor(springVersion.getVersion());
// }
// }
public void process(File source, File target) throws IOException {
if (FileUtil.isBinaryFile(source)) {
logger.debug("Copying binary file " + source);
FileUtil.copy(source, target);
} else if (source.isDirectory()) {
try {
FileUtil.copyDirectory(source, target, new NullProgressMonitor());
}
catch (CoreException e) {
logger.error("Problem while attempting to copy template directory", e);
}
String[] names = source.list();
if (names!=null) {
for (String childName : names) {
File childSource = new File(source, childName);
File childTarget = new File(target, childName);
process(childSource, childTarget);
}
}
}
else {
logger.debug("Template processing text file " + source);
process(new FileReader(source), new FileWriter(target));
}
}
public void process(Reader reader, Writer writer) throws IOException {
BufferedReader bufferedReader = new BufferedReader(reader);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
break;
}
line = replaceTokens(line);
bufferedWriter.write(line);
bufferedWriter.write('\n');
}
bufferedWriter.flush();
}
public String replaceTokens(String input) {
String topLevelPackageStr = replacementContext.get("||top-level-package||");
if (topLevelPackageStr != null) {
if (topLevelPackageStr.startsWith("&&")) {
topLevelPackageStr = topLevelPackageStr.substring(2);
}
topLevelPackageStr = topLevelPackageStr.replaceAll("&&", ".");
String userTopLevelPackageStr = replacementContext.get("||user-top-level-package||");
if (userTopLevelPackageStr.startsWith("&&")) {
userTopLevelPackageStr = userTopLevelPackageStr.substring(2);
}
if (input.contains(topLevelPackageStr) && userTopLevelPackageStr != null) {
int index = input.indexOf(topLevelPackageStr);
String newInput = input.substring(0, index) + userTopLevelPackageStr.replaceAll("&&", ".");
if (index + topLevelPackageStr.length() < input.length()) {
newInput += input.substring(index + topLevelPackageStr.length());
}
input = newInput;
}
}
for (String token : replacementContext.keySet()) {
String replacement = replacementContext.get(token);
input = input.replace(token, replacement);
}
if (input.indexOf("my") >= 0) {
logger.warn("May have failed to replace token " + input);
}
return input;
}
public String replacePathForDirectory(String path, char separator) {
String originalTopLevelPackageStr = replacementContext.get("||top-level-package||");
if (originalTopLevelPackageStr != null) {
originalTopLevelPackageStr = originalTopLevelPackageStr.replaceAll("&&", "\\" + separator);
String userTopLevelPackageStr = replacementContext.get("||user-top-level-package||");
if (path.contains(originalTopLevelPackageStr) && userTopLevelPackageStr != null) {
int index = path.indexOf(originalTopLevelPackageStr);
String replacementString = userTopLevelPackageStr.replaceAll("&&", "\\" + separator);
String newPath = path.substring(0, index) + replacementString;
if (index + 1 + originalTopLevelPackageStr.length() < path.length()) {
newPath += path.substring(index + originalTopLevelPackageStr.length());
}
return newPath;
}
}
return null;
}
}

View File

@@ -0,0 +1,561 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.ide.eclipse.commons.core.util;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
/**
* Miscellaneous collection utility methods.
* Mainly for internal use within the framework.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Arjen Poutsma
* @since 1.1.3
*/
public abstract class CollectionUtils {
// /**
// * Return {@code true} if the supplied Collection is {@code null} or empty.
// * Otherwise, return {@code false}.
// * @param collection the Collection to check
// * @return whether the given Collection is empty
// */
// public static boolean isEmpty(@Nullable Collection<?> collection) {
// return (collection == null || collection.isEmpty());
// }
//
// /**
// * Return {@code true} if the supplied Map is {@code null} or empty.
// * Otherwise, return {@code false}.
// * @param map the Map to check
// * @return whether the given Map is empty
// */
// public static boolean isEmpty(@Nullable Map<?, ?> map) {
// return (map == null || map.isEmpty());
// }
//
// /**
// * Convert the supplied array into a List. A primitive array gets converted
// * into a List of the appropriate wrapper type.
// * <p><b>NOTE:</b> Generally prefer the standard {@link Arrays#asList} method.
// * This {@code arrayToList} method is just meant to deal with an incoming Object
// * value that might be an {@code Object[]} or a primitive array at runtime.
// * <p>A {@code null} source value will be converted to an empty List.
// * @param source the (potentially primitive) array
// * @return the converted List result
// * @see ObjectUtils#toObjectArray(Object)
// * @see Arrays#asList(Object[])
// */
// @SuppressWarnings("rawtypes")
// public static List arrayToList(@Nullable Object source) {
// return Arrays.asList(ObjectUtils.toObjectArray(source));
// }
//
// /**
// * Merge the given array into the given Collection.
// * @param array the array to merge (may be {@code null})
// * @param collection the target Collection to merge the array into
// */
// @SuppressWarnings("unchecked")
// public static <E> void mergeArrayIntoCollection(@Nullable Object array, Collection<E> collection) {
// Object[] arr = ObjectUtils.toObjectArray(array);
// for (Object elem : arr) {
// collection.add((E) elem);
// }
// }
//
/**
* Merge the given Properties instance into the given Map,
* copying all properties (key-value pairs) over.
* <p>Uses {@code Properties.propertyNames()} to even catch
* default properties linked into the original Properties instance.
* @param props the Properties instance to merge (may be {@code null})
* @param map the target Map to merge the properties into
*/
@SuppressWarnings("unchecked")
public static <K, V> void mergePropertiesIntoMap(/*@Nullable*/ Properties props, Map<K, V> map) {
if (props != null) {
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
Object value = props.get(key);
if (value == null) {
// Allow for defaults fallback or potentially overridden accessor...
value = props.getProperty(key);
}
map.put((K) key, (V) value);
}
}
}
//
//
// /**
// * Check whether the given Iterator contains the given element.
// * @param iterator the Iterator to check
// * @param element the element to look for
// * @return {@code true} if found, {@code false} otherwise
// */
// public static boolean contains(@Nullable Iterator<?> iterator, Object element) {
// if (iterator != null) {
// while (iterator.hasNext()) {
// Object candidate = iterator.next();
// if (ObjectUtils.nullSafeEquals(candidate, element)) {
// return true;
// }
// }
// }
// return false;
// }
//
// /**
// * Check whether the given Enumeration contains the given element.
// * @param enumeration the Enumeration to check
// * @param element the element to look for
// * @return {@code true} if found, {@code false} otherwise
// */
// public static boolean contains(@Nullable Enumeration<?> enumeration, Object element) {
// if (enumeration != null) {
// while (enumeration.hasMoreElements()) {
// Object candidate = enumeration.nextElement();
// if (ObjectUtils.nullSafeEquals(candidate, element)) {
// return true;
// }
// }
// }
// return false;
// }
//
// /**
// * Check whether the given Collection contains the given element instance.
// * <p>Enforces the given instance to be present, rather than returning
// * {@code true} for an equal element as well.
// * @param collection the Collection to check
// * @param element the element to look for
// * @return {@code true} if found, {@code false} otherwise
// */
// public static boolean containsInstance(@Nullable Collection<?> collection, Object element) {
// if (collection != null) {
// for (Object candidate : collection) {
// if (candidate == element) {
// return true;
// }
// }
// }
// return false;
// }
//
// /**
// * Return {@code true} if any element in '{@code candidates}' is
// * contained in '{@code source}'; otherwise returns {@code false}.
// * @param source the source Collection
// * @param candidates the candidates to search for
// * @return whether any of the candidates has been found
// */
// public static boolean containsAny(Collection<?> source, Collection<?> candidates) {
// if (isEmpty(source) || isEmpty(candidates)) {
// return false;
// }
// for (Object candidate : candidates) {
// if (source.contains(candidate)) {
// return true;
// }
// }
// return false;
// }
//
// /**
// * Return the first element in '{@code candidates}' that is contained in
// * '{@code source}'. If no element in '{@code candidates}' is present in
// * '{@code source}' returns {@code null}. Iteration order is
// * {@link Collection} implementation specific.
// * @param source the source Collection
// * @param candidates the candidates to search for
// * @return the first present object, or {@code null} if not found
// */
// @SuppressWarnings("unchecked")
// @Nullable
// public static <E> E findFirstMatch(Collection<?> source, Collection<E> candidates) {
// if (isEmpty(source) || isEmpty(candidates)) {
// return null;
// }
// for (Object candidate : candidates) {
// if (source.contains(candidate)) {
// return (E) candidate;
// }
// }
// return null;
// }
//
// /**
// * Find a single value of the given type in the given Collection.
// * @param collection the Collection to search
// * @param type the type to look for
// * @return a value of the given type found if there is a clear match,
// * or {@code null} if none or more than one such value found
// */
// @SuppressWarnings("unchecked")
// @Nullable
// public static <T> T findValueOfType(Collection<?> collection, @Nullable Class<T> type) {
// if (isEmpty(collection)) {
// return null;
// }
// T value = null;
// for (Object element : collection) {
// if (type == null || type.isInstance(element)) {
// if (value != null) {
// // More than one value found... no clear single value.
// return null;
// }
// value = (T) element;
// }
// }
// return value;
// }
//
// /**
// * Find a single value of one of the given types in the given Collection:
// * searching the Collection for a value of the first type, then
// * searching for a value of the second type, etc.
// * @param collection the collection to search
// * @param types the types to look for, in prioritized order
// * @return a value of one of the given types found if there is a clear match,
// * or {@code null} if none or more than one such value found
// */
// @Nullable
// public static Object findValueOfType(Collection<?> collection, Class<?>[] types) {
// if (isEmpty(collection) || ObjectUtils.isEmpty(types)) {
// return null;
// }
// for (Class<?> type : types) {
// Object value = findValueOfType(collection, type);
// if (value != null) {
// return value;
// }
// }
// return null;
// }
//
// /**
// * Determine whether the given Collection only contains a single unique object.
// * @param collection the Collection to check
// * @return {@code true} if the collection contains a single reference or
// * multiple references to the same instance, {@code false} otherwise
// */
// public static boolean hasUniqueObject(Collection<?> collection) {
// if (isEmpty(collection)) {
// return false;
// }
// boolean hasCandidate = false;
// Object candidate = null;
// for (Object elem : collection) {
// if (!hasCandidate) {
// hasCandidate = true;
// candidate = elem;
// }
// else if (candidate != elem) {
// return false;
// }
// }
// return true;
// }
//
// /**
// * Find the common element type of the given Collection, if any.
// * @param collection the Collection to check
// * @return the common element type, or {@code null} if no clear
// * common type has been found (or the collection was empty)
// */
// @Nullable
// public static Class<?> findCommonElementType(Collection<?> collection) {
// if (isEmpty(collection)) {
// return null;
// }
// Class<?> candidate = null;
// for (Object val : collection) {
// if (val != null) {
// if (candidate == null) {
// candidate = val.getClass();
// }
// else if (candidate != val.getClass()) {
// return null;
// }
// }
// }
// return candidate;
// }
//
// /**
// * Retrieve the last element of the given Set, using {@link SortedSet#last()}
// * or otherwise iterating over all elements (assuming a linked set).
// * @param set the Set to check (may be {@code null} or empty)
// * @return the last element, or {@code null} if none
// * @since 5.0.3
// * @see SortedSet
// * @see LinkedHashMap#keySet()
// * @see java.util.LinkedHashSet
// */
// @Nullable
// public static <T> T lastElement(@Nullable Set<T> set) {
// if (isEmpty(set)) {
// return null;
// }
// if (set instanceof SortedSet) {
// return ((SortedSet<T>) set).last();
// }
//
// // Full iteration necessary...
// Iterator<T> it = set.iterator();
// T last = null;
// while (it.hasNext()) {
// last = it.next();
// }
// return last;
// }
//
// /**
// * Retrieve the last element of the given List, accessing the highest index.
// * @param list the List to check (may be {@code null} or empty)
// * @return the last element, or {@code null} if none
// * @since 5.0.3
// */
// @Nullable
// public static <T> T lastElement(@Nullable List<T> list) {
// if (isEmpty(list)) {
// return null;
// }
// return list.get(list.size() - 1);
// }
//
// /**
// * Marshal the elements from the given enumeration into an array of the given type.
// * Enumeration elements must be assignable to the type of the given array. The array
// * returned will be a different instance than the array given.
// */
// public static <A, E extends A> A[] toArray(Enumeration<E> enumeration, A[] array) {
// ArrayList<A> elements = new ArrayList<>();
// while (enumeration.hasMoreElements()) {
// elements.add(enumeration.nextElement());
// }
// return elements.toArray(array);
// }
//
// /**
// * Adapt an {@link Enumeration} to an {@link Iterator}.
// * @param enumeration the original {@code Enumeration}
// * @return the adapted {@code Iterator}
// */
// public static <E> Iterator<E> toIterator(@Nullable Enumeration<E> enumeration) {
// return (enumeration != null ? new EnumerationIterator<>(enumeration) : Collections.emptyIterator());
// }
//
// /**
// * Adapt a {@code Map<K, List<V>>} to an {@code MultiValueMap<K, V>}.
// * @param map the original map
// * @return the multi-value map
// * @since 3.1
// */
// public static <K, V> MultiValueMap<K, V> toMultiValueMap(Map<K, List<V>> map) {
// return new MultiValueMapAdapter<>(map);
// }
//
// /**
// * Return an unmodifiable view of the specified multi-value map.
// * @param map the map for which an unmodifiable view is to be returned.
// * @return an unmodifiable view of the specified multi-value map.
// * @since 3.1
// */
// @SuppressWarnings("unchecked")
// public static <K, V> MultiValueMap<K, V> unmodifiableMultiValueMap(MultiValueMap<? extends K, ? extends V> map) {
// Assert.notNull(map, "'map' must not be null");
// Map<K, List<V>> result = new LinkedHashMap<>(map.size());
// map.forEach((key, value) -> {
// List<? extends V> values = Collections.unmodifiableList(value);
// result.put(key, (List<V>) values);
// });
// Map<K, List<V>> unmodifiableMap = Collections.unmodifiableMap(result);
// return toMultiValueMap(unmodifiableMap);
// }
//
//
// /**
// * Iterator wrapping an Enumeration.
// */
// private static class EnumerationIterator<E> implements Iterator<E> {
//
// private final Enumeration<E> enumeration;
//
// public EnumerationIterator(Enumeration<E> enumeration) {
// this.enumeration = enumeration;
// }
//
// @Override
// public boolean hasNext() {
// return this.enumeration.hasMoreElements();
// }
//
// @Override
// public E next() {
// return this.enumeration.nextElement();
// }
//
// @Override
// public void remove() throws UnsupportedOperationException {
// throw new UnsupportedOperationException("Not supported");
// }
// }
//
//
// /**
// * Adapts a Map to the MultiValueMap contract.
// */
// @SuppressWarnings("serial")
// private static class MultiValueMapAdapter<K, V> implements MultiValueMap<K, V>, Serializable {
//
// private final Map<K, List<V>> map;
//
// public MultiValueMapAdapter(Map<K, List<V>> map) {
// Assert.notNull(map, "'map' must not be null");
// this.map = map;
// }
//
// @Override
// @Nullable
// public V getFirst(K key) {
// List<V> values = this.map.get(key);
// return (values != null ? values.get(0) : null);
// }
//
// @Override
// public void add(K key, @Nullable V value) {
// List<V> values = this.map.computeIfAbsent(key, k -> new LinkedList<>());
// values.add(value);
// }
//
// @Override
// public void addAll(K key, List<? extends V> values) {
// List<V> currentValues = this.map.computeIfAbsent(key, k -> new LinkedList<>());
// currentValues.addAll(values);
// }
//
// @Override
// public void addAll(MultiValueMap<K, V> values) {
// for (Entry<K, List<V>> entry : values.entrySet()) {
// addAll(entry.getKey(), entry.getValue());
// }
// }
//
// @Override
// public void set(K key, @Nullable V value) {
// List<V> values = new LinkedList<>();
// values.add(value);
// this.map.put(key, values);
// }
//
// @Override
// public void setAll(Map<K, V> values) {
// values.forEach(this::set);
// }
//
// @Override
// public Map<K, V> toSingleValueMap() {
// LinkedHashMap<K, V> singleValueMap = new LinkedHashMap<>(this.map.size());
// this.map.forEach((key, value) -> singleValueMap.put(key, value.get(0)));
// return singleValueMap;
// }
//
// @Override
// public int size() {
// return this.map.size();
// }
//
// @Override
// public boolean isEmpty() {
// return this.map.isEmpty();
// }
//
// @Override
// public boolean containsKey(Object key) {
// return this.map.containsKey(key);
// }
//
// @Override
// public boolean containsValue(Object value) {
// return this.map.containsValue(value);
// }
//
// @Override
// public List<V> get(Object key) {
// return this.map.get(key);
// }
//
// @Override
// public List<V> put(K key, List<V> value) {
// return this.map.put(key, value);
// }
//
// @Override
// public List<V> remove(Object key) {
// return this.map.remove(key);
// }
//
// @Override
// public void putAll(Map<? extends K, ? extends List<V>> map) {
// this.map.putAll(map);
// }
//
// @Override
// public void clear() {
// this.map.clear();
// }
//
// @Override
// public Set<K> keySet() {
// return this.map.keySet();
// }
//
// @Override
// public Collection<List<V>> values() {
// return this.map.values();
// }
//
// @Override
// public Set<Entry<K, List<V>>> entrySet() {
// return this.map.entrySet();
// }
//
// @Override
// public boolean equals(Object other) {
// if (this == other) {
// return true;
// }
// return this.map.equals(other);
// }
//
// @Override
// public int hashCode() {
// return this.map.hashCode();
// }
//
// @Override
// public String toString() {
// return this.map.toString();
// }
// }
}

View File

@@ -0,0 +1,241 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.ide.eclipse.commons.core.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.log4j.lf5.util.StreamUtils;
import org.eclipse.core.runtime.Assert;
/**
* Simple utility methods for file and stream copying. All copy methods use a block size
* of 4096 bytes, and close all affected streams when done. A variation of the copy
* methods from this class that leave streams open can be found in {@link StreamUtils}.
*
* <p>Mainly for use within the framework, but also useful for application code.
*
* @author Juergen Hoeller
* @since 06.10.2003
* @see StreamUtils
* @see FileSystemUtils
*/
public abstract class FileCopyUtils {
// /**
// * The default buffer size used when copying bytes.
// */
// public static final int BUFFER_SIZE = StreamUtils.BUFFER_SIZE;
//
//
// //---------------------------------------------------------------------
// // Copy methods for java.io.File
// //---------------------------------------------------------------------
//
// /**
// * Copy the contents of the given input File to the given output File.
// * @param in the file to copy from
// * @param out the file to copy to
// * @return the number of bytes copied
// * @throws IOException in case of I/O errors
// */
// public static int copy(File in, File out) throws IOException {
// Assert.notNull(in, "No input File specified");
// Assert.notNull(out, "No output File specified");
// return copy(Files.newInputStream(in.toPath()), Files.newOutputStream(out.toPath()));
// }
//
// /**
// * Copy the contents of the given byte array to the given output File.
// * @param in the byte array to copy from
// * @param out the file to copy to
// * @throws IOException in case of I/O errors
// */
// public static void copy(byte[] in, File out) throws IOException {
// Assert.notNull(in, "No input byte array specified");
// Assert.notNull(out, "No output File specified");
// copy(new ByteArrayInputStream(in), Files.newOutputStream(out.toPath()));
// }
//
// /**
// * Copy the contents of the given input File into a new byte array.
// * @param in the file to copy from
// * @return the new byte array that has been copied to
// * @throws IOException in case of I/O errors
// */
// public static byte[] copyToByteArray(File in) throws IOException {
// Assert.notNull(in, "No input File specified");
// return copyToByteArray(Files.newInputStream(in.toPath()));
// }
//
//
//---------------------------------------------------------------------
// Copy methods for java.io.InputStream / java.io.OutputStream
//---------------------------------------------------------------------
/**
* Copy the contents of the given InputStream to the given OutputStream.
* Closes both streams when done.
* @param in the stream to copy from
* @param out the stream to copy to
* @throws IOException in case of I/O errors
*/
public static void copy(InputStream in, OutputStream out) throws IOException {
Assert.isNotNull(in, "No InputStream specified");
Assert.isNotNull(out, "No OutputStream specified");
try {
StreamUtils.copy(in, out);
}
finally {
try {
in.close();
}
catch (IOException ex) {
}
try {
out.close();
}
catch (IOException ex) {
}
}
}
//
// /**
// * Copy the contents of the given byte array to the given OutputStream.
// * Closes the stream when done.
// * @param in the byte array to copy from
// * @param out the OutputStream to copy to
// * @throws IOException in case of I/O errors
// */
// public static void copy(byte[] in, OutputStream out) throws IOException {
// Assert.notNull(in, "No input byte array specified");
// Assert.notNull(out, "No OutputStream specified");
//
// try {
// out.write(in);
// }
// finally {
// try {
// out.close();
// }
// catch (IOException ex) {
// }
// }
// }
//
// /**
// * Copy the contents of the given InputStream into a new byte array.
// * Closes the stream when done.
// * @param in the stream to copy from (may be {@code null} or empty)
// * @return the new byte array that has been copied to (possibly empty)
// * @throws IOException in case of I/O errors
// */
// public static byte[] copyToByteArray(@Nullable InputStream in) throws IOException {
// if (in == null) {
// return new byte[0];
// }
//
// ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
// copy(in, out);
// return out.toByteArray();
// }
//
//
// //---------------------------------------------------------------------
// // Copy methods for java.io.Reader / java.io.Writer
// //---------------------------------------------------------------------
//
// /**
// * Copy the contents of the given Reader to the given Writer.
// * Closes both when done.
// * @param in the Reader to copy from
// * @param out the Writer to copy to
// * @return the number of characters copied
// * @throws IOException in case of I/O errors
// */
// public static int copy(Reader in, Writer out) throws IOException {
// Assert.notNull(in, "No Reader specified");
// Assert.notNull(out, "No Writer specified");
//
// try {
// int byteCount = 0;
// char[] buffer = new char[BUFFER_SIZE];
// int bytesRead = -1;
// while ((bytesRead = in.read(buffer)) != -1) {
// out.write(buffer, 0, bytesRead);
// byteCount += bytesRead;
// }
// out.flush();
// return byteCount;
// }
// finally {
// try {
// in.close();
// }
// catch (IOException ex) {
// }
// try {
// out.close();
// }
// catch (IOException ex) {
// }
// }
// }
//
// /**
// * Copy the contents of the given String to the given output Writer.
// * Closes the writer when done.
// * @param in the String to copy from
// * @param out the Writer to copy to
// * @throws IOException in case of I/O errors
// */
// public static void copy(String in, Writer out) throws IOException {
// Assert.notNull(in, "No input String specified");
// Assert.notNull(out, "No Writer specified");
//
// try {
// out.write(in);
// }
// finally {
// try {
// out.close();
// }
// catch (IOException ex) {
// }
// }
// }
//
// /**
// * Copy the contents of the given Reader into a String.
// * Closes the reader when done.
// * @param in the reader to copy from (may be {@code null} or empty)
// * @return the String that has been copied to (possibly empty)
// * @throws IOException in case of I/O errors
// */
// public static String copyToString(@Nullable Reader in) throws IOException {
// if (in == null) {
// return "";
// }
//
// StringWriter out = new StringWriter();
// copy(in, out);
// return out.toString();
// }
}

View File

@@ -0,0 +1,133 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.jface.text.IRegion;
/**
* @author Kris De Volder
*/
public class FuzzyMatcher {
private static class Region implements IRegion {
public Region(int start, int end) {
super();
this.start = start;
this.end = end;
}
int start;
int end;
@Override
public int getLength() {
return end-start;
}
@Override
public int getOffset() {
return start;
}
@Override
public String toString() {
return "Region["+start+".."+end+"]";
}
}
public static Collection<IRegion> highlights(CharSequence query, String data) {
List<IRegion> highlights = new ArrayList<>();
int qpos = 0;
int dpos = 0;
int qlen = query.length();
int dlen = data.length();
while (qpos<qlen && dpos<dlen) {
int nextMatch = data.indexOf(query.charAt(qpos), dpos);
if (nextMatch<0) {
return highlights;
}
addMatch(highlights, nextMatch);
qpos++;
dpos = nextMatch+1;
}
return highlights;
}
private static void addMatch(List<IRegion> highlights, int nextMatch) {
if (highlights.isEmpty()) {
highlights.add(new Region(nextMatch, nextMatch+1));
}
Region lastRegion = (Region) highlights.get(highlights.size()-1);
if (lastRegion.getOffset()+lastRegion.getLength()==nextMatch) {
lastRegion.end++;
} else {
highlights.add(new Region(nextMatch, nextMatch+1));
}
}
/**
* Match given pattern with a given data. The data is considered a 'match' for the
* pattern if all characters in the pattern can be found in the data, in the
* same order but with possible 'gaps' in between.
* <p>
* The function returns 0. when the pattern doesn't match the data and a non-zero
* 'score' when it does. The higher the score, the better the match is considered to
* be.
*/
public static double matchScore(CharSequence pattern, String data) {
int ppos = 0; //pos of next char in pattern to look for
int dpos = 0; //pos of next char in data not yet matched
int gaps = 0; //number of 'gaps' in the match. A gap is any non-empty run of consecutive characters in the data that are not used by the match
int skips = 0; //number of skipped characters. This is the sum of the length of all the gaps.
int plen = pattern.length();
int dlen = data.length();
if (plen>dlen) {
return 0.0;
}
while (ppos<plen) {
if (dpos>=dlen) {
//still chars left in pattern but no more data
return 0.0;
}
char c = pattern.charAt(ppos++);
int foundCharAt = data.indexOf(c, dpos);
if (foundCharAt>=0) {
if (foundCharAt>dpos) {
gaps++;
skips+=foundCharAt-dpos;
}
dpos = foundCharAt+1;
} else {
return 0.0;
}
}
//end of pattern reached. All matched.
if (dpos<dlen) {
//data left over
//gaps++; don't count end skipped chars as a real 'gap'. Otherwise we
//tend to favor matches at the end of the string over matches in the middle.
skips+=dlen-dpos; //but do count the extra chars at end => more extra = worse score
}
return score(gaps, skips, pattern);
}
private static double score(int gaps, int skips, CharSequence pattern) {
if (gaps==0) {
//gaps == 0 means a prefix match, ignore 'skips' at end of String and just sort
// alphabetic (see STS-4049)
return 0.5+pattern.length(); //all scored equally, assumes using a 'stable' sorter.
} else {
double badness = 1+gaps + skips/1000.0; // higher is worse
return 1.0/badness + pattern.length(); //higher is better
}
}
}

View File

@@ -0,0 +1,36 @@
/*******************************************************************************
* Copyright (c) 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import java.io.IOException;
import java.io.InputStream;
public class IOUtil {
private static final int BUF_SIZE = 1024;
/**
* Consume all data in an input stream, discdaring the data and closing the stream upon completion.
*/
public static void consume(InputStream stream) throws IOException {
try {
byte[] buf = new byte[BUF_SIZE];
while (stream.read(buf)>=0) {}
} finally {
try {
stream.close();
} catch (IOException e) {
//ignore (or it may mask a more important / interesting error in the body of the try
}
}
}
}

View File

@@ -0,0 +1,99 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import java.io.IOException;
import java.io.OutputStream;
/**
* A wrapper around multiple output streams that mulitplexes any output written to this Stream to all
* the wrapped Streams.
* @author Kris De Volder
*/
public class MultiplexingOutputStream extends OutputStream {
OutputStream[] streams = null;
public MultiplexingOutputStream(OutputStream... streams) {
super();
if (streams==null) {
this.streams = new OutputStream[0];
} else {
this.streams = streams;
}
}
/**
* Writes the byte b to each wrapped OutputStream.
* <p>
* If one of the Streams throws an Exception this exception is
* propagated. No guarantees are made in this case that output
* is written to the other Streams.
*/
@Override
public void write(int b) throws IOException {
for (OutputStream s : streams) {
s.write(b);
}
}
/**
* Writes to each wrapped OutputStream.
* <p>
* If one of the Streams throws an Exception this exception is
* propagated. No guarantees are made in this case that output
* is written to the other Streams.
*/
@Override
public void write(byte[] b, int off, int len) throws IOException {
for (OutputStream s : streams) {
s.write(b, off, len);
}
}
/**
* Attempt to close all of the underlying Streams. If any of the Streams
* throws an exception it is guaranteed that at least one of those
* exceptions will be propagated.
* <p>
* Even if one of the streams throws an Exception, we will still
* attempt to close the other Streams.
*/
@Override
public void close() throws IOException {
super.close();
Throwable caught = null;
for (OutputStream s : streams) {
try {
s.close();
} catch (Throwable e) {
caught = e;
}
}
if (caught!=null) {
if (caught instanceof IOException) {
throw (IOException)caught;
} else {
// If not a Declared exception it must be an unchecked exception.
throw (Error)caught;
}
}
}
@Override
public void flush() throws IOException {
for (OutputStream s : streams) {
s.flush();
}
}
}

View File

@@ -0,0 +1,48 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
/**
* Simple name generator implementation
*
* @author Alex Boyko
* @author Kris De Volder
*/
public class NameGenerator {
private static final String delimiter = "-";
private String prefix;
private int number = 0;
public NameGenerator(String previousName) {
prefix = previousName.replace(' ', '-'); //See: https://github.com/spring-projects/spring-ide/issues/230
int d = previousName.lastIndexOf(delimiter);
if (d>=0) {
try {
String numString = previousName.substring(d+1);
number = Integer.parseInt(numString);
prefix = previousName.substring(0, d);
} catch (NumberFormatException e) {
//ignore
}
}
}
public String generateNext() {
StringBuilder sb = new StringBuilder();
sb.append(prefix);
sb.append(delimiter);
sb.append(++number);
return sb.toString();
}
}

View File

@@ -0,0 +1,83 @@
/*******************************************************************************
* Copyright (c) 2012, 2015 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import java.util.LinkedHashSet;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* @author Kris De Volder
*/
public class NatureUtils {
/**
* Make sure a project has a number of required natures. If the natures are not yet present, add them now.
* @throws CoreException
*/
public static void ensure(IProject project, IProgressMonitor mon, String... reqNatures) throws CoreException {
IProjectDescription desc = project.getDescription();
String[] oldNaturesArr = desc.getNatureIds();
Set<String> natures = new LinkedHashSet<String>();
for (String n : reqNatures) {
natures.add(n);
}
for (String n : oldNaturesArr) {
natures.add(n);
}
if (natures.size()>oldNaturesArr.length) {
//Some natures got added
desc.setNatureIds(natures.toArray(new String[natures.size()]));
project.setDescription(desc, mon);
} else {
//No new natures added, but need to set it to force desired ordering
desc.setNatureIds(natures.toArray(new String[natures.size()]));
project.setDescription(desc, IResource.AVOID_NATURE_CONFIG, mon);
}
}
/**
* Removes a nature from a project. This does nothing if the project doesn't have the nature.
*/
public static void remove(IProject project, String natureId, IProgressMonitor mon) throws CoreException {
IProjectDescription desc = project.getDescription();
String[] oldNaturesArr = desc.getNatureIds();
Set<String> natures = new LinkedHashSet<String>();
for (String n : oldNaturesArr) {
if (!n.equals(natureId)) {
natures.add(n);
}
}
if (natures.size()!=oldNaturesArr.length) {
//Something removed
desc.setNatureIds(natures.toArray(new String[natures.size()]));
project.setDescription(desc, mon);
}
}
public static boolean hasNature(IProject p, String natureId) {
try {
return p!=null && p.isAccessible() && p.hasNature(natureId);
} catch (CoreException e) {
CorePlugin.log(e);
}
return false;
}
}

View File

@@ -0,0 +1,63 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import static java.nio.file.attribute.PosixFilePermission.GROUP_EXECUTE;
import static java.nio.file.attribute.PosixFilePermission.GROUP_READ;
import static java.nio.file.attribute.PosixFilePermission.GROUP_WRITE;
import static java.nio.file.attribute.PosixFilePermission.OTHERS_EXECUTE;
import static java.nio.file.attribute.PosixFilePermission.OTHERS_READ;
import static java.nio.file.attribute.PosixFilePermission.OTHERS_WRITE;
import static java.nio.file.attribute.PosixFilePermission.OWNER_EXECUTE;
import static java.nio.file.attribute.PosixFilePermission.OWNER_READ;
import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE;
import java.nio.file.attribute.PosixFilePermission;
import java.util.EnumSet;
import java.util.Set;
/**
* @author Kris De Volder
*
* @since 2.8
*/
public class OsUtils {
public static boolean isWindows() {
return System.getProperty("os.name").contains("Windows");
}
private static final PosixFilePermission[] decodeMap = {
//This is exactly the reverse order as in the enum.
//But it seems safer not to rely on that.
OTHERS_EXECUTE,
OTHERS_WRITE,
OTHERS_READ,
GROUP_EXECUTE,
GROUP_WRITE,
GROUP_READ,
OWNER_EXECUTE,
OWNER_WRITE,
OWNER_READ
};
public static Set<PosixFilePermission> posixFilePermissions(int mode) {
int mask = 1;
Set<PosixFilePermission> perms = EnumSet.noneOf(PosixFilePermission.class);
for (PosixFilePermission flag : decodeMap) {
if (flag!=null && (mask & mode) != 0) {
perms.add(flag);
}
mask = mask << 1;
}
return perms;
}
}

View File

@@ -0,0 +1,94 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
/**
* Process Utilities making use of JDK tools
*
* @author Alex Boyko
*
*/
@SuppressWarnings("restriction")
public class ProcessUtils {
/**
* Retrieves PID of a process
* @param p the process
* @return PID
*/
public static long getProcessID(Process p) {
long result = -1;
try {
Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
result = f.getLong(p);
f.setAccessible(false);
}
catch (Exception ex) {
throw new UnsupportedOperationException("Process PID calculation not supported on the current platform",
ex);
}
return result;
}
/**
* Creates JMX Connector to a process specified by its PID
* @param pid the PID
* @return JMX connector
*/
public static JMXConnector createJMXConnector(String pid) {
List<VirtualMachineDescriptor> vmds = VirtualMachine.list();
VirtualMachineDescriptor vmd = vmds.stream().filter(descriptor -> descriptor.id().equals(pid)).findFirst().orElse(null);
if (vmd != null) {
try {
String agentUrl = VirtualMachine.attach(vmd).startLocalManagementAgent();
if (agentUrl != null) {
JMXServiceURL serviceUrl = new JMXServiceURL(agentUrl);
return JMXConnectorFactory.connect(serviceUrl, null);
}
} catch (AttachNotSupportedException e) {
CorePlugin.log(e);
} catch (IOException e) {
CorePlugin.log(e);
}
}
return null;
}
/**
* Determines whether current JDK supports utilities defined in this class
* @return <code>true</code> for compatible JDK
*/
public static boolean isLatestJdkForTools() {
try {
return VirtualMachine.class.getDeclaredMethod("startLocalManagementAgent") != null;
}
catch (NoSuchMethodException | SecurityException e) {
// ignore
}
return false;
}
}

View File

@@ -0,0 +1,263 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.ide.eclipse.commons.core.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.eclipse.core.runtime.Assert;
/**
* Simple utility methods for dealing with streams. The copy methods of this class are
* similar to those defined in {@link FileCopyUtils} except that all affected streams are
* left open when done. All copy methods use a block size of 4096 bytes.
*
* <p>Mainly for use within the framework, but also useful for application code.
*
* @author Juergen Hoeller
* @author Phillip Webb
* @author Brian Clozel
* @since 3.2.2
* @see FileCopyUtils
*/
public abstract class StreamUtils {
/**
* The default buffer size used why copying bytes.
*/
public static final int BUFFER_SIZE = 4096;
// private static final byte[] EMPTY_CONTENT = new byte[0];
//
//
// /**
// * Copy the contents of the given InputStream into a new byte array.
// * Leaves the stream open when done.
// * @param in the stream to copy from (may be {@code null} or empty)
// * @return the new byte array that has been copied to (possibly empty)
// * @throws IOException in case of I/O errors
// */
// public static byte[] copyToByteArray(@Nullable InputStream in) throws IOException {
// if (in == null) {
// return new byte[0];
// }
//
// ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
// copy(in, out);
// return out.toByteArray();
// }
//
// /**
// * Copy the contents of the given InputStream into a String.
// * Leaves the stream open when done.
// * @param in the InputStream to copy from (may be {@code null} or empty)
// * @return the String that has been copied to (possibly empty)
// * @throws IOException in case of I/O errors
// */
// public static String copyToString(@Nullable InputStream in, Charset charset) throws IOException {
// if (in == null) {
// return "";
// }
//
// StringBuilder out = new StringBuilder();
// InputStreamReader reader = new InputStreamReader(in, charset);
// char[] buffer = new char[BUFFER_SIZE];
// int bytesRead = -1;
// while ((bytesRead = reader.read(buffer)) != -1) {
// out.append(buffer, 0, bytesRead);
// }
// return out.toString();
// }
//
// /**
// * Copy the contents of the given byte array to the given OutputStream.
// * Leaves the stream open when done.
// * @param in the byte array to copy from
// * @param out the OutputStream to copy to
// * @throws IOException in case of I/O errors
// */
// public static void copy(byte[] in, OutputStream out) throws IOException {
// Assert.notNull(in, "No input byte array specified");
// Assert.notNull(out, "No OutputStream specified");
//
// out.write(in);
// }
//
// /**
// * Copy the contents of the given String to the given output OutputStream.
// * Leaves the stream open when done.
// * @param in the String to copy from
// * @param charset the Charset
// * @param out the OutputStream to copy to
// * @throws IOException in case of I/O errors
// */
// public static void copy(String in, Charset charset, OutputStream out) throws IOException {
// Assert.notNull(in, "No input String specified");
// Assert.notNull(charset, "No charset specified");
// Assert.notNull(out, "No OutputStream specified");
//
// Writer writer = new OutputStreamWriter(out, charset);
// writer.write(in);
// writer.flush();
// }
//
/**
* Copy the contents of the given InputStream to the given OutputStream.
* Leaves both streams open when done.
* @param in the InputStream to copy from
* @param out the OutputStream to copy to
* @return the number of bytes copied
* @throws IOException in case of I/O errors
*/
public static int copy(InputStream in, OutputStream out) throws IOException {
Assert.isNotNull(in, "No InputStream specified");
Assert.isNotNull(out, "No OutputStream specified");
int byteCount = 0;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
}
// /**
// * Copy a range of content of the given InputStream to the given OutputStream.
// * <p>If the specified range exceeds the length of the InputStream, this copies
// * up to the end of the stream and returns the actual number of copied bytes.
// * <p>Leaves both streams open when done.
// * @param in the InputStream to copy from
// * @param out the OutputStream to copy to
// * @param start the position to start copying from
// * @param end the position to end copying
// * @return the number of bytes copied
// * @throws IOException in case of I/O errors
// * @since 4.3
// */
// public static long copyRange(InputStream in, OutputStream out, long start, long end) throws IOException {
// Assert.notNull(in, "No InputStream specified");
// Assert.notNull(out, "No OutputStream specified");
//
// long skipped = in.skip(start);
// if (skipped < start) {
// throw new IOException("Skipped only " + skipped + " bytes out of " + start + " required");
// }
//
// long bytesToCopy = end - start + 1;
// byte[] buffer = new byte[StreamUtils.BUFFER_SIZE];
// while (bytesToCopy > 0) {
// int bytesRead = in.read(buffer);
// if (bytesRead == -1) {
// break;
// }
// else if (bytesRead <= bytesToCopy) {
// out.write(buffer, 0, bytesRead);
// bytesToCopy -= bytesRead;
// }
// else {
// out.write(buffer, 0, (int) bytesToCopy);
// bytesToCopy = 0;
// }
// }
// return (end - start + 1 - bytesToCopy);
// }
//
// /**
// * Drain the remaining content of the given InputStream.
// * Leaves the InputStream open when done.
// * @param in the InputStream to drain
// * @return the number of bytes read
// * @throws IOException in case of I/O errors
// * @since 4.3
// */
// public static int drain(InputStream in) throws IOException {
// Assert.notNull(in, "No InputStream specified");
// byte[] buffer = new byte[BUFFER_SIZE];
// int bytesRead = -1;
// int byteCount = 0;
// while ((bytesRead = in.read(buffer)) != -1) {
// byteCount += bytesRead;
// }
// return byteCount;
// }
//
// /**
// * Return an efficient empty {@link InputStream}.
// * @return a {@link ByteArrayInputStream} based on an empty byte array
// * @since 4.2.2
// */
// public static InputStream emptyInput() {
// return new ByteArrayInputStream(EMPTY_CONTENT);
// }
//
// /**
// * Return a variant of the given {@link InputStream} where calling
// * {@link InputStream#close() close()} has no effect.
// * @param in the InputStream to decorate
// * @return a version of the InputStream that ignores calls to close
// */
// public static InputStream nonClosing(InputStream in) {
// Assert.notNull(in, "No InputStream specified");
// return new NonClosingInputStream(in);
// }
//
// /**
// * Return a variant of the given {@link OutputStream} where calling
// * {@link OutputStream#close() close()} has no effect.
// * @param out the OutputStream to decorate
// * @return a version of the OutputStream that ignores calls to close
// */
// public static OutputStream nonClosing(OutputStream out) {
// Assert.notNull(out, "No OutputStream specified");
// return new NonClosingOutputStream(out);
// }
//
//
// private static class NonClosingInputStream extends FilterInputStream {
//
// public NonClosingInputStream(InputStream in) {
// super(in);
// }
//
// @Override
// public void close() throws IOException {
// }
// }
//
//
// private static class NonClosingOutputStream extends FilterOutputStream {
//
// public NonClosingOutputStream(OutputStream out) {
// super(out);
// }
//
// @Override
// public void write(byte[] b, int off, int let) throws IOException {
// // It is critical that we override this method for performance
// this.out.write(b, off, let);
// }
//
// @Override
// public void close() throws IOException {
// }
// }
}

View File

@@ -0,0 +1,143 @@
/*******************************************************************************
* Copyright (c) 2017 Spring IDE Developers
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spring IDE Developers - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.core.util;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
public static boolean hasText(String name) {
return name!=null && !name.trim().equals("");
}
public static String trim(String s) {
if (s!=null) {
return s.trim();
}
return null;
}
public static String trimEnd(String s) {
if (s!=null) {
return s.replaceAll("\\s+\\z", "");
}
return null;
}
public static int commonPrefixLength(CharSequence s, CharSequence t) {
int shortestStringLen = Math.min(s.length(), t.length());
for (int i = 0; i < shortestStringLen; i++) {
if (s.charAt(i)!=t.charAt(i)) {
return i;
}
}
//no difference found upto entire length of shortest string.
return shortestStringLen;
}
/**
* @return longest string which is a prefix of both argument Strings.
*/
public static String commonPrefix(CharSequence s, CharSequence t) {
int len = commonPrefixLength(s, t);
if (len>0) {
return s.subSequence(0,len).toString();
}
return "";
}
public static String removePrefix(String s, String prefix) {
if (s.startsWith(prefix)) {
return s.substring(prefix.length());
} else {
return s;
}
}
public static String camelCaseToHyphens(String value) {
Matcher matcher = CAMEL_CASE_PATTERN.matcher(value);
StringBuffer result = new StringBuffer();
int start = 0;
while (matcher.find()) {
result.append(value.substring(start, matcher.start()));
result.append(matcher.group(1));
result.append('-');
result.append(matcher.group(2).toLowerCase());
start = matcher.end();
}
result.append(value.substring(start));
return result.toString();
}
private static final Pattern CAMEL_CASE_PATTERN = Pattern.compile("([^A-Z-])([A-Z])");
public static String arrayToCommaDelimitedString(Object[] array) {
return collectionToCommaDelimitedString(Arrays.asList(array));
}
public static String collectionToCommaDelimitedString(Collection<?> items) {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Object item : items) {
if (!first) {
buf.append(",");
}
buf.append(item);
first = false;
}
return buf.toString();
}
public static String upperCaseToHyphens(String v) {
if (v!=null) {
return v.toLowerCase().replace('_', '-');
}
return null;
}
public static String hyphensToUpperCase(String v) {
if (v!=null) {
return v.toUpperCase().replace('-', '_');
}
return null;
}
public static String hyphensToCamelCase(String propName, boolean startWithUpperCase) {
String [] parts = propName.split("-");
if (startWithUpperCase) {
parts[0] = upCaseFirstChar(parts[0]);
}
StringBuilder camelCased = new StringBuilder(parts[0]);
for (int i = 1; i < parts.length; i++) {
camelCased.append(upCaseFirstChar(parts[i]));
}
return camelCased.toString();
}
public static String upCaseFirstChar(String string) {
if (StringUtil.hasText(string)) {
return Character.toUpperCase(string.charAt(0)) + string.substring(1);
}
return "";
}
public static String datestamp() {
Date d = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
return f.format(d);
}
}

View File

@@ -0,0 +1,100 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.prefs.Preferences;
/**
* @author Steffen Pingel
* @author Leo Dos Santos
* @author Christian Dupuis
*/
public class CorePlugin extends Plugin {
public static final String PLUGIN_ID = "org.springsource.ide.eclipse.commons.core";
private static CorePlugin plugin;
private static final String UUID_PROPERTY_KEY = "install.id";
public static IStatus createErrorStatus(String message, Throwable exception) {
if (message == null) {
message = "";
}
return new Status(IStatus.ERROR, PLUGIN_ID, 0, message, exception);
}
public static CorePlugin getDefault() {
return plugin;
}
public synchronized static String getUUID() {
ServiceReference ref = getDefault().getBundle().getBundleContext()
.getServiceReference(IPreferencesService.class.getName());
IPreferencesService prefService = (IPreferencesService) getDefault().getBundle().getBundleContext()
.getService(ref);
try {
IEclipsePreferences prefs = (IEclipsePreferences) prefService.getRootNode().node(InstanceScope.SCOPE);
Preferences p = prefs.node(PLUGIN_ID);
if (StringUtils.isEmpty(p.get(UUID_PROPERTY_KEY, ""))) {
p.put(UUID_PROPERTY_KEY, UUID.randomUUID().toString());
}
return p.get(UUID_PROPERTY_KEY, "");
}
finally {
if (prefService != null) {
getDefault().getBundle().getBundleContext().ungetService(ref);
}
}
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void log(String message, Throwable exception) {
IStatus status = createErrorStatus(message, exception);
log(status);
}
public static void log(Throwable exception) {
log(createErrorStatus("Internal Error", exception));
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
savePluginPreferences();
}
public static void warn(String msg) {
log(new Status(IStatus.WARNING, PLUGIN_ID, msg));
}
}

View File

@@ -0,0 +1,339 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core.commandhistory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.resources.ISaveContext;
import org.eclipse.core.resources.ISaveParticipant;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.springsource.ide.eclipse.commons.core.Entry;
import org.springsource.ide.eclipse.commons.core.ICommandHistory;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* This provides a light-weight command history that is persisted in the user's
* workspace.
* @author Andrew Eisenberg
* @author Christian Dupuis
* @author Kris De Volder
* @since 2.5.0
*/
public class CommandHistory implements Iterable<Entry>, ICommandHistory {
/**
* Our ISaveParticipant, responsible for persisting the CommandHistory in
* the workspace.
*/
private class CommandHistorySaver implements ISaveParticipant {
public void doneSaving(ISaveContext context) {
}
public void prepareToSave(ISaveContext context) throws CoreException {
}
public void rollback(ISaveContext context) {
}
public void saving(ISaveContext context) throws CoreException {
if (isDirty()) {
try {
save(getSavePath());
}
catch (Exception e) {
throw new CoreException(CorePlugin.createErrorStatus("Couldn't save command history", e));
}
context.needSaveNumber();
}
}
}
private static final String HISTORY_FILE_NAME = ".commandhistory";
/**
* If the number of history entries exceeds maxSize, older items will be
* automatically dropped.
*/
private int maxSize = DEFAULT_MAX_SIZE;
private boolean isDirty;
private LinkedList<Entry> history = new LinkedList<Entry>();
private final String natureId;
private final String historyId;
public CommandHistory(String historyId, String natureId) {
this.natureId = natureId;
this.historyId = historyId;
}
/**
* Create an "auto saving" CommandHistory and register it as a save
* participant with the workspace.
*/
public CommandHistory(String historyId, String natureId, boolean persist) throws CoreException {
this.natureId = natureId;
this.historyId = historyId;
if (persist) {
CommandHistorySaver saver = new CommandHistorySaver();
// Method addSaveParticipant(String, ISaveParticipant) is deprecated
// on 3.6, but the alternative does not exist in 3.5
ResourcesPlugin.getWorkspace().addSaveParticipant(CorePlugin.getDefault(), saver);
load(getSavePath());
}
}
/**
* Add an element to the history. If a similar element already exists in the
* history, the older element is removed before adding the new one.
* <p>
* Adding an element beyond the maxSize will result in the oldest item being
* discarded.
*/
public void add(Entry entry) {
history.remove(entry);
history.addFirst(entry);
discardOldEntries();
isDirty = true;
}
public void clear() {
history.clear();
isDirty = true;
}
/**
* Throw away old entries until our size obeys the maxSize constraint.
*/
private void discardOldEntries() {
while (size() > getMaxSize()) {
history.removeLast();
}
}
/**
* Return the last added element.
*/
public Entry getLast() {
// elements in backing collection are actually in inverse order
return history.getFirst();
}
/**
* @return The number of items in the history is limited to.
*/
public int getMaxSize() {
return maxSize;
}
/**
* Retrieve a List of most recent entries, (most recent first).
* @param limit Return at most this many elements.
*/
public List<Entry> getRecentValid(int limit) {
ArrayList<Entry> result = new ArrayList<Entry>(limit);
for (Entry entry : validEntries()) {
if (limit-- <= 0) {
return result;
}
result.add(entry);
}
return result;
}
private IPath getSavePath() {
return CorePlugin.getDefault().getStateLocation().append(historyId + HISTORY_FILE_NAME);
}
/**
* Did this history get changed since it was last saved?
*/
public boolean isDirty() {
return isDirty;
}
public boolean isEmpty() {
return history.isEmpty();
}
/**
* Iterator that starts from the most recently added element.
*/
public Iterator<Entry> iterator() {
return history.iterator();
}
/**
* Load history contents from a file. If the file does not exist we silently
* assume the history should be empty.
* <p>
* If there are errors loading file we keep the current history and log an
* exception.
*/
public void load(File file) {
try {
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
ObjectInputStream oIn = null;
try {
oIn = new ObjectInputStream(fIn);
load(oIn);
isDirty = false;
}
finally {
if (oIn != null) {
oIn.close();
}
else if (fIn != null) {
fIn.close();
}
}
}
}
catch (Exception e) {
CorePlugin.log("Could not restore the command history", e);
if (file.exists()) {
// File is corrupt...
file.delete();
}
}
}
private void load(IPath savePath) {
load(savePath.toFile());
}
/**
* Load the state from an InputOutputStream, let someone else worry where
* this stream came from and how to handle error / exception making sure the
* stream is closed no matter what.
* @throws ClassNotFoundException
* @throws IOException
*/
private void load(ObjectInputStream in) throws IOException, ClassNotFoundException {
int newMaxSize = in.readInt();
Entry[] elements = new Entry[in.readInt()];
for (int i = 0; i < elements.length; i++) {
elements[i] = (Entry) in.readObject();
}
// We could do this in one go, but it is slightly nicer not to modify
// the state of this history object until we are successful reading
// all the elements.
maxSize = newMaxSize;
history = new LinkedList<Entry>();
for (Entry element : elements) {
history.add(element);
}
isDirty = false;
}
/**
* Save this history to a file
* @throws IOException
*/
public void save(File file) throws IOException {
if (isDirty()) {
FileOutputStream fOut = new FileOutputStream(file);
ObjectOutputStream oOut = null;
try {
oOut = new ObjectOutputStream(fOut);
save(oOut);
isDirty = false;
}
finally {
if (oOut != null) {
oOut.close();
}
else if (fOut != null) {
fOut.close();
}
}
}
}
/**
* Save this history to a file
* @throws IOException
*/
private void save(IPath file) throws IOException {
save(file.toFile());
}
/**
* Save the state to an ObjectOutputStream, let someone else worry where
* this stream came from and how to handle error / exception making sure the
* stream is closed no matter what.
*/
private void save(ObjectOutputStream out) throws IOException {
out.writeInt(maxSize);
out.writeInt(size());
for (Entry entry : history) {
out.writeObject(entry);
}
}
/**
* Set the maxSize value. This will limit the number of items that will be
* retained in the history. When the limit is exceeded, older items are
* discarded.
*/
public void setMaxSize(int max) {
Assert.isLegal(max > 0);
this.maxSize = max;
discardOldEntries();
isDirty = true;
}
public int size() {
return history.size();
}
/**
* Returns an array of the elements in the history, with the newest item at
* position 0.
*/
public Entry[] toArray() {
Entry[] result = new Entry[size()];
int i = 0;
for (Entry entry : this) {
result[i++] = entry;
}
return result;
}
/**
* @return an Iterable (suitable for "foreach" iteration) providing only
* Entry's who's projects are valid open projects in the workspace.
*/
public Iterable<Entry> validEntries() {
return new ValidProjectFilter(this, natureId);
}
}

View File

@@ -0,0 +1,73 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core.commandhistory;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.iterators.FilterIterator;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.springsource.ide.eclipse.commons.core.Entry;
import org.springsource.ide.eclipse.commons.core.SpringCoreUtils;
/**
* Utility class, provides a method to decide whether a given command history
* Entry belongs to a project with the given nature.
* <p>
* The CommandHistory stores history items that may no longer be valid (because
* the associated project has been closed/renamed/deleted etc.
* <p>
* A ValidProjectFilter can be applied to an Iterable<Entry> (which includes
* CommandHistory) to only yield valid entries according to the current state of
* the workspace.
* <p>
* The Filtering is efficient in the sense that it does not create an extra
* collection containing the valid elements but only an iterator that skips over
* invalid entries in the original collection.
* @author Andrew Eisenberg
* @author Christian Dupuis
* @author Kris De Volder
* @since 2.5.0
*/
public class ValidProjectFilter implements Iterable<Entry> {
private final Iterable<Entry> target;
private final String natureId;
public ValidProjectFilter(Iterable<Entry> target, String natureId) {
this.target = target;
this.natureId = natureId;
}
@SuppressWarnings("unchecked")
public Iterator<Entry> iterator() {
final Set<String> validProjects = new HashSet<String>();
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject project : projects) {
// Test if the selected project has the given nature
if (project.isAccessible() && SpringCoreUtils.hasNature(project, natureId)) {
validProjects.add(project.getName());
}
}
return new FilterIterator(target.iterator(), new Predicate() {
public boolean evaluate(Object _entry) {
Entry entry = (Entry) _entry;
return validProjects.contains(entry.getProject());
}
});
}
}

View File

@@ -0,0 +1,233 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core.net;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.mylyn.commons.net.WebLocation;
import org.eclipse.osgi.util.NLS;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* A utility for accessing web resources.
* @author Steffen Pingel
*/
public class HttpClientTransportService implements ITransportService {
private static final int BUFFER_SIZE = 4 * 1024;
public HttpClientTransportService() {
}
/**
* Download an HTTP-based resource
*
* @param target the target file to which the content is saved
* @param location the web location of the content
* @param monitor the monitor
* @throws IOException if a network or IO problem occurs
*/
public void download(java.net.URI uri, OutputStream out, IProgressMonitor progressMonitor) throws CoreException {
WebLocation location = new WebLocation(uri.toString());
SubMonitor monitor = SubMonitor.convert(progressMonitor);
monitor.subTask(NLS.bind("Fetching {0}", location.getUrl()));
try {
HttpClient client = new HttpClient();
org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$
GetMethod method = new GetMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil.createHostConfiguration(
client, location, monitor);
int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
long total = method.getResponseContentLength();
if (total != -1) {
monitor.setWorkRemaining((int) total);
}
InputStream in = org.eclipse.mylyn.commons.net.WebUtil.getResponseBodyAsStream(method, monitor);
try {
in = new BufferedInputStream(in);
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
if (total != -1) {
monitor.worked(len);
}
else {
monitor.worked(1);
monitor.setWorkRemaining(10000);
}
if (monitor.isCanceled()) {
// this point is reached if the user requests a
// cancellation
throw new OperationCanceledException();
}
}
}
catch (OperationCanceledException e) {
// this point is reached if there is some problem with
// the download
throw toException(location, result);
}
catch (IOException e) {
// this point is reached if there is some problem with
// the network
throw toException(location, 500);
}
finally {
in.close();
}
}
else {
throw toException(location, result);
}
}
finally {
method.releaseConnection();
}
}
catch (IOException e) {
throw toException(location, e);
}
finally {
monitor.done();
}
}
/**
* Verify availability of resources at the given web locations. Normally
* this would be done using an HTTP HEAD.
*
* @param locations the locations of the resource to verify
* @param one indicate if only one of the resources must exist
* @param progressMonitor the monitor
* @return true if the resource exists
*/
public long getLastModified(java.net.URI uri, IProgressMonitor progressMonitor) throws CoreException {
WebLocation location = new WebLocation(uri.toString());
SubMonitor monitor = SubMonitor.convert(progressMonitor);
monitor.subTask(NLS.bind("Fetching {0}", location.getUrl()));
try {
HttpClient client = new HttpClient();
org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$
HeadMethod method = new HeadMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil.createHostConfiguration(
client, location, monitor);
int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
Header lastModified = method.getResponseHeader("Last-Modified"); //$NON-NLS-1$
if (lastModified != null) {
try {
return DateUtil.parseDate(lastModified.getValue()).getTime();
}
catch (DateParseException e) {
// fall through
}
}
return 0;
}
else {
throw toException(location, result);
}
}
catch (IOException e) {
throw toException(location, e);
}
finally {
method.releaseConnection();
}
}
finally {
monitor.done();
}
}
/**
* Read a web-based resource at the specified location using the given
* processor.
*
* @param location the web location of the content
* @param processor the processor that will handle content
* @param progressMonitor the monitor
* @throws IOException if a network or IO problem occurs
*/
public InputStream stream(java.net.URI uri, IProgressMonitor progressMonitor) throws CoreException {
WebLocation location = new WebLocation(uri.toString());
SubMonitor monitor = SubMonitor.convert(progressMonitor);
monitor.subTask(NLS.bind("Fetching {0}", location.getUrl()));
try {
HttpClient client = new HttpClient();
org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$
boolean success = false;
GetMethod method = new GetMethod(location.getUrl());
try {
HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil.createHostConfiguration(
client, location, monitor);
int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method, monitor);
if (result == HttpStatus.SC_OK) {
InputStream in = org.eclipse.mylyn.commons.net.WebUtil.getResponseBodyAsStream(method, monitor);
success = true;
return in;
}
else {
throw toException(location, result);
}
}
catch (IOException e) {
throw toException(location, e);
}
finally {
if (!success) {
method.releaseConnection();
}
}
}
finally {
monitor.done();
}
}
private CoreException toException(WebLocation location, int result) {
return new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, NLS.bind(
"Download of {0} failed: Unexpected HTTP response {1}", location.getUrl(), result)));
}
private CoreException toException(WebLocation location, IOException e) throws CoreException {
String message = e.getMessage() != null ? e.getMessage() : "Unexpected error";
return new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, NLS.bind(
"Download of {0} failed: {1}", location.getUrl(), message), e));
}
}

View File

@@ -0,0 +1,31 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core.net;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* @author Steffen Pingel
*/
public interface ITransportService {
public abstract void download(URI uri, OutputStream out, IProgressMonitor monitor) throws CoreException;
public abstract long getLastModified(URI location, IProgressMonitor monitor) throws CoreException;
public abstract InputStream stream(URI uri, IProgressMonitor monitor) throws CoreException;
}

View File

@@ -0,0 +1,120 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core.net;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.osgi.util.NLS;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* @author Terry Denney
*/
public class JDKTransportService implements ITransportService {
private static final int BUFFER_SIZE = 4 * 1024;
public void download(URI uri, OutputStream out, IProgressMonitor progressMonitor) throws CoreException {
SubMonitor monitor = SubMonitor.convert(progressMonitor);
try {
URL url = uri.toURL();
monitor.subTask(NLS.bind("Fetching {0}", url));
try {
InputStream in = url.openStream();
InputStream bufferedIn = new BufferedInputStream(in);
try {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = bufferedIn.read(buffer)) != -1) {
out.write(buffer, 0, len);
monitor.worked(1);
monitor.setWorkRemaining(10000);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
}
finally {
bufferedIn.close();
in.close();
}
}
catch (IOException e) {
throw toException(url, e);
}
}
catch (MalformedURLException e) {
throw toException(uri, e);
}
}
public long getLastModified(URI location, IProgressMonitor monitor) throws CoreException {
try {
URL url = location.toURL();
try {
return url.openConnection().getLastModified();
}
catch (IOException e) {
throw toException(url, e);
}
}
catch (MalformedURLException e) {
throw toException(location, e);
}
}
public InputStream stream(URI uri, IProgressMonitor monitor) throws CoreException {
try {
URL url = uri.toURL();
try {
InputStream in = url.openStream();
return in;
}
catch (IOException e) {
throw toException(url, e);
}
}
catch (MalformedURLException e) {
throw toException(uri, e);
}
}
private CoreException toException(URI uri, IOException e) throws CoreException {
String message = e.getMessage() != null ? e.getMessage() : "Unexpected error";
return new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, NLS.bind(
"Download of {0} failed: {1}", uri.getFragment(), message), e));
}
private CoreException toException(URL url, IOException e) throws CoreException {
String message = e.getMessage() != null ? e.getMessage() : "Unexpected error";
return new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, NLS.bind(
"Download of {0} failed: {1}", url, message), e));
}
}

View File

@@ -0,0 +1,151 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.internal.core.net;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.springsource.ide.eclipse.commons.internal.core.CorePlugin;
/**
* @author Steffen Pingel
*/
public class P2TransportService implements ITransportService {
private Object transport;
private Method downloadMethod;
private Method streamMethod;
private Method getLastModifiedMethod;
public P2TransportService() throws ClassNotFoundException {
// TODO e3.5 remove reflection
try {
Class<?> clazz;
try {
clazz = Class.forName("org.eclipse.equinox.internal.p2.repository.RepositoryTransport"); //$NON-NLS-1$
Method getInstanceMethod = clazz.getDeclaredMethod("getInstance"); //$NON-NLS-1$
transport = getInstanceMethod.invoke(null);
}
catch (ClassNotFoundException e) {
// the class moved to a different bundle in 3.7
transport = getTransport_e3_7();
clazz = transport.getClass();
}
downloadMethod = clazz.getDeclaredMethod("download", URI.class, OutputStream.class, IProgressMonitor.class); //$NON-NLS-1$
streamMethod = clazz.getDeclaredMethod("stream", URI.class, IProgressMonitor.class); //$NON-NLS-1$
getLastModifiedMethod = clazz.getDeclaredMethod("getLastModified", URI.class, IProgressMonitor.class); //$NON-NLS-1$
}
catch (LinkageError e) {
throw new ClassNotFoundException("Failed to load P2 transport", e); //$NON-NLS-1$
}
catch (Exception e) {
throw new ClassNotFoundException("Failed to load P2 transport", e); //$NON-NLS-1$
}
}
private static Object getTransport_e3_7() throws Exception {
// This line is here merely to make sure that the bundle gets activated
// before trying to use the service (to get rid of a race condition).
Class<?> clazz = Class.forName("org.eclipse.equinox.p2.core.IProvisioningAgent"); //$NON-NLS-1$
BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
ServiceReference serviceReference = bundleContext
.getServiceReference("org.eclipse.equinox.p2.core.IProvisioningAgent");
if (serviceReference != null) {
try {
Object agent = bundleContext.getService(serviceReference);
if (agent != null) {
Method getServiceMethod = agent.getClass().getDeclaredMethod("getService", String.class); //$NON-NLS-1$
return getServiceMethod.invoke(agent, "org.eclipse.equinox.internal.p2.repository.Transport");
}
}
finally {
bundleContext.ungetService(serviceReference);
}
}
throw new RuntimeException("Transport service not available");
}
private void convertException(InvocationTargetException e) throws CoreException {
if (e.getCause() instanceof CoreException) {
throw (CoreException) e.getCause();
}
else {
throw new CoreException(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, e.getCause().getMessage(),
e.getCause()));
}
}
public void download(URI uri, OutputStream out, IProgressMonitor monitor) throws CoreException {
try {
IStatus result = (IStatus) downloadMethod.invoke(transport, uri, out, monitor);
if (result.getSeverity() == IStatus.CANCEL) {
throw new OperationCanceledException();
}
if (!result.isOK()) {
throw new CoreException(result);
}
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof CoreException) {
throw (CoreException) e.getCause();
}
}
catch (IllegalArgumentException e) {
throw new RuntimeException(e);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public long getLastModified(URI location, IProgressMonitor monitor) throws CoreException {
try {
return (Long) getLastModifiedMethod.invoke(transport, location, monitor);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
catch (InvocationTargetException e) {
convertException(e);
}
// should never happen
throw new IllegalStateException();
}
public InputStream stream(URI uri, IProgressMonitor monitor) throws CoreException {
try {
return (InputStream) streamMethod.invoke(transport, uri, monitor);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
catch (InvocationTargetException e) {
convertException(e);
}
// should never happen
throw new IllegalStateException();
}
}

View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.springsource.ide.eclipse.commons.frameworks.core</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -0,0 +1,39 @@
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %pluginName
Bundle-SymbolicName: org.springsource.ide.eclipse.commons.frameworks.core;singleton:=true
Bundle-Version: 4.8.1.qualifier
Bundle-Activator: org.springsource.ide.eclipse.commons.frameworks.core.FrameworkCoreActivator
Bundle-Vendor: %providerName
Require-Bundle: org.eclipse.ui,
org.eclipse.jdt.core,
org.eclipse.core.resources,
org.eclipse.jdt.debug.ui,
org.apache.commons.io,
org.apache.commons.codec,
org.springsource.ide.eclipse.commons.livexp,
io.projectreactor.reactor-core;bundle-version="[3.3.1,3.3.2)",
org.reactivestreams.reactive-streams,
org.eclipse.jface.text
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Eclipse-LazyStart: true
Bundle-ActivationPolicy: lazy
Export-Package: org.springsource.ide.eclipse.commons.frameworks.core,
org.springsource.ide.eclipse.commons.frameworks.core.async,
org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager,
org.springsource.ide.eclipse.commons.frameworks.core.internal.cache,
org.springsource.ide.eclipse.commons.frameworks.core.internal.commands,
org.springsource.ide.eclipse.commons.frameworks.core.internal.java,
org.springsource.ide.eclipse.commons.frameworks.core.internal.plugins,
org.springsource.ide.eclipse.commons.frameworks.core.legacyconversion,
org.springsource.ide.eclipse.commons.frameworks.core.maintype,
org.springsource.ide.eclipse.commons.frameworks.core.util,
org.springsource.ide.eclipse.commons.frameworks.core.workspace
Bundle-Localization: plugin
Import-Package: org.eclipse.core.internal.runtime,
org.eclipse.core.runtime,
org.eclipse.core.runtime.jobs,
org.eclipse.core.runtime.preferences,
org.osgi.framework,
org.osgi.framework.wiring,
org.osgi.service.prefs

View File

@@ -0,0 +1,22 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>About Eclipse Integration Commons</title>
<meta name="author" content="Pivotal">
</head>
<body>
<h2>About Eclipse Integration Commons</h2>
<p>June 30, 2015</p>
<h3>Abstract</h3>
<p>The Eclipse Integration Commons project provides components that help
other projects to implement Eclipse-based tooling.</p>
<h3>License</h3>
<p>Pivotal Software, Inc. (“Pivotal”) makes available all content
in this download ("Content"). Unless otherwise indicated below, the
Content is provided to you under the terms and conditions of the Eclipse
Public License Version 1.0 ("EPL"). A copy of the EPL is available in
the file called license.txt. For purposes of the EPL, "Program" will
mean the Content.</p>
</body>
</html>

View File

@@ -0,0 +1,6 @@
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
plugin.properties,\
about.html

View File

@@ -0,0 +1,2 @@
pluginName=SpringSource Tool Suite Framework Support Core
providerName=Pivotal Software, Inc.

View File

@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot.ide</groupId>
<artifactId>org.springframework.boot.ide.servers</artifactId>
<version>4.8.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>org.springsource.ide.eclipse.commons.frameworks.core</artifactId>
<packaging>eclipse-plugin</packaging>
<name>org.springsource.ide.eclipse.commons.frameworks.core</name>
<build>
<plugins>
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>tycho-p2-plugin</artifactId>
<version>${tycho-version}</version>
<executions>
<execution>
<id>second-generate-p2-metadata</id>
<goals>
<goal>p2-metadata</goal>
</goals>
<phase>verify</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,12 @@
Important notes about dependencies for commons.frameworks.core
commons.FRAMEWORKS.core is dependended on by other framework tooling like GGTS, CloudFoundry tooling etc.
These tooling do not want to drag in dependencies on things like mylin, m2e etc. Generally only
dependencies on 'plain Eclipse' are allowed in commons fw core.
Since commons.core has dependencies on mylin, m2e etc. commons.frameworks.core should also *not*
dependend on commons.core.
However it is ok for commons.core (or really any other module) to depend on commons.fw.core.
commons.fw.core should be a 'leaf' in the dependency tree if ignore dependencies that are
commonly available in plain eclipse.

View File

@@ -0,0 +1,142 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
/**
* Utility methods to convert exceptions into other types of exceptions, status
* objects etc.
*
* Deprecated because this class was moved to livexp bundle. Use the moved class instead of this one.
*
* @author Kris De Volder
*/
@Deprecated
public class ExceptionUtil {
public static CoreException coreException(int severity, String msg) {
return coreException(status(severity, msg));
}
public static CoreException coreException(IStatus status) {
if (status==null) {
return coreException("Null status?");
}
Throwable e = status.getException();
if (e == null) {
return new CoreException(status);
}
else if (e instanceof CoreException) {
return (CoreException) e;
}
return new CoreException(status);
}
public static CoreException coreException(String msg) {
return coreException(IStatus.ERROR, msg);
}
public static CoreException coreException(Throwable e) {
if (e instanceof CoreException) {
return (CoreException) e;
}
else {
return coreException(status(e));
}
}
public static Throwable getDeepestCause(Throwable e) {
Throwable cause = e;
Throwable parent = e.getCause();
while (parent != null && parent != e) {
cause = parent;
parent = cause.getCause();
}
return cause;
}
public static String getMessage(Throwable e) {
// The message of nested exception is usually more interesting than the
// one on top.
Throwable cause = getDeepestCause(e);
String msg = cause.getClass().getSimpleName() + ": " + cause.getMessage();
return msg;
}
public static IllegalStateException notImplemented(String string) {
return new IllegalStateException("Not implemented: " + string);
}
public static IStatus status(int severity, String msg) {
return new Status(severity, FrameworkCoreActivator.PLUGIN_ID, msg);
}
public static IStatus status(Throwable e) {
return status(IStatus.ERROR, e);
}
public static IStatus status(int severity, Throwable e) {
if (e instanceof OperationCanceledException || e instanceof InterruptedException) {
return Status.CANCEL_STATUS;
}
if (e instanceof CoreException) {
IStatus status = ((CoreException) e).getStatus();
if (status != null && status.getSeverity() == severity) {
Throwable ee = status.getException();
if (ee != null) {
return status;
}
}
}
return new Status(severity, FrameworkCoreActivator.PLUGIN_ID, getMessage(e), e);
}
public static IStatus status(String msg) {
return status(IStatus.ERROR, msg);
}
public static final IStatus OK_STATUS = status(IStatus.OK, "");
public static Exception exception(Throwable e) {
if (e instanceof Exception) {
return (Exception)e;
} else {
return coreException(e);
}
}
public static RuntimeException unchecked(Exception e) {
return new RuntimeException(e);
}
public static String stacktrace() {
return stacktrace(new Exception("Stacktrace"));
}
public static String stacktrace(Exception exception) {
ByteArrayOutputStream dump = new ByteArrayOutputStream();
PrintStream out = new PrintStream(dump);
try {
exception.printStackTrace(out);
} finally {
out.close();
}
return dump.toString();
}
}

View File

@@ -0,0 +1,116 @@
/*******************************************************************************
* Copyright (c) 2012 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core;
import java.net.URISyntaxException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
import org.springsource.ide.eclipse.commons.frameworks.core.legacyconversion.IConversionConstants;
/**
* @author Nieraj Singh
* @author Christian Dupuis
* @since 2.5.0
*/
public class FrameworkCoreActivator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.springsource.ide.eclipse.commons.frameworks.core"; //$NON-NLS-1$
// The shared instance
private static FrameworkCoreActivator plugin;
/**
* The constructor
*/
public FrameworkCoreActivator() {
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static FrameworkCoreActivator getDefault() {
return plugin;
}
public static void logError(String message, Throwable exception) {
getDefault().getLog().log(createErrorStatus(message, exception));
}
public static void log(Throwable e) {
getDefault().getLog().log(createErrorStatus(e.getMessage(), e));
}
public static IStatus createErrorStatus(String message, Throwable exception) {
if (message == null) {
message = "";
}
return new Status(IStatus.ERROR, PLUGIN_ID, 0, message, exception);
}
public static IStatus createWarningStatus(String message,
Throwable exception) {
if (message == null) {
message = "";
}
return new Status(IStatus.WARNING, PLUGIN_ID, 0, message, exception);
}
/**
* Returns true if the plugin id has not yet run legacy conversion for this workspace yet
* @param pluginid plugin id to check
* @return true iff legacy conversion has not taken place for this plugin, but it has for the workspace as a whole
*/
public boolean shouldMigratePlugin(String pluginid) {
if (getPreferenceStore().getBoolean(IConversionConstants.LEGACY_MIGRATION_ALREADY_DONE)) {
String plugins = getPreferenceStore().getString(IConversionConstants.LEGACY_MIGRATION_PLUGINS);
return plugins.contains("," + pluginid + ","); //$NON-NLS-1$ //$NON-NLS-2$
} else {
// workspace legacy migration has not yet been successfully performed
return false;
}
}
public void registerPluginMigrationComplete(String pluginid) {
String plugins = getPreferenceStore().getString(IConversionConstants.LEGACY_MIGRATION_PLUGINS);
plugins += "," + pluginid + ","; //$NON-NLS-1$ //$NON-NLS-2$
getPreferenceStore().putValue(IConversionConstants.LEGACY_MIGRATION_PLUGINS, plugins);
}
}

View File

@@ -0,0 +1,160 @@
/*******************************************************************************
* Copyright (c) 2016, 2019 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
import java.time.Duration;
import java.util.Collection;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.springsource.ide.eclipse.commons.frameworks.core.internal.cache.Cache;
import org.springsource.ide.eclipse.commons.frameworks.core.internal.cache.LimitedTimeCache;
import reactor.core.publisher.Flux;
/**
* COPIED FROM:
* org.springframework.ide.eclipse.boot.properties.editor.metadata.CachingValueProvider
* <p>
* TODO: refactor so that there is only one CachingValueProvider that can be reused
* <p>
* A abstract {@link ValueProviderStrategy} that is mean to help speedup successive invocations of
* content assist with a similar 'query' string.
* <p>
* This implementation is meant to be used for providers that use potentially lengthy/expensive searches
* to determine hints. Since content assist hints are requested by Eclipse CA framework directly on
* the UI thread, they can not simply perform a lengthy search and block UI thread until it finished.
* <p>
* This implementation therefore does the following:
* <ul>
* <li>Limit the duration of time spent on the UI thread.
* <li>Cache results of searches for a limited time.
* <li>Speedup queries for successive queries by using the already cached result of a similar (prefix) query.
* <li>When the time spent on UI thread waiting for a current search exceeds the allowed time limit,
* return immediately with whatever results have been found so far.
* </ul>
*
* TODO: rather than an abstract class this should really be 'Wrapper' class that delegates to another
* {@link ValueProviderStrategy} and adds a cache in front of it.
*
* @author Kris De Volder
*/
public abstract class CachingValueProvider<T> {
// protected static final boolean DEBUG = (""+Platform.getLocation()).contains("kdvolder");
//
// protected static void debug(String string) {
// if (DEBUG) {
// System.out.println(string);
// }
// }
private static final Duration DEFAULT_TIMEOUT = Duration.ofMillis(1000);
/**
* Content assist is called inside UI thread and so doing something lenghty things
* like a JavaSearch will block the UI thread completely freezing the UI. So, we
* only return as many results as can be obtained within this hard TIMEOUT limit.
*/
public static Duration TIMEOUT = DEFAULT_TIMEOUT;
/**
* The maximum number of results returned for a single request. Used to limit the
* values that are cached per entry.
*/
private int MAX_RESULTS = 500;
private Cache<String, CacheEntry> cache = createCache();
private class CacheEntry {
boolean isComplete = false;
int count = 0;
Flux<T> values;
public CacheEntry(String query, Flux<T> producer) {
values = producer
.doOnNext((e) -> {
count++;
// debug("onNext["+query+":"+count+"]: "+e.getValue().toString());
})
.doOnComplete(() -> {
// debug("onComplete["+query+":"+count+"]");
isComplete = true;
})
.take(MAX_RESULTS)
.cache(MAX_RESULTS);
values.subscribe(); // create infinite demand so that we actually force cache entries to be fetched upto the max.
}
@Override
public String toString() {
return "CacheEntry [isComplete=" + isComplete + ", count=" + count + "]";
}
}
public final Flux<T> getValues(IType type, IJavaSearchScope scope) {
// debug("CA query: "+query);
String key = key(type);
CacheEntry cached = cache.get(key);
if (cached==null) {
cache.put(key, cached = new CacheEntry(key, getValuesIncremental(type, scope)));
}
return cached.values;
}
public final Collection<T> getValuesNow(IType type, IJavaSearchScope scope) {
return this.getValues(type, scope)
.take(CachingValueProvider.TIMEOUT)
.collectList()
.block();
}
/**
* Tries to use an already cached, complete result for a query that is a prefix of the current query to speed things up.
* <p>
* Falls back on doing a full-blown search if there's no usable 'prefix-query' in the cache.
*/
private Flux<T> getValuesIncremental(IType expectedType, IJavaSearchScope scope) {
// debug("trying to solve "+query+" incrementally");
CacheEntry cached = cache.get(key(expectedType));
if (cached!=null) {
System.out.println("cached "+expectedType+": "+cached);
if (cached.isComplete) {
// debug("filtering "+subquery+" -> "+query);
return cached.values
// .doOnNext((hint) -> debug("filter["+query+"]: "+hint.getValue()))
// .filter((hint) -> 0!=FuzzyMatcher.matchScore(query, hint.getValue().toString()))
;
} else {
// debug("subquery "+subquery+" cached but is incomplete");
}
}
// debug("full search for: "+query);
return getValuesAsycn(expectedType, scope);
}
protected abstract Flux<T> getValuesAsycn(IType expectedType, IJavaSearchScope scope);
private String key(IType expectedType) {
return expectedType == null ? null : expectedType.getFullyQualifiedName();
}
protected <K,V> Cache<K,V> createCache() {
return new LimitedTimeCache<>(Duration.ofMinutes(1));
}
public static void restoreDefaults() {
TIMEOUT = DEFAULT_TIMEOUT;
}
}

View File

@@ -0,0 +1,46 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
import java.util.function.Function;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchPattern;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* Searches for all constructors for a given type.
*/
public class ConstructorSearchValueProvider extends CachingValueProvider<JavaConstructorHint> {
@Override
public Flux<JavaConstructorHint> getValuesAsycn(IType type, IJavaSearchScope scope) {
try {
return new FluxConstructorSearch()
.scope(scope)
.pattern("*")
.patternRule(SearchPattern.R_PATTERN_MATCH)
.search()
.flatMap(getPostProcessor());
} catch (Exception e) {
return Flux.error(e);
}
}
protected Function<JavaConstructorHint, Mono<JavaConstructorHint>> getPostProcessor() {
return (match) -> {
return Mono.justOrEmpty(match);
};
}
}

View File

@@ -0,0 +1,186 @@
/*******************************************************************************
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.eclipse.jdt.internal.core.search.BasicSearchEngine;
import org.eclipse.jdt.internal.core.search.IRestrictedAccessConstructorRequestor;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.ReplayProcessor;
import reactor.util.concurrent.Queues;
/**
*
* NOTE:
* This is derived from:
* org.springsource.ide.eclipse.commons.frameworks.core.async.FluxJdtSearch
* <p>
* TODO:
* There should only one reusable Flux JDT Search. Refactor so that FluxJdtSearch and FluxConstructorSearch
* share a common base
* <p>
* Helper class to perform a search using Eclipse JDT search engine returning
* the search results as a Flux.
* <p>
* The conversion from Eclipse callback style using {@link SearchRequestor} involves
* a buffer that allows subscribers to attach to the Flux after the search has already
* started without loosing results. However, if the buffer overflows then results will
* be lost.
* <p>
* Clients should therfore start consuming the results as soon as possible and avoid
* blocking the pipeline to avoid the loss of results they may care about.
* <p>
* Alternatively, client can specify a large enough buffer size so that the buffer can hold
* at least as many results as the client may care to retrieve. This will allow the returned
* Flux to be reused any number of times without timing constraints, provided that the
* consumer never requests more than the number of buffered results.
*
* @author Kris De Volder
*/
@SuppressWarnings("restriction")
public class FluxConstructorSearch {
private static final boolean DEBUG = (""+Platform.getLocation()).contains("kdvolder");
private static void debug(String string) {
if (DEBUG) {
System.out.println(string);
}
}
private BasicSearchEngine engine = new BasicSearchEngine();
private IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
private String pattern = null;
private int patternRule = SearchPattern.R_PATTERN_MATCH;
private int bufferSize = Queues.SMALL_BUFFER_SIZE;
private boolean useSystemJob = false;
private int jobPriority = Job.INTERACTIVE;
public FluxConstructorSearch engine(BasicSearchEngine engine) {
this.engine = engine;
return this;
}
public FluxConstructorSearch scope(IJavaSearchScope scope) {
this.scope = scope;
return this;
}
public FluxConstructorSearch bufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
public FluxConstructorSearch patternRule(int patternRule) {
this.patternRule = patternRule;
return this;
}
public FluxConstructorSearch pattern(String pattern) {
this.pattern = pattern;
return this;
}
/**
* Implementation of {@link SearchRequestor} that emits search results to an {@link ReplayProcessor}
* with replay capability.
*
* @author Kris De Volder
*/
class FluxSearchRequestor {
private boolean isCanceled = false;
private ReplayProcessor<JavaConstructorHint> emitter = ReplayProcessor.<JavaConstructorHint>create(bufferSize);
private Flux<JavaConstructorHint> flux = emitter.doOnCancel(() -> isCanceled=true);
public Flux<JavaConstructorHint> asFlux() {
return flux;
}
public void acceptSearchMatch(JavaConstructorHint match) {
if (isCanceled) {
debug("!!!! canceling search !!!!");
//Stop searching
throw new OperationCanceledException();
}
emitter.onNext(match);
}
public void cancel() {
isCanceled = true;
}
public void done() {
emitter.onComplete();
}
}
public Flux<JavaConstructorHint> search() {
validate();
if (scope==null) {
return Flux.empty();
}
final FluxSearchRequestor requestor = new FluxSearchRequestor();
Job job = new Job("Search for "+pattern) {
@Override
protected IStatus run(IProgressMonitor monitor) {
long start = System.currentTimeMillis();
debug("Starting search for '"+pattern+"'");
try {
engine.searchAllConstructorDeclarations(null, pattern.toCharArray(), patternRule,
scope, new IRestrictedAccessConstructorRequestor() {
@Override
public void acceptConstructor(int modifiers, char[] simpleTypeName, int parameterCount,
char[] signature, char[][] parameterTypes, char[][] parameterNames, int typeModifiers,
char[] packageName, int extraFlags, String path, AccessRestriction access) {
requestor.acceptSearchMatch(JavaConstructorHint.asHint(modifiers, simpleTypeName, parameterCount, signature, parameterTypes, parameterNames, typeModifiers, packageName, extraFlags, path, access));
}
}, IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor);
requestor.done();
} catch (Exception e) {
debug("Canceled search for: "+pattern);
debug(" exception: "+ExceptionUtil.getMessage(e));
long duration = System.currentTimeMillis() - start;
debug(" duration: "+duration+" ms");
requestor.cancel();
}
return Status.OK_STATUS;
}
};
job.setSystem(useSystemJob);
job.setPriority(jobPriority);
job.schedule();
return requestor.asFlux();
}
private void validate() {
Assert.isNotNull(engine, "engine");
Assert.isNotNull(pattern, "pattern");
Assert.isLegal(bufferSize > 0);
}
}

View File

@@ -0,0 +1,229 @@
/*******************************************************************************
* Copyright (c) 2016, 2018 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchMatch;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.core.search.SearchRequestor;
import org.springsource.ide.eclipse.commons.frameworks.core.FrameworkCoreActivator;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.ReplayProcessor;
import reactor.util.concurrent.Queues;
/**
* Helper class to perform a search using Eclipse JDT search engine returning
* the search results as a Flux.
* <p>
* The conversion from Eclipse callback style using {@link SearchRequestor} involves
* a buffer that allows subscribers to attach to the Flux after the search has already
* started without loosing results. However, if the buffer overflows then results will
* be lost.
* <p>
* Clients should therfore start consuming the results as soon as possible and avoid
* blocking the pipeline to avoid the loss of results they may care about.
* <p>
* Alternatively, client can specify a large enough buffer size so that the buffer can hold
* at least as many results as the client may care to retrieve. This will allow the returned
* Flux to be reused any number of times without timing constraints, provided that the
* consumer never requests more than the number of buffered results.
*
* @author Kris De Volder
*/
public class FluxJdtSearch {
private static final boolean DEBUG = (""+Platform.getLocation()).contains("kdvolder");
private static void debug(String string) {
if (DEBUG) {
System.out.println(string);
}
}
private SearchEngine engine = new SearchEngine();
private IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
private SearchPattern pattern = null;
private SearchParticipant[] participants = new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
private int bufferSize = Queues.SMALL_BUFFER_SIZE;
private boolean useSystemJob = false;
private int jobPriority = Job.INTERACTIVE;
public FluxJdtSearch engine(SearchEngine engine) {
this.engine = engine;
return this;
}
public FluxJdtSearch scope(IJavaSearchScope scope) {
this.scope = scope;
return this;
}
public FluxJdtSearch scope(IProject project) throws JavaModelException {
return scope(JavaCore.create(project));
}
public FluxJdtSearch scope(IJavaProject project) throws JavaModelException {
return scope(searchScope(project));
}
public FluxJdtSearch bufferSize(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
public FluxJdtSearch pattern(SearchPattern pattern) {
this.pattern = pattern;
return this;
}
/**
* Create a search scope that includes a given project and its dependencies.
*/
public static IJavaSearchScope searchScope(IJavaProject javaProject, boolean includeBinaries) throws JavaModelException {
int includeMask =
IJavaSearchScope.REFERENCED_PROJECTS |
IJavaSearchScope.SOURCES;
if (includeBinaries) {
includeMask = includeMask | IJavaSearchScope.APPLICATION_LIBRARIES;
}
return SearchEngine.createJavaSearchScope(new IJavaElement[] {javaProject}, includeMask);
}
public static IJavaSearchScope searchScope(IJavaProject javaProject) throws JavaModelException {
return searchScope(javaProject, true);
}
/**
* Implementation of {@link SearchRequestor} that emits search results to an {@link ReplayProcessor}
* with replay capability.
*
* @author Kris De Volder
*/
class FluxSearchRequestor extends SearchRequestor {
private boolean isCanceled = false;
private ReplayProcessor<SearchMatch> emitter = ReplayProcessor.<SearchMatch>create(bufferSize);
private Flux<SearchMatch> flux = emitter.doOnCancel(() -> isCanceled=true);
public Flux<SearchMatch> asFlux() {
return flux;
}
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (isCanceled) {
debug("!!!! canceling search !!!!");
//Stop searching
throw new OperationCanceledException();
}
emitter.onNext(match);
}
public void cancel() {
isCanceled = true;
}
public void done() {
emitter.onComplete();
}
}
protected SearchEngine searchEngine() {
return new SearchEngine();
}
protected SearchParticipant[] participants() {
return new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()};
}
public Flux<SearchMatch> search() {
validate();
if (scope==null) {
return Flux.empty();
}
final FluxSearchRequestor requestor = new FluxSearchRequestor();
Job job = new Job("Search for "+pattern) {
@Override
protected IStatus run(IProgressMonitor monitor) {
long start = System.currentTimeMillis();
debug("Starting search for '"+pattern+"'");
try {
searchEngine().search(pattern, participants, scope, requestor, monitor);
requestor.done();
} catch (Exception e) {
debug("Canceled search for: "+pattern);
debug(" exception: "+ExceptionUtil.getMessage(e));
long duration = System.currentTimeMillis() - start;
debug(" duration: "+duration+" ms");
requestor.cancel();
}
return Status.OK_STATUS;
}
};
job.setSystem(useSystemJob);
job.setPriority(jobPriority);
job.schedule();
return requestor.asFlux();
}
private void validate() {
Assert.isNotNull(engine, "engine");
//We allow scope to be set to null. This means there's no valid scope (or empty scope)
// and the search should just return no results.
// Assert.isNotNull(scope, "scope");
Assert.isNotNull(pattern, "pattern");
Assert.isNotNull(participants, "participants");
Assert.isLegal(bufferSize > 0);
}
public static IJavaSearchScope workspaceScope(boolean includeBinaries) {
if (includeBinaries) {
return SearchEngine.createWorkspaceScope();
} else {
List<IJavaProject> projects = new ArrayList<>();
for (IProject p : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
try {
if (p.isAccessible() && p.hasNature(JavaCore.NATURE_ID)) {
IJavaProject jp = JavaCore.create(p);
projects.add(jp);
}
} catch (Exception e) {
FrameworkCoreActivator.log(e);
}
}
int includeMask = IJavaSearchScope.SOURCES;
return SearchEngine.createJavaSearchScope(projects.toArray(new IJavaElement[projects.size()]), includeMask);
}
}
}

View File

@@ -0,0 +1,57 @@
/*******************************************************************************
* Copyright (c) 2017 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
import org.eclipse.jdt.internal.compiler.env.AccessRestriction;
@SuppressWarnings("restriction")
/**
* Contains information required for JDT's BasicSearchEngine to search for constructors. Note that this is to support
* "legacy" implementation around an internal JDT search engine that allows for searching constructors
*
*
*/
public class JavaConstructorHint {
public int modifiers;
public char[] simpleTypeName;
public int parameterCount;
public char[] signature;
public char[][] parameterTypes;
public char[][] parameterNames;
public int typeModifiers;
public char[] packageName;
public int extraFlags;
public String path;
public AccessRestriction access;
public JavaConstructorHint(int modifiers, char[] simpleTypeName, int parameterCount, char[] signature,
char[][] parameterTypes, char[][] parameterNames, int typeModifiers, char[] packageName, int extraFlags,
String path, AccessRestriction access) {
this.modifiers = modifiers;
this.simpleTypeName = simpleTypeName;
this.parameterCount = parameterCount;
this.signature = signature;
this.parameterTypes = parameterTypes;
this.parameterNames = parameterNames;
this.typeModifiers = typeModifiers;
this.packageName = packageName;
this.extraFlags = extraFlags;
this.path = path;
this.access = access;
}
public static JavaConstructorHint asHint(int modifiers, char[] simpleTypeNames, int parameterCount,
char[] signatures, char[][] parameterTypes, char[][] parameterNames, int typeModifiers, char[] packageNames,
int extraFlags, String path, AccessRestriction access) {
return new JavaConstructorHint(modifiers, simpleTypeNames, parameterCount, signatures, parameterTypes,
parameterNames, typeModifiers, packageNames, extraFlags, path, access);
}
}

View File

@@ -0,0 +1,36 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
/**
* An object implementing this interface represents some entity awaiting
* the result of an asynchronous computation. The result should
* either be a value passed to the 'resolve' method (if the computation
* succeeded) or an Exception, passed to the 'reject' method (if the
* compuration failed).
* <p>
* Generally a computation can only complete by a call to resolve or
* reject.
* <p>
* Implementations of Resolvable may rely on this assumption to free up
* resources when resolve/reject are called.
* <p>
* Generally, implementations of {@link Resolvable} should guard against
* bad/buggy callers and by disregarding additional calls to resolve/reject
* after the first.
*
*
* @author Kris De Volder
*/
public interface Resolvable<T> {
void resolve(T value);
void reject(Exception e);
}

View File

@@ -0,0 +1,104 @@
/*******************************************************************************
* Copyright (c) 2015 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.async;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A java.util.concurrent.Future which isn't created by some
* executor, but rather just an object which is awaiting some kind
* of event to resolve or reject it.
*
* Deprecated. Now that we have Java 8 you can use {@link CompletableFuture}
*
* @author Kris De Volder
*/
@Deprecated
public class ResolvableFuture<T> implements Future<T>, Resolvable<T> {
private boolean isPending = true;
private Exception exception;
private T value;
public synchronized void resolve(T v) {
this.value = v;
this.isPending = false;
this.notifyAll();
}
public synchronized void reject(Exception e) {
if (!isPending) {
this.exception = e;
this.isPending = false;
this.notifyAll();
}
}
@Override
public synchronized boolean cancel(boolean mayInterruptIfRunning) {
if (isPending) {
reject(new CancellationException());
return true;
}
return false;
}
@Override
public boolean isCancelled() {
return exception instanceof CancellationException;
}
@Override
public synchronized boolean isDone() {
return !isPending;
}
@Override
public synchronized T get() throws InterruptedException, ExecutionException {
while (isPending) {
wait();
}
if (isPending) {
throw new IllegalStateException("Still pending, can't fetch value or exception");
}
if (exception!=null) {
throw new ExecutionException(exception);
} else {
return value;
}
}
@Override
public synchronized T get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
long startTime = System.currentTimeMillis();
long endTime = startTime + unit.toMillis(timeout);
long waitTime;
while (isPending
&& 0 < (waitTime = endTime - System.currentTimeMillis())) {
wait(waitTime);
}
if (isPending) {
throw new TimeoutException();
}
if (exception!=null) {
throw new ExecutionException(exception);
} else {
return value;
}
}
}

View File

@@ -0,0 +1,287 @@
/*******************************************************************************
* Copyright (c) 2012, 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.URIUtil;
import org.eclipse.swt.widgets.Display;
import org.springsource.ide.eclipse.commons.frameworks.core.ExceptionUtil;
import org.springsource.ide.eclipse.commons.frameworks.core.FrameworkCoreActivator;
import org.springsource.ide.eclipse.commons.frameworks.core.util.FileUtil;
/**
* Manages a cache of downloaded content.
*
* @author Kris De Volder
*/
public class DownloadManager {
/**
* An instance of this interface represent an action to execute on a downloaded
* File. The action may indicate failure by throwing an exception or by
* returning false. A failed action may trigger the DownloadManager to
* clear the cache and try again for a limited number of times.
*/
public interface DownloadRequestor {
void exec(File downloadedFile) throws Exception;
}
/**
* An instance of this class represents some type of service able to fetch the
* content data.
*/
public interface DownloadService {
void fetch(URL url, OutputStream writeTo) throws IOException;
}
private final File cacheDirectory;
private final DownloadService downloader;
private boolean deleteCacheOnDispose = false;
private boolean allowUIThread = false;
private int tries = 5; //5 retries by default
private long retryInterval = 0; //no wait between retries by default.
public DownloadManager(DownloadService downloader, File cacheDir) throws IOException {
if (cacheDir==null) {
cacheDir = FileUtil.createTempDirectoryWithTimestamp("downloadCache");
this.deleteCacheOnDispose = true; // This dir can not be used by anynone after this DLM is diposed so better delete it.
}
if (downloader==null) {
downloader = new SimpleDownloadService();
}
this.downloader = downloader;
this.cacheDirectory = cacheDir;
if (!cacheDir.isDirectory()) {
Assert.isTrue(cacheDir.mkdirs(), "Couldn't create cache directory at "+cacheDir);
}
}
public DownloadManager clearCache() {
FileUtils.deleteQuietly(cacheDirectory);
cacheDirectory.mkdirs();
return this;
}
/**
* Deprecated use one of the other contructors (probably you want to use
* the one that takes a {@link URLConnectionFactory} if you where using
* this one.
*/
@Deprecated
public DownloadManager() throws IOException {
this(new URLConnectionFactory());
}
/**
* Create a Default downloadmanager. This downloadmanager does not use authentication and
* simply uses standard JavaApi to fetch url content.
* <p>
* A new temp directory is created to use as the cache directory.
* <p>
* When this DownloadManager is disposed the cache directory is deleted (since the next
* DownloadManager created in this way will use a different cache dir anyway there isn't
* much use leaving it around).
*/
public DownloadManager(URLConnectionFactory urlConnectionFactory) throws IOException {
this(new SimpleDownloadService(urlConnectionFactory), null);
this.deleteCacheOnDispose = true;
}
/**
* This method is deprecated, please use doWithDownload to provide proper recovery
* for cache corruption.
*/
@Deprecated
public File downloadFile(DownloadableItem item) throws URISyntaxException, FileNotFoundException, CoreException, IOException, UIThreadDownloadDisallowed {
File target = getLocalLocation(item);
if (target.exists()) {
return target;
}
if (!allowUIThread && Display.getCurrent()!=null) {
throw new UIThreadDownloadDisallowed("Don't call download manager from the UI Thread unless the data is already cached.");
}
//
// );
//It is important not to lock the UI thread for downloads!!!
// If the UI thread is well behaved, we assume it will be careful not to call this method unless the
// content is already cached. So once we get past the exists check it is ok to grab the lock.
synchronized (this) {
//It is possible that multiple thread where waiting to enter here... only one of them should proceed
// to actually download. So make sure to retest the target.exists() condition to avoid multiple downloads
if (target.exists()) {
return target;
}
if (!cacheDirectory.exists()) {
cacheDirectory.mkdirs();
}
File targetPart = new File(target.toString()+".part");
FileOutputStream out = new FileOutputStream(targetPart);
try {
URL url = item.getURL();
System.out.println("Downloading " + url + " to " + target);
downloader.fetch(url, out);
}
finally {
out.close();
}
if (!targetPart.renameTo(target)) {
throw new IOException("Error while renaming " + targetPart + " to " + target);
}
return target;
}
}
/**
* Get the local location of given item. Note that the item may or may not yet be downloaded so
* there are no guarantees there is anything meaningful to be found there.
*/
public File getLocalLocation(DownloadableItem item) {
URL url = item.getURL();
String protocol = url.getProtocol();
try {
if ("file".equals(protocol)) {
//already local, so don't bother downloading.
return new File(URIUtil.toURI(url));
}
} catch (URISyntaxException e) {
FrameworkCoreActivator.log(e);
}
String filename = item.getFileName();
File target = new File(cacheDirectory, filename);
return target;
}
/**
* This method tries to download or fetch a File from the cache, then passes the
* downloaded file to the DownloadRequestor.
* <p>
* If the requestor fails to properly execute on the downloaded file, the cache
* will be presumed to be corrupt. The file will be deleted from the cache
* and the download will be tried again. (for a limited number of times)
*/
public void doWithDownload(DownloadableItem target, DownloadRequestor action) throws Exception {
int tries = getTries(); // try at most X times
Throwable e = null;
File downloadedFile = null;
do {
tries--;
try {
downloadedFile = downloadFile(target);
action.exec(downloadedFile);
return; // action succeeded without exceptions
} catch (UIThreadDownloadDisallowed caught) {
//No sense retrying this as it will just fail again...
throw caught;
} catch (Throwable caught) {
FrameworkCoreActivator.log(caught);
//Presume the cache may be corrupt!
//System.out.println("Delete corrupt download: "+downloadedFile);
if (downloadedFile!=null) {
downloadedFile.delete();
downloadedFile = null;
}
e = caught;
if (tries>0 && retryInterval>0) {
Thread.sleep(retryInterval);
}
}
} while (tries>0);
//Can only get here if action failed to execute on downloaded file...
//thus, e can not be null.
throw ExceptionUtil.exception(e);
}
/**
* @since 3.6.3
*/
public int getTries() {
return tries;
}
/**
* Sets the maximum number of times DownloadManager will try and retyr to fetch
* a failed download. Note that the first try also counts. So if 'tries' is
* set to 3 then a failed download will be retried upto 2 times. I.e. one
* try and then 2 retries.
*
* @since 3.6.3
*/
public DownloadManager setTries(int r) {
//Setting to 0 is not sensible because it would mean to just fail without even trying.
Assert.isLegal(r>1);
this.tries = r;
return this;
}
/**
* Sets the time in milliseconds to wait between retries. The default is 0 meaning no
* wait.
*
* @since 3.6.3
*/
public void setRetryInterval(long retryInterval) {
Assert.isLegal(retryInterval>=0);
this.retryInterval = retryInterval;
}
/**
* @since 3.6.3
*/
public long getRetryInterval(long retryInterval) {
return retryInterval;
}
public File getCacheDir() {
return cacheDirectory;
}
public boolean isDownloaded(DownloadableItem item) {
File target = getLocalLocation(item);
return target!=null && target.exists();
}
/**
* Dispose this download manager. Optionally delete its cache directory as well.
*/
public void dispose() {
if (deleteCacheOnDispose) {
FileUtils.deleteQuietly(cacheDirectory);
deleteCacheOnDispose = false;
}
}
/**
* If this is false, an exception will be thrown if download is attempted on
* the UI thread. The default value is true.
*/
public DownloadManager allowUIThread(boolean allow) {
allowUIThread = allow;
return this;
}
}

View File

@@ -0,0 +1,153 @@
/*******************************************************************************
* Copyright (c) 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager;
import java.io.File;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.springsource.ide.eclipse.commons.frameworks.core.ExceptionUtil;
import org.springsource.ide.eclipse.commons.frameworks.core.FrameworkCoreActivator;
import org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager.DownloadManager.DownloadRequestor;
/**
* A DownloadableItem is something that can be downloaded and
* stored in the local file system as a file.
*
* @author Kris De Volder
*/
public class DownloadableItem {
private final URL url;
protected final DownloadManager downloader;
private String name; //optional name. If set this name will be used as filename in the cache otherwise
// suitable name will be computed.
protected IStatus downloadStatus = Status.OK_STATUS; //error message if download failed. Otherwise contains 'OK'.
public DownloadableItem(URL url, DownloadManager downloader) {
this.url = url;
this.downloader = downloader;
}
public void setFileName(String n) {
this.name = n;
}
/**
* A downloadable item must provide a URI where its contents can be fetched from.
*/
public URL getURL() {
return url;
}
/**
* Force the item to be downloaded to a local File. If an item is already downloaded
* the cached local file will be returned immediately. Otherwise the method will block
* until the download is complete or an error occurs.
*/
public File getFile() throws Exception {
try {
final File[] fileBox = new File[1];
downloader.doWithDownload(this, new DownloadRequestor() {
public void exec(File downloadedFile) throws Exception {
fileBox[0] = downloadedFile;
//TODO; validate file contents?
}
});
downloadStatus = Status.OK_STATUS;
return fileBox[0];
} catch (UIThreadDownloadDisallowed e) {
//Shouldn't affect download status since it means download was not attempted
throw e;
} catch (Exception e) {
downloadStatus = error(ExceptionUtil.getMessage(e));
throw e;
}
}
protected IStatus error(String message) {
return new Status(IStatus.ERROR, FrameworkCoreActivator.PLUGIN_ID, message);
}
/**
* A downloadable item must provide a filename where its cached downloaded contents
* should be stored. The name must uniquely identify the downloadable item
* within the scope of the DownloadManager used to download this item.
* <p>
* The name must also be a legal file name on the current OS.
* <p>
* A default implementation is provided that uses sha1 and Base64 encoding
* to generate a name from the uri.
* <p>
* These generated names are not guaranteed to be unique, but the chance of
* a collisions is astronomically small.
*/
protected String getFileName() {
if (name==null) {
try {
MessageDigest sha1encoder = MessageDigest.getInstance("sha1");
byte[] bytes = sha1encoder.digest((""+getURL()).getBytes());
name = new String(Base64.encodeBase64(bytes));
name = name.replace('/', '_'); //slashes are trouble in file names.
} catch (NoSuchAlgorithmException e) {
//This should not be possible
throw new Error(e);
}
}
return name;
}
@Override
public String toString() {
return url.toString();
}
public boolean isDownloaded() {
return downloader!=null && downloader.isDownloaded(this);
}
/**
* Error message if download failed. Other
* @return
*/
public IStatus getDownloadStatus() {
return downloadStatus;
}
public void clearCache() {
//Take care not to delete the original file if was local to begin with (in that case we don't
// copy it into the cache dir so there is no cache to clear!
if (url!=null && !"file".equals(url.getProtocol())) {
//Avoid race conditions when someone is downloading this item at the moment.
synchronized (downloader) {
File localFile = downloader.getLocalLocation(this);
FileUtils.deleteQuietly(localFile);
}
}
}
/**
* Determine the location to unzip to (without actually doing any unzipping).
*/
public File getUnzipDir() {
String fileName = getFileName();
Assert.isTrue(fileName.endsWith(".zip"));
File unzipLocation = new File(downloader.getCacheDir(), fileName.substring(0, fileName.length()-4));
return unzipLocation;
}
}

View File

@@ -0,0 +1,70 @@
/*******************************************************************************
* Copyright (c) 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager.DownloadManager.DownloadService;
import org.springsource.ide.eclipse.commons.frameworks.core.util.IOUtil;
public class SimpleDownloadService implements DownloadService {
private final URLConnectionFactory connectionFactory;
private static final boolean DEBUG = false;
public SimpleDownloadService() {
this(new URLConnectionFactory());
}
public SimpleDownloadService(URLConnectionFactory urlConnectionFactory) {
this.connectionFactory = urlConnectionFactory;
}
//@Override
public void fetch(URL url, OutputStream writeTo) throws IOException {
URLConnection conn = null;
InputStream input = null;
try {
conn = connectionFactory.createConnection(url);
conn.connect();
if (DEBUG) {
System.out.println(">>> "+url);
Map<String, List<String>> headers = conn.getHeaderFields();
for (Entry<String, List<String>> header : headers.entrySet()) {
System.out.println(header.getKey()+":");
for (String value : header.getValue()) {
System.out.println(" "+value);
}
}
System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
}
input = conn.getInputStream();
IOUtil.pipe(input, writeTo);
} finally {
if (input!=null) {
try {
input.close();
} catch (Throwable e) {
//ignore.
}
}
}
}
}

View File

@@ -0,0 +1,29 @@
/*******************************************************************************
* Copyright (c) 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager;
/**
* Exception thrown by the DownloadManager when a download operation
* is attempted in the UIThread. This is bad practice as it will
* freeze the UI until the download is complete.
*
* @author Kris De Volder
*/
public class UIThreadDownloadDisallowed extends Exception {
public UIThreadDownloadDisallowed(String string) {
super(string);
}
private static final long serialVersionUID = 1L;
}

View File

@@ -0,0 +1,27 @@
/*******************************************************************************
* Copyright (c) 2013 Pivotal Software, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.downloadmanager;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class URLConnectionFactory {
public int CONNECT_TIMEOUT = 3000;
public URLConnection createConnection(URL url) throws IOException {
URLConnection conn = url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
return conn;
}
}

View File

@@ -0,0 +1,15 @@
package org.springsource.ide.eclipse.commons.frameworks.core.internal.cache;
/**
* A Cache is basically just some kind of map in which key/value pairs can be kept.
* <p>
* Different implementations of this interface may implement different methods of automatically
* expiring cache entries.
*/
public interface Cache<K,V> {
V get(K key);
void put(K key, V value);
void clear(); //clear all entries from the cache.
}

View File

@@ -0,0 +1,155 @@
/*******************************************************************************
* Copyright (c) 2016, 2017 Pivotal, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Pivotal, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.internal.cache;
import java.time.Duration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
/**
* A cache that automatically removes entries when they reach a certain age.
*
* @author Kris De Volder
*/
public class LimitedTimeCache<K,V> implements Cache<K, V> {
private static final boolean DEBUG = false; //(""+Platform.getLocation()).contains("kdvolder");
private static void debug(String string) {
if (DEBUG) {
System.out.println(string);
}
}
public final long MAX_AGE;
public final long AGE_MARGIN;
private Map<K, Entry> cache = new HashMap<>();
/**
* Job that removes expired entries from the cache.
*/
private Job clearExpiredJob = new Job("Clean expired cache entries") {
{
setSystem(true);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
long oldest = clearExpired();
//Reschedule job to again run when the next entry expires.
if (oldest>=0) {
clearExpiredJob.schedule(MAX_AGE - oldest + AGE_MARGIN);
}
return Status.OK_STATUS;
}
};
private class Entry {
long lastUsed;
V value;
Entry(V v) {
this.value = v;
this.lastUsed = System.currentTimeMillis();
}
long age() {
return System.currentTimeMillis() - lastUsed;
}
}
public LimitedTimeCache(Duration MAX_AGE_DURATION) {
MAX_AGE = MAX_AGE_DURATION.toMillis();
AGE_MARGIN = Math.max(1000, MAX_AGE / 20);
}
@Override
public synchronized V get(K key) {
Entry e = cache.get(key);
if (e!=null) {
e.lastUsed = System.currentTimeMillis();
return e.value;
}
return null;
}
@Override
public synchronized void put(K key, V value) {
boolean wasEmpty = cache.isEmpty();
if (value==null) {
cache.remove(key);
} else {
cache.put(key, new Entry(value));
}
//if the cache was not empty then it is already guaranteed a 'cleaningJob' will run to
// clean the existing oldest entry.
if (wasEmpty && !cache.isEmpty()) {
//The entry we just added is the only one in the cache.
//Therefore, that entry must be the oldest and its age is 0.
//So we know when the job should run next:
clearExpiredJob.schedule(MAX_AGE+AGE_MARGIN);
}
}
@Override
public synchronized void clear() {
cache.clear();
}
/**
* Iterates the cache removing all expired entries.
* @return The age of the oldest non-expired entry in the cache or -1 if the cache is empty.
*/
private synchronized long clearExpired() {
debug(">>> clearExpired MAX_AGE = "+MAX_AGE);
Iterator<java.util.Map.Entry<K, LimitedTimeCache<K, V>.Entry>> iter = cache.entrySet().iterator();
long oldest = -1;
while (iter.hasNext()) {
java.util.Map.Entry<K, LimitedTimeCache<K, V>.Entry> me = iter.next();
Entry e = me.getValue();
long age = e.age();
if (age>=MAX_AGE) {
debug("Expired: "+me.getKey() +" age: "+e.age());
iter.remove();
} else {
oldest = Math.max(oldest, age);
}
}
debug("<<< clearExpired ["+cache.size()+"]");
return oldest;
}
/**
* Applies a {@link LimitedTimeCache} cache around a given function.
*
* @param duration time after which entries in the cache should expire.
* @param func Function to wrap the cache around
* @return Equivalent function but with caching.
*/
public static <K,V> Function<K,V> applyOn(Duration duration, Function<K,V> func) {
LimitedTimeCache<K, V> cache = new LimitedTimeCache<>(duration);
return (k) -> {
V v = cache.get(k);
if (v==null) {
cache.put(k, v=func.apply(k));
}
return v;
};
}
}

Some files were not shown because too many files have changed in this diff Show More