commit_id
stringlengths
40
40
project
stringclasses
90 values
commit_message
stringlengths
5
2.21k
type
stringclasses
3 values
url
stringclasses
89 values
git_diff
stringlengths
283
4.32M
17cf114310d01eb41045872d12758bff2c452d93
hbase
HBASE-5857 RIT map in RS not getting cleared- while region opening--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1329470 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java index 408cfbe5664e..025fc53d0e9a 100644 --- a/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java +++ b/src/main/java/org/apache/hadoop/hbase/regionserver/HRegionServer.java @@ -2485,9 +2485,9 @@ public RegionOpeningState openRegion(HRegionInfo region, int versionOfOfflineNod } LOG.info("Received request to open region: " + region.getRegionNameAsString()); + HTableDescriptor htd = this.tableDescriptors.get(region.getTableName()); this.regionsInTransitionInRS.putIfAbsent(region.getEncodedNameAsBytes(), true); - HTableDescriptor htd = this.tableDescriptors.get(region.getTableName()); // Need to pass the expected version in the constructor. if (region.isRootRegion()) { this.service.submit(new OpenRootHandler(this, this, region, htd, diff --git a/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java b/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java index c8e523f5e56e..8c3f67e1e490 100644 --- a/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java +++ b/src/test/java/org/apache/hadoop/hbase/master/TestZKBasedOpenCloseRegion.java @@ -47,9 +47,13 @@ import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.junit.Assert.assertFalse; /** * Test open and close of regions using zk. @@ -308,6 +312,30 @@ public void testRSAlreadyProcessingRegion() throws Exception { LOG.info("Done with testCloseRegion"); } + /** + * If region open fails with IOException in openRegion() while doing tableDescriptors.get() + * the region should not add into regionsInTransitionInRS map + * @throws Exception + */ + @Test + public void testRegionOpenFailsDueToIOException() throws Exception { + HRegionInfo REGIONINFO = new HRegionInfo(Bytes.toBytes("t"), + HConstants.EMPTY_START_ROW, HConstants.EMPTY_START_ROW); + HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(0); + TableDescriptors htd = Mockito.mock(TableDescriptors.class); + Object orizinalState = Whitebox.getInternalState(regionServer,"tableDescriptors"); + Whitebox.setInternalState(regionServer, "tableDescriptors", htd); + Mockito.doThrow(new IOException()).when(htd).get((byte[]) Mockito.any()); + try { + regionServer.openRegion(REGIONINFO); + fail("It should throw IOException "); + } catch (IOException e) { + } + Whitebox.setInternalState(regionServer, "tableDescriptors", orizinalState); + assertFalse("Region should not be in RIT", + regionServer.getRegionsInTransitionInRS().containsKey(REGIONINFO.getEncodedNameAsBytes())); + } + private static void waitUntilAllRegionsAssigned() throws IOException { HTable meta = new HTable(TEST_UTIL.getConfiguration(),
5e56988bd8fbc352fccd0429a85a0dcdb8104994
Valadoc
gtkdoc-parser: Allow <title> in ordered and itemized lists
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/documentation/gtkdoccommentparser.vala b/src/libvaladoc/documentation/gtkdoccommentparser.vala index 36544c08c8..e044bd4635 100644 --- a/src/libvaladoc/documentation/gtkdoccommentparser.vala +++ b/src/libvaladoc/documentation/gtkdoccommentparser.vala @@ -607,28 +607,29 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { return (Warning?) parse_docbook_information_box_template ("warning", factory.create_warning ()); } - private inline Content.List? parse_docbook_orderedlist () { + private inline LinkedList<Block>? parse_docbook_orderedlist () { return parse_docbook_itemizedlist ("orderedlist", Content.List.Bullet.ORDERED); } - private Content.List? parse_docbook_itemizedlist (string tag_name = "itemizedlist", Content.List.Bullet bullet_type = Content.List.Bullet.UNORDERED) { + private LinkedList<Block>? parse_docbook_itemizedlist (string tag_name = "itemizedlist", Content.List.Bullet bullet_type = Content.List.Bullet.UNORDERED) { if (!check_xml_open_tag (tag_name)) { this.report_unexpected_token (current, "<%s>".printf (tag_name)); return null; } - next (); + + LinkedList<Block> content = new LinkedList<Block> (); parse_docbook_spaces (); + if (current.type == TokenType.XML_OPEN && current.content == "title") { + append_block_content_not_null (content, parse_docbook_title ()); + parse_docbook_spaces (); + } + Content.List list = factory.create_list (); list.bullet = bullet_type; - -// if (current.type == TokenType.XML_OPEN && current.content == "title") { - // TODO -// parse_docbook_title (); -// parse_docbook_spaces (); -// } + content.add (list); while (current.type == TokenType.XML_OPEN) { if (current.content == "listitem") { @@ -642,11 +643,11 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { if (!check_xml_close_tag (tag_name)) { this.report_unexpected_token (current, "</%s>".printf (tag_name)); - return list; + return content; } next (); - return list; + return content; } private Paragraph? parse_gtkdoc_paragraph () { @@ -1380,9 +1381,9 @@ public class Valadoc.Gtkdoc.Parser : Object, ResourceLocator { parse_docbook_spaces (false); if (current.type == TokenType.XML_OPEN && current.content == "itemizedlist") { - this.append_block_content_not_null (content, parse_docbook_itemizedlist ()); + this.append_block_content_not_null_all (content, parse_docbook_itemizedlist ()); } else if (current.type == TokenType.XML_OPEN && current.content == "orderedlist") { - this.append_block_content_not_null (content, parse_docbook_orderedlist ()); + this.append_block_content_not_null_all (content, parse_docbook_orderedlist ()); } else if (current.type == TokenType.XML_OPEN && current.content == "variablelist") { this.append_block_content_not_null_all (content, parse_docbook_variablelist ()); } else if (current.type == TokenType.XML_OPEN && current.content == "simplelist") {
454302cf65c3c617149f28aee819549dd02f3680
Mylyn Reviews
Move versions-task bridge to reviews
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.project b/versions/org.eclipse.mylyn.versions.tasks-feature/.project new file mode 100644 index 00000000..dfb62cc5 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.mylyn.versions-feature</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.pde.FeatureBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.FeatureNature</nature> + </natures> +</projectDescription> diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..bbaca6d6 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,357 @@ +#Wed Mar 02 16:00:06 PST 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +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.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=enabled +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=warning +org.eclipse.jdt.core.compiler.problem.nullReference=error +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.redundantSuperinterface=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=ignore +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.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.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled +org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,HIGH,NORMAL +org.eclipse.jdt.core.compiler.taskTags=TODO,FIXME,XXX +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_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_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=48 +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_method_declaration=0 +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=80 +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=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true +org.eclipse.jdt.core.formatter.comment.format_block_comments=false +org.eclipse.jdt.core.formatter.comment.format_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=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=120 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_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_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_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.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +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=true +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true +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_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 00000000..f6c0a161 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,63 @@ +#Wed Mar 02 16:00:06 PST 2011 +cleanup_settings_version=2 +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +formatter_profile=_Mylyn based on Eclipse +formatter_settings_version=12 +internal.default.compliance=default +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.javadoc=false +org.eclipse.jdt.ui.keywordthis=false +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created Java files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="false" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="false" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment"/><template autoinsert\="false" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">/*******************************************************************************\r\n * Copyright (c) ${year} Tasktop Technologies and others.\r\n * All rights reserved. This program and the accompanying materials\r\n * are made available under the terms of the Eclipse Public License v1.0\r\n * which accompanies this distribution, and is available at\r\n * http\://www.eclipse.org/legal/epl-v10.html\r\n *\r\n * Contributors\:\r\n * Tasktop Technologies - initial API and implementation\r\n *******************************************************************************/\r\n\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="false" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="false" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">// ignore\r\n${body_statement}</template><template autoinsert\="false" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ignore</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created JavaScript files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n *\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for vars" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.overridecomment" name\="overridecomment">/* (non-Jsdoc)\r\n * ${see_to_overridden}\r\n */</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.newtype" name\="newtype">${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="true" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created function stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodbody" name\="methodbody">// ${todo} Auto-generated function stub\r\n${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ${todo} Auto-generated constructor stub</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates> +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_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=true +sp_cleanup.format_source_code=true +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_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=true +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 diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs new file mode 100644 index 00000000..47ada179 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs @@ -0,0 +1,4 @@ +#Thu Dec 20 14:12:59 PST 2007 +eclipse.preferences.version=1 +project.repository.kind=bugzilla +project.repository.url=https\://bugs.eclipse.org/bugs diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/about.html b/versions/org.eclipse.mylyn.versions.tasks-feature/about.html new file mode 100644 index 00000000..d774b07c --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/about.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> +<head> +<title>About</title> +<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> +</head> +<body lang="EN-US"> +<h2>About This Content</h2> + +<p>June 25, 2008</p> +<h3>License</h3> + +<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available +at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. +For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> + +<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p> + +</body> +</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/build.properties b/versions/org.eclipse.mylyn.versions.tasks-feature/build.properties new file mode 100644 index 00000000..1d717bf0 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/build.properties @@ -0,0 +1,16 @@ +############################################################################### +# Copyright (c) 2009, 2010 Tasktop Technologies and others. +# 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Tasktop Technologies - initial API and implementation +############################################################################### +bin.includes = feature.properties,\ + feature.xml,\ + about.html,\ + epl-v10.html,\ + license.html +src.includes = about.html diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/epl-v10.html b/versions/org.eclipse.mylyn.versions.tasks-feature/epl-v10.html new file mode 100644 index 00000000..ed4b1966 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/epl-v10.html @@ -0,0 +1,328 @@ +<html xmlns:o="urn:schemas-microsoft-com:office:office" +xmlns:w="urn:schemas-microsoft-com:office:word" +xmlns="http://www.w3.org/TR/REC-html40"> + +<head> +<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> +<meta name=ProgId content=Word.Document> +<meta name=Generator content="Microsoft Word 9"> +<meta name=Originator content="Microsoft Word 9"> +<link rel=File-List +href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> +<title>Eclipse Public License - Version 1.0</title> +<!--[if gte mso 9]><xml> + <o:DocumentProperties> + <o:Revision>2</o:Revision> + <o:TotalTime>3</o:TotalTime> + <o:Created>2004-03-05T23:03:00Z</o:Created> + <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> + <o:Pages>4</o:Pages> + <o:Words>1626</o:Words> + <o:Characters>9270</o:Characters> + <o:Lines>77</o:Lines> + <o:Paragraphs>18</o:Paragraphs> + <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> + <o:Version>9.4402</o:Version> + </o:DocumentProperties> +</xml><![endif]--><!--[if gte mso 9]><xml> + <w:WordDocument> + <w:TrackRevisions/> + </w:WordDocument> +</xml><![endif]--> +<style> +<!-- + /* Font Definitions */ +@font-face + {font-family:Tahoma; + panose-1:2 11 6 4 3 5 4 4 2 4; + mso-font-charset:0; + mso-generic-font-family:swiss; + mso-font-pitch:variable; + mso-font-signature:553679495 -2147483648 8 0 66047 0;} + /* Style Definitions */ +p.MsoNormal, li.MsoNormal, div.MsoNormal + {mso-style-parent:""; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p + {margin-right:0in; + mso-margin-top-alt:auto; + mso-margin-bottom-alt:auto; + margin-left:0in; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p.BalloonText, li.BalloonText, div.BalloonText + {mso-style-name:"Balloon Text"; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:8.0pt; + font-family:Tahoma; + mso-fareast-font-family:"Times New Roman";} +@page Section1 + {size:8.5in 11.0in; + margin:1.0in 1.25in 1.0in 1.25in; + mso-header-margin:.5in; + mso-footer-margin:.5in; + mso-paper-source:0;} +div.Section1 + {page:Section1;} +--> +</style> +</head> + +<body lang=EN-US style='tab-interval:.5in'> + +<div class=Section1> + +<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> +</p> + +<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.</span> </p> + +<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> + +<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and<br clear=left> +b) in the case of each subsequent Contributor:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +changes to the Program, and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +additions to the Program;</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or +entity that distributes the Program.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions +distributed in accordance with this Agreement.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who +receives the Program under this Agreement, including all Contributors.</span> </p> + +<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to<span +style='color:red'> </span>reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder. </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement. </span></p> + +<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> + +<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that:</span> +</p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it complies with the terms and conditions of this Agreement; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +its license agreement:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.<span style='color:blue'> </span></span></p> + +<p><span style='font-size:10.0pt'>When the Program is made available in source +code form:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it must be made available under this Agreement; and </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a +copy of this Agreement must be included with each copy of the Program. </span></p> + +<p><span style='font-size:10.0pt'>Contributors may not remove or alter any +copyright notices contained within the Program. </span></p> + +<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution. </span></p> + +<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> + +<p><span style='font-size:10.0pt'>Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor (&quot;Commercial +Contributor&quot;) hereby agrees to defend and indemnify every other +Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and +costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.</span> </p> + +<p><span style='font-size:10.0pt'>For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.</span> </p> + +<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations. </span></p> + +<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.</span> </p> + +<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> + +<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.</span> </p> + +<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed. </span></p> + +<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive. </span></p> + +<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.</span> </p> + +<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.</span> </p> + +<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> + +</div> + +</body> + +</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties new file mode 100644 index 00000000..1f3b6ab9 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.properties @@ -0,0 +1,138 @@ +############################################################################### +# Copyright (c) 2011 Tasktop Technologies and others. +# 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Tasktop Technologies - initial API and implementation +############################################################################### +featureName=Mylyn Versions (Incubation) +description=Provides a framework for accessing team providers. +providerName=Eclipse Mylyn +copyright=Copyright (c) 2011 Tasktop Technologies and others. All rights reserved. + +license=\ +Eclipse Foundation Software User Agreement\n\ +April 14, 2010\n\ +\n\ +Usage Of Content\n\ +\n\ +THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ +OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ +USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ +AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ +NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ +AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ +AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ +OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ +TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ +OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ +BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ +\n\ +Applicable Licenses\n\ +\n\ +Unless otherwise indicated, all Content made available by the\n\ +Eclipse Foundation is provided to you under the terms and conditions of\n\ +the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is\n\ +provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ +For purposes of the EPL, "Program" will mean the Content.\n\ +\n\ +Content includes, but is not limited to, source code, object code,\n\ +documentation and other files maintained in the Eclipse Foundation source code\n\ +repository ("Repository") in software modules ("Modules") and made available\n\ +as downloadable archives ("Downloads").\n\ +\n\ + - Content may be structured and packaged into modules to facilitate delivering,\n\ + extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ + plug-in fragments ("Fragments"), and features ("Features").\n\ + - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java(TM) ARchive)\n\ + in a directory named "plugins".\n\ + - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ + Each Feature may be packaged as a sub-directory in a directory named "features".\n\ + Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ + numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ + - Features may also include other Features ("Included Features"). Within a Feature, files\n\ + named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ +\n\ +The terms and conditions governing Plug-ins and Fragments should be\n\ +contained in files named "about.html" ("Abouts"). The terms and\n\ +conditions governing Features and Included Features should be contained\n\ +in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ +Licenses may be located in any directory of a Download or Module\n\ +including, but not limited to the following locations:\n\ +\n\ + - The top-level (root) directory\n\ + - Plug-in and Fragment directories\n\ + - Inside Plug-ins and Fragments packaged as JARs\n\ + - Sub-directories of the directory named "src" of certain Plug-ins\n\ + - Feature directories\n\ +\n\ +Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ +Provisioning Technology (as defined below), you must agree to a license ("Feature \n\ +Update License") during the installation process. If the Feature contains\n\ +Included Features, the Feature Update License should either provide you\n\ +with the terms and conditions governing the Included Features or inform\n\ +you where you can locate them. Feature Update Licenses may be found in\n\ +the "license" property of files named "feature.properties" found within a Feature.\n\ +Such Abouts, Feature Licenses, and Feature Update Licenses contain the\n\ +terms and conditions (or references to such terms and conditions) that\n\ +govern your use of the associated Content in that directory.\n\ +\n\ +THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER\n\ +TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ +SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ +\n\ + - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ + - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ + - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ + - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ + - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ +\n\ +IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ +TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License\n\ +is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ +govern that particular Content.\n\ +\n\ +\n\Use of Provisioning Technology\n\ +\n\ +The Eclipse Foundation makes available provisioning software, examples of which include,\n\ +but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for\n\ +the purpose of allowing users to install software, documentation, information and/or\n\ +other materials (collectively "Installable Software"). This capability is provided with\n\ +the intent of allowing such users to install, extend and update Eclipse-based products.\n\ +Information about packaging Installable Software is available at\n\ +http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").\n\ +\n\ +You may use Provisioning Technology to allow other parties to install Installable Software.\n\ +You shall be responsible for enabling the applicable license agreements relating to the\n\ +Installable Software to be presented to, and accepted by, the users of the Provisioning Technology\n\ +in accordance with the Specification. By using Provisioning Technology in such a manner and\n\ +making it available in accordance with the Specification, you further acknowledge your\n\ +agreement to, and the acquisition of all necessary rights to permit the following:\n\ +\n\ + 1. A series of actions may occur ("Provisioning Process") in which a user may execute\n\ + the Provisioning Technology on a machine ("Target Machine") with the intent of installing,\n\ + extending or updating the functionality of an Eclipse-based product.\n\ + 2. During the Provisioning Process, the Provisioning Technology may cause third party\n\ + Installable Software or a portion thereof to be accessed and copied to the Target Machine.\n\ + 3. Pursuant to the Specification, you will provide to the user the terms and conditions that\n\ + govern the use of the Installable Software ("Installable Software Agreement") and such\n\ + Installable Software Agreement shall be accessed from the Target Machine in accordance\n\ + with the Specification. Such Installable Software Agreement must inform the user of the\n\ + terms and conditions that govern the Installable Software and must solicit acceptance by\n\ + the end user in the manner prescribed in such Installable Software Agreement. Upon such\n\ + indication of agreement by the user, the provisioning Technology will complete installation\n\ + of the Installable Software.\n\ +\n\ +Cryptography\n\ +\n\ +Content may contain encryption software. The country in which you are\n\ +currently may have restrictions on the import, possession, and use,\n\ +and/or re-export to another country, of encryption software. BEFORE\n\ +using any encryption software, please check the country's laws,\n\ +regulations and policies concerning the import, possession, or use, and\n\ +re-export of encryption software, to see if this is permitted.\n\ +\n\ +Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.\n diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml new file mode 100644 index 00000000..c3e2ad93 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/feature.xml @@ -0,0 +1,48 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright (c) 2010 Tasktop Technologies and others. + 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 + http://www.eclipse.org/legal/epl-v10.html + + Contributors: + Tasktop Technologies - initial API and implementation + --> +<feature + id="org.eclipse.mylyn.versions" + label="%featureName" + version="0.7.0.qualifier" + provider-name="%providerName" + plugin="org.eclipse.mylyn"> + + <description url="http://eclipse.org/mylyn"> + %description + </description> + + <copyright> + %copyright + </copyright> + + <license url="license.html"> + %license + </license> + + <requires> + </requires> + + <plugin + id="org.eclipse.mylyn.versions.tasks.core" + download-size="0" + install-size="0" + version="0.0.0" + unpack="false"/> + + <plugin + id="org.eclipse.mylyn.versions.tasks.ui" + download-size="0" + install-size="0" + version="0.0.0" + unpack="false"/> + +</feature> diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/license.html b/versions/org.eclipse.mylyn.versions.tasks-feature/license.html new file mode 100644 index 00000000..c184ca36 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/license.html @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="ISO-8859-1" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> +<title>Eclipse Foundation Software User Agreement</title> +</head> + +<body lang="EN-US"> +<h2>Eclipse Foundation Software User Agreement</h2> +<p>April 14, 2010</p> + +<h3>Usage Of Content</h3> + +<p>THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS + (COLLECTIVELY &quot;CONTENT&quot;). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND + CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE + OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR + NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND + CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.</p> + +<h3>Applicable Licenses</h3> + +<p>Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 + (&quot;EPL&quot;). A copy of the EPL is provided with this Content and is also available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. + For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> + +<p>Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code + repository (&quot;Repository&quot;) in software modules (&quot;Modules&quot;) and made available as downloadable archives (&quot;Downloads&quot;).</p> + +<ul> + <li>Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins (&quot;Plug-ins&quot;), plug-in fragments (&quot;Fragments&quot;), and features (&quot;Features&quot;).</li> + <li>Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java&trade; ARchive) in a directory named &quot;plugins&quot;.</li> + <li>A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named &quot;features&quot;. Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of the Plug-ins + and/or Fragments associated with that Feature.</li> + <li>Features may also include other Features (&quot;Included Features&quot;). Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of Included Features.</li> +</ul> + +<p>The terms and conditions governing Plug-ins and Fragments should be contained in files named &quot;about.html&quot; (&quot;Abouts&quot;). The terms and conditions governing Features and +Included Features should be contained in files named &quot;license.html&quot; (&quot;Feature Licenses&quot;). Abouts and Feature Licenses may be located in any directory of a Download or Module +including, but not limited to the following locations:</p> + +<ul> + <li>The top-level (root) directory</li> + <li>Plug-in and Fragment directories</li> + <li>Inside Plug-ins and Fragments packaged as JARs</li> + <li>Sub-directories of the directory named &quot;src&quot; of certain Plug-ins</li> + <li>Feature directories</li> +</ul> + +<p>Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license (&quot;Feature Update License&quot;) during the +installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or +inform you where you can locate them. Feature Update Licenses may be found in the &quot;license&quot; property of files named &quot;feature.properties&quot; found within a Feature. +Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in +that directory.</p> + +<p>THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE +OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):</p> + +<ul> + <li>Common Public License Version 1.0 (available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>)</li> + <li>Apache Software License 1.1 (available at <a href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</a>)</li> + <li>Apache Software License 2.0 (available at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>)</li> + <li>Metro Link Public License 1.00 (available at <a href="http://www.opengroup.org/openmotif/supporters/metrolink/license.html">http://www.opengroup.org/openmotif/supporters/metrolink/license.html</a>)</li> + <li>Mozilla Public License Version 1.1 (available at <a href="http://www.mozilla.org/MPL/MPL-1.1.html">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li> +</ul> + +<p>IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please +contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.</p> + + +<h3>Use of Provisioning Technology</h3> + +<p>The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse + Update Manager (&quot;Provisioning Technology&quot;) for the purpose of allowing users to install software, documentation, information and/or + other materials (collectively &quot;Installable Software&quot;). This capability is provided with the intent of allowing such users to + install, extend and update Eclipse-based products. Information about packaging Installable Software is available at <a + href="http://eclipse.org/equinox/p2/repository_packaging.html">http://eclipse.org/equinox/p2/repository_packaging.html</a> + (&quot;Specification&quot;).</p> + +<p>You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the + applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology + in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the + Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:</p> + +<ol> + <li>A series of actions may occur (&quot;Provisioning Process&quot;) in which a user may execute the Provisioning Technology + on a machine (&quot;Target Machine&quot;) with the intent of installing, extending or updating the functionality of an Eclipse-based + product.</li> + <li>During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be + accessed and copied to the Target Machine.</li> + <li>Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable + Software (&quot;Installable Software Agreement&quot;) and such Installable Software Agreement shall be accessed from the Target + Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern + the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such + indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.</li> +</ol> + +<h3>Cryptography</h3> + +<p>Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to + another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, + possession, or use, and re-export of encryption software, to see if this is permitted.</p> + +<p><small>Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.</small></p> +</body> +</html> diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml b/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml new file mode 100644 index 00000000..e586b3a1 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks-feature/pom.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <artifactId>mylyn-versions-tasks-parent</artifactId> + <groupId>org.eclipse.mylyn.versions</groupId> + <version>0.7.0-SNAPSHOT</version> + </parent> + <groupId>org.eclipse.mylyn.versions</groupId> + <artifactId>org.eclipse.mylyn.versions.tasks</artifactId> + <version>0.7.0-SNAPSHOT</version> + <packaging>eclipse-feature</packaging> +</project> diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/.classpath b/versions/org.eclipse.mylyn.versions.tasks.core/.classpath new file mode 100644 index 00000000..64c5e31b --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/.classpath @@ -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/J2SE-1.5"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/.project b/versions/org.eclipse.mylyn.versions.tasks.core/.project new file mode 100644 index 00000000..ed1b636d --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.mylyn.versions.tasks.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> diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks.core/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..cc25307b --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Feb 22 18:52:35 PST 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/META-INF/MANIFEST.MF b/versions/org.eclipse.mylyn.versions.tasks.core/META-INF/MANIFEST.MF new file mode 100644 index 00000000..c5705d8a --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/META-INF/MANIFEST.MF @@ -0,0 +1,10 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %Bundle-Name +Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.core +Bundle-Version: 0.1.0.qualifier +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Require-Bundle: org.eclipse.mylyn.tasks.core;bundle-version="3.5.0", + org.eclipse.mylyn.versions.core;bundle-version="0.1.0" +Export-Package: org.eclipse.mylyn.versions.tasks.core;x-internal:=true +Bundle-Vendor: %Bundle-Vendor diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/about.html b/versions/org.eclipse.mylyn.versions.tasks.core/about.html new file mode 100644 index 00000000..d774b07c --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/about.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> +<head> +<title>About</title> +<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> +</head> +<body lang="EN-US"> +<h2>About This Content</h2> + +<p>June 25, 2008</p> +<h3>License</h3> + +<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available +at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. +For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> + +<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p> + +</body> +</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/build.properties b/versions/org.eclipse.mylyn.versions.tasks.core/build.properties new file mode 100644 index 00000000..34d2e4d2 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/plugin.properties b/versions/org.eclipse.mylyn.versions.tasks.core/plugin.properties new file mode 100644 index 00000000..eee282ab --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/plugin.properties @@ -0,0 +1,12 @@ +############################################################################### +# Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology and others. +# 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation +############################################################################### +Bundle-Vendor = Eclipse Mylyn +Bundle-Name = Mylyn Versions Framework Task Integration diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/pom.xml b/versions/org.eclipse.mylyn.versions.tasks.core/pom.xml new file mode 100644 index 00000000..9cd4adab --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/pom.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <artifactId>mylyn-versions-tasks-parent</artifactId> + <groupId>org.eclipse.mylyn.versions</groupId> + <version>0.7.0-SNAPSHOT</version> + </parent> + <artifactId>org.eclipse.mylyn.versions.tasks.core</artifactId> + <version>0.1.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + <build> + <plugins> + <plugin> + <groupId>org.sonatype.tycho</groupId> + <artifactId>maven-osgi-source-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>findbugs-maven-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-pmd-plugin</artifactId> + </plugin> + </plugins> + </build> +</project> diff --git a/versions/org.eclipse.mylyn.versions.tasks.core/src/org/eclipse/mylyn/versions/tasks/core/TaskChangeSet.java b/versions/org.eclipse.mylyn.versions.tasks.core/src/org/eclipse/mylyn/versions/tasks/core/TaskChangeSet.java new file mode 100644 index 00000000..4b7e6ac0 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.core/src/org/eclipse/mylyn/versions/tasks/core/TaskChangeSet.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.core; + +import org.eclipse.mylyn.tasks.core.ITask; +import org.eclipse.mylyn.versions.core.ChangeSet; + +/** + * + * @author Kilian Matt + * + */ +public class TaskChangeSet { + private ChangeSet changeset; + private ITask task; + + public TaskChangeSet(ITask task, ChangeSet cs) { + this.task = task; + this.changeset = cs; + } + + public ChangeSet getChangeset() { + return changeset; + } + + public ITask getTask() { + return task; + } +} diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.project b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.project new file mode 100644 index 00000000..c9fcc520 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.mylyn.versions.sdk-feature</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.pde.FeatureBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.FeatureNature</nature> + </natures> +</projectDescription> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..bbaca6d6 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,357 @@ +#Wed Mar 02 16:00:06 PST 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +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.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=enabled +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=warning +org.eclipse.jdt.core.compiler.problem.nullReference=error +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.redundantSuperinterface=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=ignore +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.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.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled +org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,HIGH,NORMAL +org.eclipse.jdt.core.compiler.taskTags=TODO,FIXME,XXX +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_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_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=48 +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_method_declaration=0 +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=80 +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=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true +org.eclipse.jdt.core.formatter.comment.format_block_comments=false +org.eclipse.jdt.core.formatter.comment.format_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=false +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert +org.eclipse.jdt.core.formatter.comment.line_length=120 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_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_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert +org.eclipse.jdt.core.formatter.insert_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.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +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=true +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true +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_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.ui.prefs new file mode 100644 index 00000000..ae5a0874 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.jdt.ui.prefs @@ -0,0 +1,63 @@ +#Wed Mar 02 16:00:03 PST 2011 +cleanup_settings_version=2 +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +formatter_profile=_Mylyn based on Eclipse +formatter_settings_version=12 +internal.default.compliance=default +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.javadoc=false +org.eclipse.jdt.ui.keywordthis=false +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created Java files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="false" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="false" context\="overridecomment_context" deleted\="false" description\="Comment for overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.overridecomment" name\="overridecomment"/><template autoinsert\="false" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.newtype" name\="newtype">/*******************************************************************************\r\n * Copyright (c) ${year} Tasktop Technologies and others.\r\n * All rights reserved. This program and the accompanying materials\r\n * are made available under the terms of the Eclipse Public License v1.0\r\n * which accompanies this distribution, and is available at\r\n * http\://www.eclipse.org/legal/epl-v10.html\r\n *\r\n * Contributors\:\r\n * Tasktop Technologies - initial API and implementation\r\n *******************************************************************************/\r\n\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="false" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="false" context\="methodbody_context" deleted\="false" description\="Code in created method stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodbody" name\="methodbody">// ignore\r\n${body_statement}</template><template autoinsert\="false" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ignore</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="gettercomment_context" deleted\="false" description\="Comment for getter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.gettercomment" name\="gettercomment">/**\r\n * @return the ${bare_field_name}\r\n */</template><template autoinsert\="true" context\="settercomment_context" deleted\="false" description\="Comment for setter function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.settercomment" name\="settercomment">/**\r\n * @param ${param} the ${bare_field_name} to set\r\n */</template><template autoinsert\="true" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="filecomment_context" deleted\="false" description\="Comment for created JavaScript files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.filecomment" name\="filecomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="typecomment_context" deleted\="false" description\="Comment for created types" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.typecomment" name\="typecomment">/**\r\n * @author ${user}\r\n *\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="fieldcomment_context" deleted\="false" description\="Comment for vars" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment">/**\r\n * \r\n */</template><template autoinsert\="true" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding function" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodcomment" name\="methodcomment">/**\r\n * ${tags}\r\n */</template><template autoinsert\="true" context\="overridecomment_context" deleted\="false" description\="Comment for overriding functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.overridecomment" name\="overridecomment">/* (non-Jsdoc)\r\n * ${see_to_overridden}\r\n */</template><template autoinsert\="true" context\="delegatecomment_context" deleted\="false" description\="Comment for delegate functions" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment">/**\r\n * ${tags}\r\n * ${see_to_target}\r\n */</template><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.newtype" name\="newtype">${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}</template><template autoinsert\="true" context\="classbody_context" deleted\="false" description\="Code in new class type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.classbody" name\="classbody">\r\n</template><template autoinsert\="true" context\="interfacebody_context" deleted\="false" description\="Code in new interface type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.interfacebody" name\="interfacebody">\r\n</template><template autoinsert\="true" context\="enumbody_context" deleted\="false" description\="Code in new enum type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.enumbody" name\="enumbody">\r\n</template><template autoinsert\="true" context\="annotationbody_context" deleted\="false" description\="Code in new annotation type bodies" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.annotationbody" name\="annotationbody">\r\n</template><template autoinsert\="true" context\="catchblock_context" deleted\="false" description\="Code in new catch blocks" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.catchblock" name\="catchblock">// ${todo} Auto-generated catch block\r\n${exception_var}.printStackTrace();</template><template autoinsert\="true" context\="methodbody_context" deleted\="false" description\="Code in created function stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.methodbody" name\="methodbody">// ${todo} Auto-generated function stub\r\n${body_statement}</template><template autoinsert\="true" context\="constructorbody_context" deleted\="false" description\="Code in created constructor stubs" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.constructorbody" name\="constructorbody">${body_statement}\r\n// ${todo} Auto-generated constructor stub</template><template autoinsert\="true" context\="getterbody_context" deleted\="false" description\="Code in created getters" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.getterbody" name\="getterbody">return ${field};</template><template autoinsert\="true" context\="setterbody_context" deleted\="false" description\="Code in created setters" enabled\="true" id\="org.eclipse.wst.jsdt.ui.text.codetemplates.setterbody" name\="setterbody">${field} \= ${param};</template></templates> +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_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=true +sp_cleanup.format_source_code=true +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_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=true +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 diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs new file mode 100644 index 00000000..47ada179 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/.settings/org.eclipse.mylyn.tasks.ui.prefs @@ -0,0 +1,4 @@ +#Thu Dec 20 14:12:59 PST 2007 +eclipse.preferences.version=1 +project.repository.kind=bugzilla +project.repository.url=https\://bugs.eclipse.org/bugs diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/about.html b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/about.html new file mode 100644 index 00000000..d774b07c --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/about.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> +<head> +<title>About</title> +<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> +</head> +<body lang="EN-US"> +<h2>About This Content</h2> + +<p>June 25, 2008</p> +<h3>License</h3> + +<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available +at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. +For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> + +<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p> + +</body> +</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/build.properties b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/build.properties new file mode 100644 index 00000000..1d717bf0 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/build.properties @@ -0,0 +1,16 @@ +############################################################################### +# Copyright (c) 2009, 2010 Tasktop Technologies and others. +# 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Tasktop Technologies - initial API and implementation +############################################################################### +bin.includes = feature.properties,\ + feature.xml,\ + about.html,\ + epl-v10.html,\ + license.html +src.includes = about.html diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/epl-v10.html b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/epl-v10.html new file mode 100644 index 00000000..ed4b1966 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/epl-v10.html @@ -0,0 +1,328 @@ +<html xmlns:o="urn:schemas-microsoft-com:office:office" +xmlns:w="urn:schemas-microsoft-com:office:word" +xmlns="http://www.w3.org/TR/REC-html40"> + +<head> +<meta http-equiv=Content-Type content="text/html; charset=windows-1252"> +<meta name=ProgId content=Word.Document> +<meta name=Generator content="Microsoft Word 9"> +<meta name=Originator content="Microsoft Word 9"> +<link rel=File-List +href="./Eclipse%20EPL%202003_11_10%20Final_files/filelist.xml"> +<title>Eclipse Public License - Version 1.0</title> +<!--[if gte mso 9]><xml> + <o:DocumentProperties> + <o:Revision>2</o:Revision> + <o:TotalTime>3</o:TotalTime> + <o:Created>2004-03-05T23:03:00Z</o:Created> + <o:LastSaved>2004-03-05T23:03:00Z</o:LastSaved> + <o:Pages>4</o:Pages> + <o:Words>1626</o:Words> + <o:Characters>9270</o:Characters> + <o:Lines>77</o:Lines> + <o:Paragraphs>18</o:Paragraphs> + <o:CharactersWithSpaces>11384</o:CharactersWithSpaces> + <o:Version>9.4402</o:Version> + </o:DocumentProperties> +</xml><![endif]--><!--[if gte mso 9]><xml> + <w:WordDocument> + <w:TrackRevisions/> + </w:WordDocument> +</xml><![endif]--> +<style> +<!-- + /* Font Definitions */ +@font-face + {font-family:Tahoma; + panose-1:2 11 6 4 3 5 4 4 2 4; + mso-font-charset:0; + mso-generic-font-family:swiss; + mso-font-pitch:variable; + mso-font-signature:553679495 -2147483648 8 0 66047 0;} + /* Style Definitions */ +p.MsoNormal, li.MsoNormal, div.MsoNormal + {mso-style-parent:""; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p + {margin-right:0in; + mso-margin-top-alt:auto; + mso-margin-bottom-alt:auto; + margin-left:0in; + mso-pagination:widow-orphan; + font-size:12.0pt; + font-family:"Times New Roman"; + mso-fareast-font-family:"Times New Roman";} +p.BalloonText, li.BalloonText, div.BalloonText + {mso-style-name:"Balloon Text"; + margin:0in; + margin-bottom:.0001pt; + mso-pagination:widow-orphan; + font-size:8.0pt; + font-family:Tahoma; + mso-fareast-font-family:"Times New Roman";} +@page Section1 + {size:8.5in 11.0in; + margin:1.0in 1.25in 1.0in 1.25in; + mso-header-margin:.5in; + mso-footer-margin:.5in; + mso-paper-source:0;} +div.Section1 + {page:Section1;} +--> +</style> +</head> + +<body lang=EN-US style='tab-interval:.5in'> + +<div class=Section1> + +<p align=center style='text-align:center'><b>Eclipse Public License - v 1.0</b> +</p> + +<p><span style='font-size:10.0pt'>THE ACCOMPANYING PROGRAM IS PROVIDED UNDER +THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, +REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE +OF THIS AGREEMENT.</span> </p> + +<p><b><span style='font-size:10.0pt'>1. DEFINITIONS</span></b> </p> + +<p><span style='font-size:10.0pt'>&quot;Contribution&quot; means:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +in the case of the initial Contributor, the initial code and documentation +distributed under this Agreement, and<br clear=left> +b) in the case of each subsequent Contributor:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +changes to the Program, and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +additions to the Program;</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>where +such changes and/or additions to the Program originate from and are distributed +by that particular Contributor. A Contribution 'originates' from a Contributor +if it was added to the Program by such Contributor itself or anyone acting on +such Contributor's behalf. Contributions do not include additions to the +Program which: (i) are separate modules of software distributed in conjunction +with the Program under their own license agreement, and (ii) are not derivative +works of the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Contributor&quot; means any person or +entity that distributes the Program.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Licensed Patents &quot; mean patent +claims licensable by a Contributor which are necessarily infringed by the use +or sale of its Contribution alone or when combined with the Program. </span></p> + +<p><span style='font-size:10.0pt'>&quot;Program&quot; means the Contributions +distributed in accordance with this Agreement.</span> </p> + +<p><span style='font-size:10.0pt'>&quot;Recipient&quot; means anyone who +receives the Program under this Agreement, including all Contributors.</span> </p> + +<p><b><span style='font-size:10.0pt'>2. GRANT OF RIGHTS</span></b> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +Subject to the terms of this Agreement, each Contributor hereby grants Recipient +a non-exclusive, worldwide, royalty-free copyright license to<span +style='color:red'> </span>reproduce, prepare derivative works of, publicly +display, publicly perform, distribute and sublicense the Contribution of such +Contributor, if any, and such derivative works, in source code and object code +form.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +Subject to the terms of this Agreement, each Contributor hereby grants +Recipient a non-exclusive, worldwide,<span style='color:green'> </span>royalty-free +patent license under Licensed Patents to make, use, sell, offer to sell, import +and otherwise transfer the Contribution of such Contributor, if any, in source +code and object code form. This patent license shall apply to the combination +of the Contribution and the Program if, at the time the Contribution is added +by the Contributor, such addition of the Contribution causes such combination +to be covered by the Licensed Patents. The patent license shall not apply to +any other combinations which include the Contribution. No hardware per se is +licensed hereunder. </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>c) +Recipient understands that although each Contributor grants the licenses to its +Contributions set forth herein, no assurances are provided by any Contributor +that the Program does not infringe the patent or other intellectual property +rights of any other entity. Each Contributor disclaims any liability to Recipient +for claims brought by any other entity based on infringement of intellectual +property rights or otherwise. As a condition to exercising the rights and +licenses granted hereunder, each Recipient hereby assumes sole responsibility +to secure any other intellectual property rights needed, if any. For example, +if a third party patent license is required to allow Recipient to distribute +the Program, it is Recipient's responsibility to acquire that license before +distributing the Program.</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>d) +Each Contributor represents that to its knowledge it has sufficient copyright +rights in its Contribution, if any, to grant the copyright license set forth in +this Agreement. </span></p> + +<p><b><span style='font-size:10.0pt'>3. REQUIREMENTS</span></b> </p> + +<p><span style='font-size:10.0pt'>A Contributor may choose to distribute the +Program in object code form under its own license agreement, provided that:</span> +</p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it complies with the terms and conditions of this Agreement; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) +its license agreement:</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>i) +effectively disclaims on behalf of all Contributors all warranties and +conditions, express and implied, including warranties or conditions of title +and non-infringement, and implied warranties or conditions of merchantability +and fitness for a particular purpose; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>ii) +effectively excludes on behalf of all Contributors all liability for damages, +including direct, indirect, special, incidental and consequential damages, such +as lost profits; </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iii) +states that any provisions which differ from this Agreement are offered by that +Contributor alone and not by any other party; and</span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>iv) +states that source code for the Program is available from such Contributor, and +informs licensees how to obtain it in a reasonable manner on or through a +medium customarily used for software exchange.<span style='color:blue'> </span></span></p> + +<p><span style='font-size:10.0pt'>When the Program is made available in source +code form:</span> </p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>a) +it must be made available under this Agreement; and </span></p> + +<p class=MsoNormal style='margin-left:.5in'><span style='font-size:10.0pt'>b) a +copy of this Agreement must be included with each copy of the Program. </span></p> + +<p><span style='font-size:10.0pt'>Contributors may not remove or alter any +copyright notices contained within the Program. </span></p> + +<p><span style='font-size:10.0pt'>Each Contributor must identify itself as the +originator of its Contribution, if any, in a manner that reasonably allows +subsequent Recipients to identify the originator of the Contribution. </span></p> + +<p><b><span style='font-size:10.0pt'>4. COMMERCIAL DISTRIBUTION</span></b> </p> + +<p><span style='font-size:10.0pt'>Commercial distributors of software may +accept certain responsibilities with respect to end users, business partners +and the like. While this license is intended to facilitate the commercial use +of the Program, the Contributor who includes the Program in a commercial +product offering should do so in a manner which does not create potential +liability for other Contributors. Therefore, if a Contributor includes the +Program in a commercial product offering, such Contributor (&quot;Commercial +Contributor&quot;) hereby agrees to defend and indemnify every other +Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and +costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other +legal actions brought by a third party against the Indemnified Contributor to +the extent caused by the acts or omissions of such Commercial Contributor in +connection with its distribution of the Program in a commercial product +offering. The obligations in this section do not apply to any claims or Losses +relating to any actual or alleged intellectual property infringement. In order +to qualify, an Indemnified Contributor must: a) promptly notify the Commercial +Contributor in writing of such claim, and b) allow the Commercial Contributor +to control, and cooperate with the Commercial Contributor in, the defense and +any related settlement negotiations. The Indemnified Contributor may participate +in any such claim at its own expense.</span> </p> + +<p><span style='font-size:10.0pt'>For example, a Contributor might include the +Program in a commercial product offering, Product X. That Contributor is then a +Commercial Contributor. If that Commercial Contributor then makes performance +claims, or offers warranties related to Product X, those performance claims and +warranties are such Commercial Contributor's responsibility alone. Under this +section, the Commercial Contributor would have to defend claims against the +other Contributors related to those performance claims and warranties, and if a +court requires any other Contributor to pay any damages as a result, the +Commercial Contributor must pay those damages.</span> </p> + +<p><b><span style='font-size:10.0pt'>5. NO WARRANTY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, +WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely +responsible for determining the appropriateness of using and distributing the +Program and assumes all risks associated with its exercise of rights under this +Agreement , including but not limited to the risks and costs of program errors, +compliance with applicable laws, damage to or loss of data, programs or +equipment, and unavailability or interruption of operations. </span></p> + +<p><b><span style='font-size:10.0pt'>6. DISCLAIMER OF LIABILITY</span></b> </p> + +<p><span style='font-size:10.0pt'>EXCEPT AS EXPRESSLY SET FORTH IN THIS +AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF +THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES.</span> </p> + +<p><b><span style='font-size:10.0pt'>7. GENERAL</span></b> </p> + +<p><span style='font-size:10.0pt'>If any provision of this Agreement is invalid +or unenforceable under applicable law, it shall not affect the validity or +enforceability of the remainder of the terms of this Agreement, and without +further action by the parties hereto, such provision shall be reformed to the +minimum extent necessary to make such provision valid and enforceable.</span> </p> + +<p><span style='font-size:10.0pt'>If Recipient institutes patent litigation +against any entity (including a cross-claim or counterclaim in a lawsuit) +alleging that the Program itself (excluding combinations of the Program with +other software or hardware) infringes such Recipient's patent(s), then such +Recipient's rights granted under Section 2(b) shall terminate as of the date +such litigation is filed. </span></p> + +<p><span style='font-size:10.0pt'>All Recipient's rights under this Agreement +shall terminate if it fails to comply with any of the material terms or +conditions of this Agreement and does not cure such failure in a reasonable +period of time after becoming aware of such noncompliance. If all Recipient's +rights under this Agreement terminate, Recipient agrees to cease use and +distribution of the Program as soon as reasonably practicable. However, +Recipient's obligations under this Agreement and any licenses granted by +Recipient relating to the Program shall continue and survive. </span></p> + +<p><span style='font-size:10.0pt'>Everyone is permitted to copy and distribute +copies of this Agreement, but in order to avoid inconsistency the Agreement is +copyrighted and may only be modified in the following manner. The Agreement +Steward reserves the right to publish new versions (including revisions) of +this Agreement from time to time. No one other than the Agreement Steward has +the right to modify this Agreement. The Eclipse Foundation is the initial +Agreement Steward. The Eclipse Foundation may assign the responsibility to +serve as the Agreement Steward to a suitable separate entity. Each new version +of the Agreement will be given a distinguishing version number. The Program +(including Contributions) may always be distributed subject to the version of +the Agreement under which it was received. In addition, after a new version of +the Agreement is published, Contributor may elect to distribute the Program +(including its Contributions) under the new version. Except as expressly stated +in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to +the intellectual property of any Contributor under this Agreement, whether +expressly, by implication, estoppel or otherwise. All rights in the Program not +expressly granted under this Agreement are reserved.</span> </p> + +<p><span style='font-size:10.0pt'>This Agreement is governed by the laws of the +State of New York and the intellectual property laws of the United States of +America. No party to this Agreement will bring a legal action under this +Agreement more than one year after the cause of action arose. Each party waives +its rights to a jury trial in any resulting litigation.</span> </p> + +<p class=MsoNormal><![if !supportEmptyParas]>&nbsp;<![endif]><o:p></o:p></p> + +</div> + +</body> + +</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.properties b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.properties new file mode 100644 index 00000000..dc762267 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.properties @@ -0,0 +1,138 @@ +############################################################################### +# Copyright (c) 2011 Tasktop Technologies and others. +# 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Tasktop Technologies - initial API and implementation +############################################################################### +featureName=Mylyn Versions SDK (Incubation) +description=Plug-in development support and sources for version integrations. +providerName=Eclipse Mylyn +copyright=Copyright (c) 2010, 2011 Tasktop Technologies and others. All rights reserved. + +license=\ +Eclipse Foundation Software User Agreement\n\ +April 14, 2010\n\ +\n\ +Usage Of Content\n\ +\n\ +THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR\n\ +OTHER MATERIALS FOR OPEN SOURCE PROJECTS (COLLECTIVELY "CONTENT").\n\ +USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS\n\ +AGREEMENT AND/OR THE TERMS AND CONDITIONS OF LICENSE AGREEMENTS OR\n\ +NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU\n\ +AGREE THAT YOUR USE OF THE CONTENT IS GOVERNED BY THIS AGREEMENT\n\ +AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS\n\ +OR NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE\n\ +TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND CONDITIONS\n\ +OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED\n\ +BELOW, THEN YOU MAY NOT USE THE CONTENT.\n\ +\n\ +Applicable Licenses\n\ +\n\ +Unless otherwise indicated, all Content made available by the\n\ +Eclipse Foundation is provided to you under the terms and conditions of\n\ +the Eclipse Public License Version 1.0 ("EPL"). A copy of the EPL is\n\ +provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html.\n\ +For purposes of the EPL, "Program" will mean the Content.\n\ +\n\ +Content includes, but is not limited to, source code, object code,\n\ +documentation and other files maintained in the Eclipse Foundation source code\n\ +repository ("Repository") in software modules ("Modules") and made available\n\ +as downloadable archives ("Downloads").\n\ +\n\ + - Content may be structured and packaged into modules to facilitate delivering,\n\ + extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"),\n\ + plug-in fragments ("Fragments"), and features ("Features").\n\ + - Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java(TM) ARchive)\n\ + in a directory named "plugins".\n\ + - A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material.\n\ + Each Feature may be packaged as a sub-directory in a directory named "features".\n\ + Within a Feature, files named "feature.xml" may contain a list of the names and version\n\ + numbers of the Plug-ins and/or Fragments associated with that Feature.\n\ + - Features may also include other Features ("Included Features"). Within a Feature, files\n\ + named "feature.xml" may contain a list of the names and version numbers of Included Features.\n\ +\n\ +The terms and conditions governing Plug-ins and Fragments should be\n\ +contained in files named "about.html" ("Abouts"). The terms and\n\ +conditions governing Features and Included Features should be contained\n\ +in files named "license.html" ("Feature Licenses"). Abouts and Feature\n\ +Licenses may be located in any directory of a Download or Module\n\ +including, but not limited to the following locations:\n\ +\n\ + - The top-level (root) directory\n\ + - Plug-in and Fragment directories\n\ + - Inside Plug-ins and Fragments packaged as JARs\n\ + - Sub-directories of the directory named "src" of certain Plug-ins\n\ + - Feature directories\n\ +\n\ +Note: if a Feature made available by the Eclipse Foundation is installed using the\n\ +Provisioning Technology (as defined below), you must agree to a license ("Feature \n\ +Update License") during the installation process. If the Feature contains\n\ +Included Features, the Feature Update License should either provide you\n\ +with the terms and conditions governing the Included Features or inform\n\ +you where you can locate them. Feature Update Licenses may be found in\n\ +the "license" property of files named "feature.properties" found within a Feature.\n\ +Such Abouts, Feature Licenses, and Feature Update Licenses contain the\n\ +terms and conditions (or references to such terms and conditions) that\n\ +govern your use of the associated Content in that directory.\n\ +\n\ +THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER\n\ +TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS.\n\ +SOME OF THESE OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):\n\ +\n\ + - Common Public License Version 1.0 (available at http://www.eclipse.org/legal/cpl-v10.html)\n\ + - Apache Software License 1.1 (available at http://www.apache.org/licenses/LICENSE)\n\ + - Apache Software License 2.0 (available at http://www.apache.org/licenses/LICENSE-2.0)\n\ + - Metro Link Public License 1.00 (available at http://www.opengroup.org/openmotif/supporters/metrolink/license.html)\n\ + - Mozilla Public License Version 1.1 (available at http://www.mozilla.org/MPL/MPL-1.1.html)\n\ +\n\ +IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR\n\ +TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License\n\ +is provided, please contact the Eclipse Foundation to determine what terms and conditions\n\ +govern that particular Content.\n\ +\n\ +\n\Use of Provisioning Technology\n\ +\n\ +The Eclipse Foundation makes available provisioning software, examples of which include,\n\ +but are not limited to, p2 and the Eclipse Update Manager ("Provisioning Technology") for\n\ +the purpose of allowing users to install software, documentation, information and/or\n\ +other materials (collectively "Installable Software"). This capability is provided with\n\ +the intent of allowing such users to install, extend and update Eclipse-based products.\n\ +Information about packaging Installable Software is available at\n\ +http://eclipse.org/equinox/p2/repository_packaging.html ("Specification").\n\ +\n\ +You may use Provisioning Technology to allow other parties to install Installable Software.\n\ +You shall be responsible for enabling the applicable license agreements relating to the\n\ +Installable Software to be presented to, and accepted by, the users of the Provisioning Technology\n\ +in accordance with the Specification. By using Provisioning Technology in such a manner and\n\ +making it available in accordance with the Specification, you further acknowledge your\n\ +agreement to, and the acquisition of all necessary rights to permit the following:\n\ +\n\ + 1. A series of actions may occur ("Provisioning Process") in which a user may execute\n\ + the Provisioning Technology on a machine ("Target Machine") with the intent of installing,\n\ + extending or updating the functionality of an Eclipse-based product.\n\ + 2. During the Provisioning Process, the Provisioning Technology may cause third party\n\ + Installable Software or a portion thereof to be accessed and copied to the Target Machine.\n\ + 3. Pursuant to the Specification, you will provide to the user the terms and conditions that\n\ + govern the use of the Installable Software ("Installable Software Agreement") and such\n\ + Installable Software Agreement shall be accessed from the Target Machine in accordance\n\ + with the Specification. Such Installable Software Agreement must inform the user of the\n\ + terms and conditions that govern the Installable Software and must solicit acceptance by\n\ + the end user in the manner prescribed in such Installable Software Agreement. Upon such\n\ + indication of agreement by the user, the provisioning Technology will complete installation\n\ + of the Installable Software.\n\ +\n\ +Cryptography\n\ +\n\ +Content may contain encryption software. The country in which you are\n\ +currently may have restrictions on the import, possession, and use,\n\ +and/or re-export to another country, of encryption software. BEFORE\n\ +using any encryption software, please check the country's laws,\n\ +regulations and policies concerning the import, possession, or use, and\n\ +re-export of encryption software, to see if this is permitted.\n\ +\n\ +Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.\n diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml new file mode 100644 index 00000000..cfe53606 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/feature.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Copyright (c) 2011 Tasktop Technologies and others. + 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 + http://www.eclipse.org/legal/epl-v10.html + + Contributors: + Tasktop Technologies - initial API and implementation + --> +<feature + id="org.eclipse.mylyn.versions.tasks.sdk" + label="%featureName" + version="0.7.0.qualifier" + provider-name="%providerName" + plugin="org.eclipse.mylyn"> + + <description url="http://eclipse.org/mylyn"> + %description + </description> + + <copyright> + %copyright + </copyright> + + <license url="license.html"> + %license + </license> + + <includes + id="org.eclipse.mylyn.tasks.versions" + version="0.0.0"/> + + <plugin + id="org.eclipse.mylyn.versions.tasks.core.source" + download-size="0" + install-size="0" + version="0.0.0" + unpack="false"/> + + <plugin + id="org.eclipse.mylyn.versions.tasks.ui.source" + download-size="0" + install-size="0" + version="0.0.0" + unpack="false"/> + + +</feature> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/license.html b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/license.html new file mode 100644 index 00000000..c184ca36 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/license.html @@ -0,0 +1,107 @@ +<?xml version="1.0" encoding="ISO-8859-1" ?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> +<title>Eclipse Foundation Software User Agreement</title> +</head> + +<body lang="EN-US"> +<h2>Eclipse Foundation Software User Agreement</h2> +<p>April 14, 2010</p> + +<h3>Usage Of Content</h3> + +<p>THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS + (COLLECTIVELY &quot;CONTENT&quot;). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND + CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE + OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR + NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND + CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.</p> + +<h3>Applicable Licenses</h3> + +<p>Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 + (&quot;EPL&quot;). A copy of the EPL is provided with this Content and is also available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. + For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> + +<p>Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code + repository (&quot;Repository&quot;) in software modules (&quot;Modules&quot;) and made available as downloadable archives (&quot;Downloads&quot;).</p> + +<ul> + <li>Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins (&quot;Plug-ins&quot;), plug-in fragments (&quot;Fragments&quot;), and features (&quot;Features&quot;).</li> + <li>Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java&trade; ARchive) in a directory named &quot;plugins&quot;.</li> + <li>A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named &quot;features&quot;. Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of the Plug-ins + and/or Fragments associated with that Feature.</li> + <li>Features may also include other Features (&quot;Included Features&quot;). Within a Feature, files named &quot;feature.xml&quot; may contain a list of the names and version numbers of Included Features.</li> +</ul> + +<p>The terms and conditions governing Plug-ins and Fragments should be contained in files named &quot;about.html&quot; (&quot;Abouts&quot;). The terms and conditions governing Features and +Included Features should be contained in files named &quot;license.html&quot; (&quot;Feature Licenses&quot;). Abouts and Feature Licenses may be located in any directory of a Download or Module +including, but not limited to the following locations:</p> + +<ul> + <li>The top-level (root) directory</li> + <li>Plug-in and Fragment directories</li> + <li>Inside Plug-ins and Fragments packaged as JARs</li> + <li>Sub-directories of the directory named &quot;src&quot; of certain Plug-ins</li> + <li>Feature directories</li> +</ul> + +<p>Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license (&quot;Feature Update License&quot;) during the +installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or +inform you where you can locate them. Feature Update Licenses may be found in the &quot;license&quot; property of files named &quot;feature.properties&quot; found within a Feature. +Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in +that directory.</p> + +<p>THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE +OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):</p> + +<ul> + <li>Common Public License Version 1.0 (available at <a href="http://www.eclipse.org/legal/cpl-v10.html">http://www.eclipse.org/legal/cpl-v10.html</a>)</li> + <li>Apache Software License 1.1 (available at <a href="http://www.apache.org/licenses/LICENSE">http://www.apache.org/licenses/LICENSE</a>)</li> + <li>Apache Software License 2.0 (available at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>)</li> + <li>Metro Link Public License 1.00 (available at <a href="http://www.opengroup.org/openmotif/supporters/metrolink/license.html">http://www.opengroup.org/openmotif/supporters/metrolink/license.html</a>)</li> + <li>Mozilla Public License Version 1.1 (available at <a href="http://www.mozilla.org/MPL/MPL-1.1.html">http://www.mozilla.org/MPL/MPL-1.1.html</a>)</li> +</ul> + +<p>IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please +contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.</p> + + +<h3>Use of Provisioning Technology</h3> + +<p>The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse + Update Manager (&quot;Provisioning Technology&quot;) for the purpose of allowing users to install software, documentation, information and/or + other materials (collectively &quot;Installable Software&quot;). This capability is provided with the intent of allowing such users to + install, extend and update Eclipse-based products. Information about packaging Installable Software is available at <a + href="http://eclipse.org/equinox/p2/repository_packaging.html">http://eclipse.org/equinox/p2/repository_packaging.html</a> + (&quot;Specification&quot;).</p> + +<p>You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the + applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology + in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the + Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:</p> + +<ol> + <li>A series of actions may occur (&quot;Provisioning Process&quot;) in which a user may execute the Provisioning Technology + on a machine (&quot;Target Machine&quot;) with the intent of installing, extending or updating the functionality of an Eclipse-based + product.</li> + <li>During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be + accessed and copied to the Target Machine.</li> + <li>Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable + Software (&quot;Installable Software Agreement&quot;) and such Installable Software Agreement shall be accessed from the Target + Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern + the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such + indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.</li> +</ol> + +<h3>Cryptography</h3> + +<p>Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to + another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, + possession, or use, and re-export of encryption software, to see if this is permitted.</p> + +<p><small>Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.</small></p> +</body> +</html> diff --git a/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml new file mode 100644 index 00000000..492a473c --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.sdk-feature/pom.xml @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <artifactId>mylyn-versions-tasks-parent</artifactId> + <groupId>org.eclipse.mylyn.versions</groupId> + <version>0.7.0-SNAPSHOT</version> + </parent> + <groupId>org.eclipse.mylyn.versions</groupId> + <artifactId>org.eclipse.mylyn.versions.tasks.sdk</artifactId> + <version>0.7.0-SNAPSHOT</version> + <packaging>eclipse-feature</packaging> +</project> diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/.classpath b/versions/org.eclipse.mylyn.versions.tasks.ui/.classpath new file mode 100644 index 00000000..64c5e31b --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/.classpath @@ -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/J2SE-1.5"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="output" path="bin"/> +</classpath> diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/.project b/versions/org.eclipse.mylyn.versions.tasks.ui/.project new file mode 100644 index 00000000..b9f9950b --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/.project @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.mylyn.versions.tasks.ui</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> diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks.ui/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..40db1b2e --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Feb 22 18:52:23 PST 2011 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF b/versions/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF new file mode 100644 index 00000000..b093dd93 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: %Bundle-Name +Bundle-SymbolicName: org.eclipse.mylyn.versions.tasks.ui;singleton:=true +Bundle-Version: 0.1.0.qualifier +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + org.eclipse.mylyn.versions.core;bundle-version="0.1.0", + org.eclipse.mylyn.tasks.ui;bundle-version="3.5.0", + org.eclipse.ui.forms;bundle-version="3.5.2", + org.eclipse.mylyn.tasks.core;bundle-version="3.5.0", + org.eclipse.mylyn.versions.ui;bundle-version="0.1.0", + org.eclipse.mylyn.versions.tasks.core;bundle-version="0.0.1" +Bundle-ActivationPolicy: lazy +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Export-Package: org.eclipse.mylyn.versions.tasks.ui;x-internal:=true +Bundle-Vendor: %Bundle-Vendor diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/about.html b/versions/org.eclipse.mylyn.versions.tasks.ui/about.html new file mode 100644 index 00000000..d774b07c --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/about.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> +<head> +<title>About</title> +<meta http-equiv=Content-Type content="text/html; charset=ISO-8859-1"> +</head> +<body lang="EN-US"> +<h2>About This Content</h2> + +<p>June 25, 2008</p> +<h3>License</h3> + +<p>The Eclipse Foundation makes available all content in this plug-in (&quot;Content&quot;). Unless otherwise +indicated below, the Content is provided to you under the terms and conditions of the +Eclipse Public License Version 1.0 (&quot;EPL&quot;). A copy of the EPL is available +at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>. +For purposes of the EPL, &quot;Program&quot; will mean the Content.</p> + +<p>If you did not receive this Content directly from the Eclipse Foundation, the Content is +being redistributed by another party (&quot;Redistributor&quot;) and different terms and conditions may +apply to your use of any object code in the Content. Check the Redistributor's license that was +provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise +indicated below, the terms and conditions of the EPL still apply to any source code in the Content +and such source code may be obtained at <a href="/">http://www.eclipse.org</a>.</p> + +</body> +</html> \ No newline at end of file diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/build.properties b/versions/org.eclipse.mylyn.versions.tasks.ui/build.properties new file mode 100644 index 00000000..e9863e28 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/plugin.properties b/versions/org.eclipse.mylyn.versions.tasks.ui/plugin.properties new file mode 100644 index 00000000..eee282ab --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/plugin.properties @@ -0,0 +1,12 @@ +############################################################################### +# Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology and others. +# 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 +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation +############################################################################### +Bundle-Vendor = Eclipse Mylyn +Bundle-Name = Mylyn Versions Framework Task Integration diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/plugin.xml b/versions/org.eclipse.mylyn.versions.tasks.ui/plugin.xml new file mode 100644 index 00000000..2d1fa5ed --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/plugin.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="UTF-8"?> +<?eclipse version="3.4"?> +<plugin> + <extension + point="org.eclipse.mylyn.tasks.ui.editors"> + <pageFactory + class="org.eclipse.mylyn.versions.tasks.ui.ChangeSetPageFactory" + id="org.eclipse.mylyn.versions.tasks.pageFactory1"> + </pageFactory> + </extension> + +</plugin> diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/pom.xml b/versions/org.eclipse.mylyn.versions.tasks.ui/pom.xml new file mode 100644 index 00000000..c3d30f40 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/pom.xml @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <artifactId>mylyn-versions-tasks-parent</artifactId> + <groupId>org.eclipse.mylyn.versions</groupId> + <version>0.7.0-SNAPSHOT</version> + </parent> + <artifactId>org.eclipse.mylyn.versions.tasks.ui</artifactId> + <version>0.1.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + <build> + <plugins> + <plugin> + <groupId>org.sonatype.tycho</groupId> + <artifactId>maven-osgi-source-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.codehaus.mojo</groupId> + <artifactId>findbugs-maven-plugin</artifactId> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-pmd-plugin</artifactId> + </plugin> + </plugins> + </build> +</project> diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPage.java b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPage.java new file mode 100644 index 00000000..ad70d593 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPage.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.ui; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.jface.action.IToolBarManager; +import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage; +import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; +import org.eclipse.mylyn.tasks.ui.editors.TaskEditor; +import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput; +import org.eclipse.mylyn.tasks.ui.editors.TaskEditorPartDescriptor; + +/** + * + * @author Kilian Matt + * + */ +public class ChangeSetPage extends AbstractTaskEditorPage { + + public ChangeSetPage(TaskEditor editor) { + super(editor, ((TaskEditorInput) editor.getEditorInput()) + .getTaskRepository().getConnectorKind()); + } + + @Override + protected Set<TaskEditorPartDescriptor> createPartDescriptors() { + Set<TaskEditorPartDescriptor> descriptors = new HashSet<TaskEditorPartDescriptor>(); + descriptors.add(new TaskEditorPartDescriptor("") { + @Override + public AbstractTaskEditorPart createPart() { + return new ChangesetPart(); + } + }); + return descriptors; + } + @Override + public void fillToolBar(IToolBarManager toolBarManager) { + + } +} diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java new file mode 100644 index 00000000..d5a530d0 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangeSetPageFactory.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.ui; + +import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory; +import org.eclipse.mylyn.tasks.ui.editors.TaskEditor; +import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput; +import org.eclipse.swt.graphics.Image; +import org.eclipse.ui.forms.editor.IFormPage; + +/** + * + * @author Kilian Matt + * + */ +public class ChangeSetPageFactory extends AbstractTaskEditorPageFactory { + + public ChangeSetPageFactory() { + } + + @Override + public boolean canCreatePageFor(TaskEditorInput input) { + return true; + } + + @Override + public IFormPage createPage(TaskEditor parentEditor) { + return new ChangeSetPage(parentEditor); + } + + @Override + public Image getPageImage() { + return null; + } + + @Override + public String getPageText() { + return "Changeset"; + } + +} diff --git a/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java new file mode 100644 index 00000000..cd5c8fb1 --- /dev/null +++ b/versions/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java @@ -0,0 +1,169 @@ +/******************************************************************************* + * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.versions.tasks.ui; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.action.MenuManager; +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.ILabelProviderListener; +import org.eclipse.jface.viewers.ITableLabelProvider; +import org.eclipse.jface.viewers.TableViewer; +import org.eclipse.jface.viewers.TableViewerColumn; +import org.eclipse.mylyn.tasks.core.ITask; +import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; +import org.eclipse.mylyn.versions.core.ChangeSet; +import org.eclipse.mylyn.versions.core.ScmCore; +import org.eclipse.mylyn.versions.core.ScmRepository; +import org.eclipse.mylyn.versions.core.spi.ScmConnector; +import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.FillLayout; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.Section; + +/** + * + * @author Kilian Matt + * + */ +public class ChangesetPart extends AbstractTaskEditorPart { + public ChangesetPart() { + setPartName("Changeset"); + setExpandVertically(true); + } + + @Override + public void createControl(Composite parent, FormToolkit toolkit) { + Section createSection = createSection(parent, toolkit, true); + createSection.setText("Changesets"); + setSection(toolkit, createSection); + GridLayout gl = new GridLayout(1, false); + gl.marginBottom = 16; + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + gd.horizontalSpan = 4; + createSection.setLayout(gl); + createSection.setLayoutData(gd); + Composite composite = toolkit.createComposite(createSection); + createSection.setClient(composite); + composite.setLayout(new FillLayout()); + + TableViewer table = new TableViewer(composite); + table.getTable().setLinesVisible(true); + table.getTable().setHeaderVisible(true); + TableViewerColumn tableViewerColumn = new TableViewerColumn(table, + SWT.LEFT); + tableViewerColumn.getColumn().setText("Id"); + tableViewerColumn.getColumn().setWidth(100); + tableViewerColumn = new TableViewerColumn(table, SWT.LEFT); + tableViewerColumn.getColumn().setText("Message"); + tableViewerColumn.getColumn().setWidth(100); + tableViewerColumn = new TableViewerColumn(table, SWT.LEFT); + tableViewerColumn.getColumn().setText("Author"); + tableViewerColumn.getColumn().setWidth(100); + tableViewerColumn = new TableViewerColumn(table, SWT.LEFT); + tableViewerColumn.getColumn().setText("Date"); + tableViewerColumn.getColumn().setWidth(100); + table.setContentProvider(ArrayContentProvider.getInstance()); + table.setLabelProvider(new ITableLabelProvider() { + + + public void addListener(ILabelProviderListener listener) { + } + + + public void dispose() { + } + + + public boolean isLabelProperty(Object element, String property) { + return false; + } + + + public void removeListener(ILabelProviderListener listener) { + } + + + public Image getColumnImage(Object element, int columnIndex) { + return null; + } + + + public String getColumnText(Object element, int columnIndex) { + TaskChangeSet cs = ((TaskChangeSet) element); + switch (columnIndex) { + case 0: + return cs.getChangeset().getId(); + case 1: + return cs.getChangeset().getMessage(); + case 2: + return cs.getChangeset().getAuthor().getEmail(); + case 3: + return cs.getChangeset().getDate().toString(); + } + return element.toString() + " " + columnIndex; + } + }); + table.setInput(getInput()); + MenuManager menuManager = new MenuManager(); + menuManager.setRemoveAllWhenShown(true); + getTaskEditorPage().getEditorSite().registerContextMenu( + "org.eclipse.mylyn.versions.changesets", menuManager, table, + true); + org.eclipse.swt.widgets.Menu menu = menuManager.createContextMenu(table + .getControl()); + table.getTable().setMenu(menu); + + } + + private List<TaskChangeSet> getInput() { + List<ScmConnector> connectors = ScmCore.getAllRegisteredConnectors(); + for (ScmConnector c : connectors) { + try { + List<ScmRepository> repositories = c + .getRepositories(new NullProgressMonitor()); + for (ScmRepository r : repositories) { + ITask task = getModel().getTask(); + List<TaskChangeSet> changes = new ArrayList<TaskChangeSet>(); + List<ChangeSet> changeSets = c.getChangeSets(r, + new NullProgressMonitor()); + if (changeSets == null) + continue; + for (ChangeSet cs : changeSets) { + if (changeSetMatches(cs)) + changes.add(new TaskChangeSet(task, cs)); + } + if (!changes.isEmpty()) + return changes; + } + } catch (CoreException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + return null; + } + + private boolean changeSetMatches(ChangeSet cs) { + return cs.getMessage().contains(getModel().getTask().getTaskKey()) + || cs.getMessage().contains(getModel().getTask().getUrl()); + } + +} diff --git a/versions/pom.xml b/versions/pom.xml new file mode 100644 index 00000000..8c91afb3 --- /dev/null +++ b/versions/pom.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.eclipse.mylyn</groupId> + <artifactId>mylyn-parent</artifactId> + <version>3.5.0-SNAPSHOT</version> + <relativePath>../../org.eclipse.mylyn/org.eclipse.mylyn.releng</relativePath> + </parent> + <groupId>org.eclipse.mylyn.versions</groupId> + <artifactId>mylyn-versions-tasks-parent</artifactId> + <version>0.7.0-SNAPSHOT</version> + <packaging>pom</packaging> + <modules> + <module>org.eclipse.mylyn.versions.tasks-feature</module> + <module>org.eclipse.mylyn.versions.tasks.core</module> + <module>org.eclipse.mylyn.versions.tasks.sdk-feature</module> + <module>org.eclipse.mylyn.versions.tasks.ui</module> + </modules> + <build> + <plugins> + <plugin> + <groupId>org.sonatype.tycho</groupId> + <artifactId>tycho-maven-plugin</artifactId> + <version>0.10.0</version> + <extensions>true</extensions> + </plugin> + </plugins> + </build> +</project>
b88e6a1a3e700c0c36522b64474b5df624bcc527
tapiji
Removes outdated dependency to org.apache.io lib.
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF index eecc0db7..d207a626 100644 --- a/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.translator.rap/META-INF/MANIFEST.MF @@ -5,6 +5,5 @@ Bundle-SymbolicName: org.eclipselabs.tapiji.translator.rap;singleton:=true Bundle-Version: 0.0.2.qualifier Fragment-Host: org.eclipselabs.tapiji.translator;bundle-version="0.0.2" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: org.eclipse.rap.ui, - org.apache.commons.io;bundle-version="2.0.1" +Require-Bundle: org.eclipse.rap.ui Export-Package: org.eclipselabs.tapiji.translator.views.widgets.provider;uses:="org.eclipse.ui,org.eclipse.jface.viewers"
8dc78ca7af53778f2e156e575551a3bcab1d1f7b
intellij-community
IDEA-70843 (fix Hector slider for GTK+ L&F)--
c
https://github.com/JetBrains/intellij-community
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java index 1792a1f8a9272..93ea6d6eb88e8 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HectorComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,6 +50,7 @@ import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; +import javax.swing.plaf.basic.BasicSliderUI; import java.awt.*; import java.lang.ref.WeakReference; import java.util.*; @@ -82,6 +83,7 @@ public HectorComponent(PsiFile file) { final FileViewProvider viewProvider = myFile.getViewProvider(); final Set<Language> languages = viewProvider.getLanguages(); for (Language language : languages) { + @SuppressWarnings("UseOfObsoleteCollectionType") final Hashtable<Integer, JLabel> sliderLabels = new Hashtable<Integer, JLabel>(); sliderLabels.put(1, new JLabel(EditorBundle.message("hector.none.slider.label"))); sliderLabels.put(2, new JLabel(EditorBundle.message("hector.syntax.slider.label"))); @@ -90,9 +92,13 @@ public HectorComponent(PsiFile file) { } final JSlider slider = new JSlider(SwingConstants.VERTICAL, 1, notInLibrary ? 3 : 2, 1); + if (UIUtil.isUnderGTKLookAndFeel()) { + // default GTK+ slider UI is way too ugly + slider.putClientProperty("Slider.paintThumbArrowShape", true); + slider.setUI(new BasicSliderUI(slider)); + } slider.setLabelTable(sliderLabels); - final boolean value = true; - UIUtil.setSliderIsFilled(slider, value); + UIUtil.setSliderIsFilled(slider, true); slider.setPaintLabels(true); slider.setSnapToTicks(true); slider.addChangeListener(new ChangeListener() { @@ -104,13 +110,13 @@ public void stateChanged(ChangeEvent e) { } } }); + final PsiFile psiRoot = viewProvider.getPsi(language); + assert psiRoot != null : "No root in " + viewProvider + " for " + language; slider.setValue(getValue(HighlightLevelUtil.shouldHighlight(psiRoot), HighlightLevelUtil.shouldInspect(psiRoot))); mySliders.put(language, slider); } - final DaemonCodeAnalyzer analyzer = DaemonCodeAnalyzer.getInstance(myFile.getProject()); - GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0); @@ -249,6 +255,7 @@ private void forceDaemonRestart() { for (Language language : mySliders.keySet()) { JSlider slider = mySliders.get(language); PsiElement root = viewProvider.getPsi(language); + assert root != null : "No root in " + viewProvider + " for " + language; int value = slider.getValue(); if (value == 1) { HighlightLevelUtil.forceRootHighlighting(root, FileHighlighingSetting.SKIP_HIGHLIGHTING); @@ -269,7 +276,7 @@ private boolean isModified() { for (Language language : mySliders.keySet()) { JSlider slider = mySliders.get(language); final PsiFile root = viewProvider.getPsi(language); - if (getValue(HighlightLevelUtil.shouldHighlight(root), HighlightLevelUtil.shouldInspect(root)) != slider.getValue()) { + if (root != null && getValue(HighlightLevelUtil.shouldHighlight(root), HighlightLevelUtil.shouldInspect(root)) != slider.getValue()) { return true; } }
f1be5f4addf30f47b1d915ca708566bf49beb7f8
ReactiveX-RxJava
Non-blocking implementation of ScheduledObserver--
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/operators/ScheduledObserver.java b/rxjava-core/src/main/java/rx/operators/ScheduledObserver.java index 3c3592ec9e..a7f1dc2878 100644 --- a/rxjava-core/src/main/java/rx/operators/ScheduledObserver.java +++ b/rxjava-core/src/main/java/rx/operators/ScheduledObserver.java @@ -21,13 +21,14 @@ import rx.util.functions.Action0; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; /* package */class ScheduledObserver<T> implements Observer<T> { private final Observer<T> underlying; private final Scheduler scheduler; private final ConcurrentLinkedQueue<Notification<T>> queue = new ConcurrentLinkedQueue<Notification<T>>(); - private final Object lock = new Object(); + private final AtomicInteger counter = new AtomicInteger(0); public ScheduledObserver(Observer<T> underlying, Scheduler scheduler) { this.underlying = underlying; @@ -50,48 +51,43 @@ public void onNext(final T args) { } private void enqueue(Notification<T> notification) { - boolean schedule; - synchronized (lock) { - schedule = queue.isEmpty(); + int count = counter.getAndIncrement(); - queue.offer(notification); + queue.offer(notification); + + if (count == 0) { + processQueue(); } + } - if (schedule) { - scheduler.schedule(new Action0() { - @Override - public void call() { - Notification<T> not = dequeue(); - - if (not == null) { - return; - } - - switch (not.getKind()) { - case OnNext: - underlying.onNext(not.getValue()); - break; - case OnError: - underlying.onError(not.getException()); - break; - case OnCompleted: - underlying.onCompleted(); - break; - default: - throw new IllegalStateException("Unknown kind of notification " + not); - - } + private void processQueue() { + scheduler.schedule(new Action0() { + @Override + public void call() { + int count = counter.decrementAndGet(); + + Notification<T> not = queue.poll(); + + switch (not.getKind()) { + case OnNext: + underlying.onNext(not.getValue()); + break; + case OnError: + underlying.onError(not.getException()); + break; + case OnCompleted: + underlying.onCompleted(); + break; + default: + throw new IllegalStateException("Unknown kind of notification " + not); - scheduler.schedule(this); + } + if (count > 0) { + scheduler.schedule(this); } - }); - } - } - private Notification<T> dequeue() { - synchronized (lock) { - return queue.poll(); - } + } + }); } }
dd897c807e495d1dbc76c21e9e944dbe030076b7
drools
JBRULES-1820 Exception: Input stream is not- explicitly closed.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@36154 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
c
https://github.com/kiegroup/drools
diff --git a/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java b/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java index e3405e92fa6..d445923812e 100644 --- a/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java +++ b/drools-compiler/src/main/java/org/drools/commons/jci/compilers/EclipseJavaCompiler.java @@ -236,23 +236,24 @@ private NameEnvironmentAnswer findType( final String pClazzName ) { } } - - final InputStream is = pClassLoader.getResourceAsStream(resourceName); - if (is == null) { - return null; - } - - final byte[] buffer = new byte[8192]; - final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length); - int count; + InputStream is = null; + ByteArrayOutputStream baos = null; try { - while ((count = is.read(buffer, 0, buffer.length)) > 0) { - baos.write(buffer, 0, count); + is = pClassLoader.getResourceAsStream(resourceName); + if (is == null) { + return null; } - baos.flush(); - final char[] fileName = pClazzName.toCharArray(); - final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true); - return new NameEnvironmentAnswer(classFileReader, null); + + final byte[] buffer = new byte[8192]; + baos = new ByteArrayOutputStream(buffer.length); + int count; + while ((count = is.read(buffer, 0, buffer.length)) > 0) { + baos.write(buffer, 0, count); + } + baos.flush(); + final char[] fileName = pClazzName.toCharArray(); + final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true); + return new NameEnvironmentAnswer(classFileReader, null); } catch ( final IOException e ) { throw new RuntimeException( "could not read class", e ); @@ -261,13 +262,17 @@ private NameEnvironmentAnswer findType( final String pClazzName ) { e ); } finally { try { - baos.close(); + if (baos != null ) { + baos.close(); + } } catch ( final IOException oe ) { throw new RuntimeException( "could not close output stream", oe ); } try { - is.close(); + if ( is != null ) { + is.close(); + } } catch ( final IOException ie ) { throw new RuntimeException( "could not close input stream", ie ); @@ -276,19 +281,29 @@ private NameEnvironmentAnswer findType( final String pClazzName ) { } private boolean isPackage( final String pClazzName ) { - - final InputStream is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName)); - if (is != null) { - return false; - } - - // FIXME: this should not be tied to the extension - final String source = pClazzName.replace('.', '/') + ".java"; - if (pReader.isAvailable(source)) { - return false; + InputStream is = null; + try { + is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName)); + if (is != null) { + return false; + } + + // FIXME: this should not be tied to the extension + final String source = pClazzName.replace('.', '/') + ".java"; + if (pReader.isAvailable(source)) { + return false; + } + + return true; + } finally { + if ( is != null ) { + try { + is.close(); + } catch ( IOException e ) { + throw new RuntimeException( "Unable to close stream for resource: " + pClazzName ); + } + } } - - return true; } public boolean isPackage( char[][] parentPackageName, char[] pPackageName ) {
a0a3baeaeaf96094b7b174ad2faaa48de185e50e
tapiji
Fixes bug in generation of Java bundle key hovers.
c
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java b/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java index 74708c6b..c05a88fd 100644 --- a/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java +++ b/org.eclipselabs.tapiji.tools.java/src/auditor/ResourceAuditVisitor.java @@ -41,6 +41,7 @@ public class ResourceAuditVisitor extends ASTVisitor implements private List<SLLocation> brokenRBReferences; private SortedMap<Long, IRegion> rbDefReferences = new TreeMap<Long, IRegion>(); private SortedMap<Long, IRegion> keyPositions = new TreeMap<Long, IRegion>(); + private Map<IRegion, String> bundleKeys = new HashMap<IRegion, String>(); private Map<IRegion, String> bundleReferences = new HashMap<IRegion, String>(); private IFile file; private Map<IVariableBinding, VariableDeclarationFragment> variableBindingManagers = new HashMap<IVariableBinding, VariableDeclarationFragment>(); @@ -114,6 +115,7 @@ public boolean visit(StringLiteral stringLiteral) { // store position of resource-bundle access keyPositions.put(Long.valueOf(stringLiteral .getStartPosition()), region); + bundleKeys.put(region, stringLiteral.getLiteralValue()); bundleReferences.put(region, rbName.getLiteral()); return false; } else if (ASTutils.isMatchingMethodParamDesc(methodInvocation, @@ -180,6 +182,13 @@ public IRegion getKeyAt(Long position) { return reg; } + + public String getKeyAt(IRegion region) { + if (bundleKeys.containsKey(region)) + return bundleKeys.get(region); + else + return ""; + } public String getBundleReference(IRegion region) { return bundleReferences.get(region); diff --git a/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java b/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java index a0e12a53..02db084d 100644 --- a/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java +++ b/org.eclipselabs.tapiji.tools.java/src/ui/ConstantStringHover.java @@ -64,17 +64,14 @@ public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { if (hoverRegion == null) return null; - try { - String hoverText = manager.getKeyHoverString(csf.getBundleReference(hoverRegion), textViewer.getDocument().get( - hoverRegion.getOffset()+1, hoverRegion.getLength()-2)); - if (hoverText == null || hoverText.equals("")) - return null; - else - return hoverText; - } catch (BadLocationException e) { - e.printStackTrace(); - } - return null; + String bundleName = csf.getBundleReference(hoverRegion); + String key = csf.getKeyAt(hoverRegion); + + String hoverText = manager.getKeyHoverString(bundleName, key); + if (hoverText == null || hoverText.equals("")) + return null; + else + return hoverText; } @Override
6ecd0a21f1545357c3bd8e9b4a161f158c8d11eb
Mylyn Reviews
322734: review type identification fallback
c
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java index eeeadcf5..d1a7e91b 100644 --- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java +++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java @@ -49,16 +49,22 @@ public static List<ReviewSubTask> getReviewSubTasksFor( List<ReviewSubTask> resultList = new ArrayList<ReviewSubTask>(); try { for (ITask subTask : taskContainer.getChildren()) { - + if (!ReviewsUtil.hasReviewMarker(subTask)) { + TaskData taskData = taskDataManager.getTaskData(subTask); + if(getReviewAttachments(repositoryModel, taskData).size()>0){ + ReviewsUtil.markAsReview(subTask); + } + } + if (ReviewsUtil.isMarkedAsReview(subTask)) {//.getSummary().startsWith("Review")) { //$NON-NLS-1$ // change to review data manager for (Review review : getReviewAttachmentFromTask( taskDataManager, repositoryModel, subTask)) { // TODO change to latest etc - if(review.getResult()!=null) - resultList.add(new ReviewSubTask(getPatchFile(review - .getScope()), getPatchCreationDate(review - .getScope()), + if (review.getResult() != null) + resultList.add(new ReviewSubTask( + getPatchFile(review.getScope()), + getPatchCreationDate(review.getScope()), getAuthorString(review.getScope()), subTask .getOwner(), review.getResult() .getRating(), review.getResult() @@ -114,8 +120,8 @@ static List<Review> parseAttachments(TaskAttribute attribute, TaskAttribute.ATTACHMENT_URL).getValue()); ZipInputStream stream = new ZipInputStream(url.openStream()); - while (!stream.getNextEntry().getName().equals( - ReviewConstants.REVIEW_DATA_FILE)) { + while (!stream.getNextEntry().getName() + .equals(ReviewConstants.REVIEW_DATA_FILE)) { } ResourceSet resourceSet = new ResourceSetImpl(); @@ -142,24 +148,36 @@ public static List<Review> getReviewAttachmentFromTask( List<Review> reviews = new ArrayList<Review>(); TaskData taskData = taskDataManager.getTaskData(task); if (taskData != null) { - List<TaskAttribute> attributesByType = taskData - .getAttributeMapper().getAttributesByType(taskData, - TaskAttribute.TYPE_ATTACHMENT); - for (TaskAttribute attribute : attributesByType) { - // TODO move RepositoryModel.createTaskAttachment to interface? - ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel) - .createTaskAttachment(attribute); - if (taskAttachment!=null&&taskAttachment.getFileName().equals( - ReviewConstants.REVIEW_DATA_CONTAINER)) { - reviews.addAll(parseAttachments(attribute, - new NullProgressMonitor())); - } + for (TaskAttribute attribute : getReviewAttachments( + repositoryModel, taskData)) { + reviews.addAll(parseAttachments(attribute, + new NullProgressMonitor())); + } } return reviews; } + public static List<TaskAttribute> getReviewAttachments( + IRepositoryModel repositoryModel, TaskData taskData) { + + List<TaskAttribute> matchingAttributes = new ArrayList<TaskAttribute>(); + List<TaskAttribute> attributesByType = taskData.getAttributeMapper() + .getAttributesByType(taskData, TaskAttribute.TYPE_ATTACHMENT); + for (TaskAttribute attribute : attributesByType) { + // TODO move RepositoryModel.createTaskAttachment to interface? + ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel) + .createTaskAttachment(attribute); + if (taskAttachment != null + && taskAttachment.getFileName().equals( + ReviewConstants.REVIEW_DATA_CONTAINER)) { + matchingAttributes.add(attribute); + } + } + return matchingAttributes; + } + private static List<ITargetPathStrategy> strategies; static { strategies = new ArrayList<ITargetPathStrategy>(); @@ -167,7 +185,6 @@ public static List<Review> getReviewAttachmentFromTask( strategies.add(new GitPatchPathFindingStrategy()); } - public static List<? extends ITargetPathStrategy> getPathFindingStrategies() { return strategies; } @@ -179,6 +196,11 @@ public static boolean isMarkedAsReview(ITask task) { } public static void markAsReview(ITask task) { - task.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG, Boolean.TRUE.toString()); + task.setAttribute(ReviewConstants.ATTR_REVIEW_FLAG, + Boolean.TRUE.toString()); + } + + public static boolean hasReviewMarker(ITask task) { + return task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG) != null; } } diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java index 75df46d7..94a62a2d 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java @@ -23,6 +23,7 @@ import org.eclipse.mylyn.reviews.ui.ReviewCommentTaskAttachmentSource; import org.eclipse.mylyn.reviews.ui.ReviewsUiPlugin; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; +import org.eclipse.mylyn.tasks.core.IRepositoryModel; import org.eclipse.mylyn.tasks.core.ITask; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; @@ -37,6 +38,21 @@ public class ReviewTaskEditorPartAdvisor implements ITaskEditorPartDescriptorAdvisor { public boolean canCustomize(ITask task) { + if (!ReviewsUtil.hasReviewMarker(task)) { + try { + IRepositoryModel repositoryModel = TasksUi.getRepositoryModel(); + TaskData taskData = TasksUiPlugin.getTaskDataManager() + .getTaskData(task); + if (ReviewsUtil.getReviewAttachments(repositoryModel, taskData) + .size() > 0) { + ReviewsUtil.markAsReview(task); + } + } catch (CoreException e) { + // FIXME + e.printStackTrace(); + } + } + boolean isReview = ReviewsUtil.isMarkedAsReview(task); return isReview; } @@ -101,7 +117,7 @@ public void afterSubmit(ITask task) { connector.getTaskAttachmentHandler().postContent( taskRepository, task, attachment, "review result", //$NON-NLS-1$ attachmentAttribute, new NullProgressMonitor()); - + TasksUiInternal.synchronizeTask(connector, task, false, null); } } catch (CoreException e) {
53283a16be694d75e4e0ae1f8eac1ab2918751a3
Vala
gtk+-2.0: Fix gtk_combo_box_set_row_separator_func binding Fixes bug 606919.
c
https://github.com/GNOME/vala/
diff --git a/vapi/gtk+-2.0.vapi b/vapi/gtk+-2.0.vapi index 29a2cc83f1..4b0f53d992 100644 --- a/vapi/gtk+-2.0.vapi +++ b/vapi/gtk+-2.0.vapi @@ -1008,7 +1008,7 @@ namespace Gtk { public void set_column_span_column (int column_span); public void set_focus_on_click (bool focus_on_click); public void set_model (Gtk.TreeModel? model); - public void set_row_separator_func (Gtk.TreeViewRowSeparatorFunc func, void* data, GLib.DestroyNotify destroy); + public void set_row_separator_func (owned Gtk.TreeViewRowSeparatorFunc func); public void set_row_span_column (int row_span); public void set_title (string title); public void set_wrap_width (int width); diff --git a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata index 92cae74606..681217d11c 100644 --- a/vapi/packages/gtk+-2.0/gtk+-2.0.metadata +++ b/vapi/packages/gtk+-2.0/gtk+-2.0.metadata @@ -103,6 +103,9 @@ gtk_color_selection_get_current_color.color is_out="1" gtk_color_selection_get_previous_color.color is_out="1" gtk_combo_box_get_active_iter.iter is_out="1" gtk_combo_box_set_model.model nullable="1" +gtk_combo_box_set_row_separator_func.func transfer_ownership="1" +gtk_combo_box_set_row_separator_func.data hidden="1" +gtk_combo_box_set_row_separator_func.destroy hidden="1" GtkComboBox::popdown has_emitter="1" GtkComboBox::popup has_emitter="1" GtkContainer::add has_emitter="1"
d1bdfa2c80fa011aef572a598e7a1e0671f70e25
intellij-community
cleanup--
p
https://github.com/JetBrains/intellij-community
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/ToggleShowWhitespacesAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/ToggleShowWhitespacesAction.java index d943dc8a18f39..a46af300fc8d7 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/ToggleShowWhitespacesAction.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/ToggleShowWhitespacesAction.java @@ -12,11 +12,14 @@ import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.actionSystem.ToggleAction; import com.intellij.openapi.editor.Editor; +import org.jetbrains.annotations.Nullable; public class ToggleShowWhitespacesAction extends ToggleAction { public void setSelected(AnActionEvent e, boolean state) { - getEditor(e).getSettings().setWhitespacesShown(state); - getEditor(e).getComponent().repaint(); + final Editor editor = getEditor(e); + assert editor != null; + editor.getSettings().setWhitespacesShown(state); + editor.getComponent().repaint(); } public boolean isSelected(AnActionEvent e) { @@ -24,6 +27,7 @@ public boolean isSelected(AnActionEvent e) { return editor != null && editor.getSettings().isWhitespacesShown(); } + @Nullable private static Editor getEditor(AnActionEvent e) { return e.getData(PlatformDataKeys.EDITOR); }
5cc86d3ca2d04a81a234a75520546884eee29b27
duracloud$duracloud
Updates the hadoop file processor classes to be more easily extended, in order to build on this base for further processing capabilities. Pulls all of the file transfer code into the mapper class, to allow this functionality to be more easily reused or reimplemented. Adds tests. git-svn-id: https://svn.duraspace.org/duracloud/trunk@73 1005ed41-97cd-4a8f-848c-be5b5fe45bcb
p
https://github.com/duracloud/duracloud
diff --git a/services/hadoop-file-processor/pom.xml b/services/hadoop-file-processor/pom.xml index 1d2533180..7ab171b24 100644 --- a/services/hadoop-file-processor/pom.xml +++ b/services/hadoop-file-processor/pom.xml @@ -23,7 +23,7 @@ <configuration> <archive> <manifest> - <mainClass>org.duracloud.services.fileprocessor.FileProcessor</mainClass> + <mainClass>org.duracloud.services.fileprocessor.JobRunner</mainClass> </manifest> </archive> </configuration> diff --git a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobBuilder.java b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobBuilder.java index fdf8e6094..b8644b21c 100644 --- a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobBuilder.java +++ b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobBuilder.java @@ -17,7 +17,7 @@ import java.text.ParseException; /** - * This class constructs a job. + * This class constructs a hadoop job to process files. * * @author: Bill Branan * Date: Aug 5, 2010 @@ -31,9 +31,9 @@ public class JobBuilder { * Constructs a Job builder * * @param inputPathPrefix - * The S3 path from which the input files can be retrieved. + * The path from which the input files can be retrieved. * @param outputPath - * The S3 path to which output files will be written. + * The path to which output files will be written. */ public JobBuilder(final String inputPathPrefix, final String outputPath) { this.inputPathPrefix = inputPathPrefix; @@ -49,15 +49,15 @@ public JobConf getJobConf() throws IOException, ParseException { " and store results in " + outputPath); JobConf conf = new JobConf(JobBuilder.class); - conf.setJobName("ProcessFiles"); + conf.setJobName(getJobName()); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(Text.class); // Configure mappper - conf.setMapperClass(ProcessFileMapper.class); + conf.setMapperClass(getMapper()); // Configure reducer - conf.setReducerClass(ResultsReducer.class); + conf.setReducerClass(getReducer()); conf.setNumReduceTasks(1); // Configure input path @@ -74,4 +74,36 @@ public JobConf getJobConf() throws IOException, ParseException { return conf; } + /** + * Retrieves the name of the hadoop job. + * + * This method can be overridden to provide an alternate job name. + */ + protected String getJobName() { + return "ProcessFiles"; + } + + /** + * Retrieves the mapper class which will be used for perform the hadoop + * mapping tasks. The default mapper performs a simple file processing task. + * + * This method can be overridden to provide an alternate mapper + * implementation class, possibly a subclass of the default mapper. + */ + protected Class getMapper() { + return ProcessFileMapper.class; + } + + /** + * Retrieves the reducer class which will be used to perform the hadoop + * reduction tasks. The default reducer simply collects all output name/value + * pairs and writes it to an output file. + * + * This method can be overridden to provide an alternate reducer + * implementation class. + */ + protected Class getReducer() { + return ResultsReducer.class; + } + } diff --git a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/FileProcessor.java b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobRunner.java similarity index 74% rename from services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/FileProcessor.java rename to services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobRunner.java index c5e7b8542..97787a469 100644 --- a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/FileProcessor.java +++ b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/JobRunner.java @@ -19,43 +19,52 @@ import java.io.IOException; /** - * This is the main point of entry for the file processing hadoop application. + * This is the main point of entry for the hadoop file processing application. * * @author: Bill Branan * Date: Aug 5, 2010 */ -public class FileProcessor { - +public class JobRunner { + + private static String inputPath; + private static String outputPath; + /** * Main method that sets up file processing job. */ - public static void main(String[] args) throws IOException, - java.text.ParseException { + public static void main(String[] args) throws Exception { CommandLine cmd = processArgs(args); - String inputPath = cmd.getOptionValue("input"); + inputPath = cmd.getOptionValue("input"); inputPath = appendTrailingSlash(inputPath); - String outputPath = cmd.getOptionValue("output"); + outputPath = cmd.getOptionValue("output"); outputPath = appendTrailingSlash(outputPath); - runJob(inputPath, outputPath); + runJob(); } // Construct and run the job. - private static void runJob(String inputPath, String outputPath) + private static void runJob() throws IOException, java.text.ParseException { - JobBuilder jobBuilder = new JobBuilder(inputPath, outputPath); + JobBuilder jobBuilder = getJobBuilder(); JobConf jobConf = jobBuilder.getJobConf(); - - System.out.println("Running job to process files."); - JobClient.runJob(jobConf); } + /** + * Creates a job builder which is responsible for creating a hadoop job + * which can be run. + * + * This method can be overridden to provide an alternate job builder. + */ + protected static JobBuilder getJobBuilder() { + return new JobBuilder(inputPath, outputPath); + } + // Process the command line arguments - private static CommandLine processArgs(String[] args) { + protected static CommandLine processArgs(String[] args) { Options options = createOptions(); CommandLine cmd = null; try { @@ -84,7 +93,8 @@ private static void printHelpText(Options options) { "-input <path to input> " + "-output <path to output> ", options); - System.exit(1); + throw new RuntimeException("Program arguments must include " + + "both input and output values"); } private static Options createOptions() { diff --git a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ProcessFileMapper.java b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ProcessFileMapper.java index 3de2292b0..7359aec76 100644 --- a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ProcessFileMapper.java +++ b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ProcessFileMapper.java @@ -8,8 +8,6 @@ package org.duracloud.services.fileprocessor; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; @@ -19,10 +17,8 @@ import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.io.InputStream; /** * Mapper used to process files. @@ -33,65 +29,158 @@ public class ProcessFileMapper extends MapReduceBase implements Mapper<Text, Text, Text, Text> { + public static final String LOCAL_FS = "file://"; + + /** + * Performs the actual file processing. + */ @Override public void map(Text key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { - String localFilePath = key.toString(); + String filePath = key.toString(); String outputPath = value.toString(); - reporter.setStatus("Processing file: " + localFilePath); - System.out.println("Beginning map process, processing file: " + - localFilePath + ". Output path: " + outputPath); - - File localFile = new File(localFilePath); + try { + reporter.setStatus("Processing file: " + filePath); + System.out.println("Starting map processing for file: " + filePath); - if(localFile.exists()) { - String fileName = localFile.getName(); + // Copy the input file to local storage + File localFile = copyFileLocal(filePath); - InputStream resultStream = processFile(localFile); + // Process the local file + File resultFile = processFile(localFile); - System.out.println("File processing complete for file " + fileName + - ", moving result to output location"); + System.out.println("File processing complete, result file " + + "generated: " + resultFile.getName()); - copyToOutput(resultStream, fileName, outputPath); + // Move the result file to the output location + String finalResultFilePath = + moveToOutput(resultFile, resultFile.getName(), outputPath); + // Delete the local file FileUtils.deleteQuietly(localFile); - output.collect(new Text(fileName), new Text("success")); + String results = "input: " + filePath + + " output: " + finalResultFilePath; + output.collect(new Text("success:"), new Text(results)); - System.out.println("Map processing completed for: " + fileName); - } else { - output.collect(new Text(localFilePath), new Text("failure")); + System.out.println("Map processing completed successfully for: " + + filePath); + } catch(IOException e) { + String results = "input: " + filePath + + " error: " + e.getMessage(); + output.collect(new Text("failure:"), new Text(results)); - System.out.println("Map processing failed for " + localFilePath + - ". File not found"); + System.out.println("Map processing failed for: " + + filePath + " due to: " + e.getMessage()); + e.printStackTrace(System.err); } - reporter.setStatus("Processing complete for file: " + localFilePath); + reporter.setStatus("Processing complete for file: " + filePath); } - private InputStream processFile(File file) throws IOException { - // Test implementation to be replaced by real processing + /** + * Copies a file from a remote file system to local storage + * + * @param filePath path to remote file + * @return local file + */ + protected File copyFileLocal(String filePath) throws IOException { + Path remotePath = new Path(filePath); + String fileName = remotePath.getName(); + + FileSystem fs = remotePath.getFileSystem(new JobConf()); + + if(fs.isFile(remotePath)) { + File localFile = new File(getTempDir(), fileName); + Path localPath = new Path(LOCAL_FS + localFile.getAbsolutePath()); + + System.out.println("Copying file (" + filePath + + ") to local file system"); + + fs.copyToLocalFile(remotePath, localPath); + + if(localFile.exists()) { + System.out.println("File moved to local storage successfully."); + return localFile; + } else { + String error = "Failure attempting to move remote file (" + + filePath + ") to local filesystem, local file (" + + localFile.getAbsolutePath() + ") not found after transfer."; + System.out.println(error); + throw new IOException(error); + } + } else { + String error = "Failure attempting to access remote file (" + + filePath + "), the file could not be found"; + System.out.println(error); + throw new IOException(error); + } + } + + /** + * Processes a file and produces a result file. The result file should + * be named as intended for the final output file. + * + * A default implementation is provided, but this method should be + * overridden by subclasses. + * + * @param file the file to process + * @return the file resulting from the processing + */ + protected File processFile(File file) throws IOException { + String fileName = file.getName(); + if(!fileName.endsWith(".txt")) { + fileName += ".txt"; + } + + File resultFile = new File(getTempDir(), fileName); + String outputText = "Processed local file: " + file.getAbsolutePath() + " in ProcessFileMapper"; - return new ByteArrayInputStream(outputText.getBytes("UTF-8")); + FileUtils.writeStringToFile(resultFile, outputText, "UTF-8"); + return resultFile; } - private void copyToOutput(InputStream resultStream, - String fileName, - String outputPath) throws IOException { + /** + * Moves the result file to the output location with the given filename. + * + * @param resultFile the file to move to output + * @param fileName the name to give the file in the output filesystem + * @param outputPath the path to where the file should be written + * @return the path of the new file in at the output location + */ + protected String moveToOutput(File resultFile, + String fileName, + String outputPath) throws IOException { if(outputPath != null) { - Path outputFile = new Path(outputPath, fileName); - FileSystem outputFS = outputFile.getFileSystem(new JobConf()); - FSDataOutputStream outputStream = outputFS.create(outputFile); + Path resultFilePath = + new Path(LOCAL_FS + resultFile.getAbsolutePath()); + Path outputFilePath = new Path(outputPath, fileName); + + System.out.println("Moving file: " + resultFilePath.toString() + + " to output " + outputFilePath.toString()); + + FileSystem outputFS = + outputFilePath.getFileSystem(new JobConf()); + outputFS.moveFromLocalFile(resultFilePath, outputFilePath); - IOUtils.copy(resultStream, outputStream); + return outputFilePath.toString(); } else { - System.out.println("Output path is null, not able to " + - "store result of processing local file"); + String error = "Output path is null, not able to " + + "store result of processing local file"; + System.out.println(error); + throw new IOException(error); } } + /** + * Retrieves a temporary directory on the local file system. + */ + public File getTempDir() { + return new File(System.getProperty("java.io.tmpdir")); + } + } diff --git a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ResultsReducer.java b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ResultsReducer.java index 12b0058a5..fc7ea3c5d 100644 --- a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ResultsReducer.java +++ b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/ResultsReducer.java @@ -28,8 +28,6 @@ public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { - System.out.println("Reducing on key: " + key.toString()); - while (values.hasNext()) { output.collect(key, values.next()); } diff --git a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/SimpleFileRecordReader.java b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/SimpleFileRecordReader.java index f268fa246..bb96ba5d8 100644 --- a/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/SimpleFileRecordReader.java +++ b/services/hadoop-file-processor/src/main/java/org/duracloud/services/fileprocessor/SimpleFileRecordReader.java @@ -7,8 +7,6 @@ */ package org.duracloud.services.fileprocessor; -import org.apache.commons.io.IOUtils; -import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileOutputFormat; @@ -17,17 +15,14 @@ import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.Reporter; -import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; /** - * Record reader used to provide a set of key/value pairs for each file - * in a file split. Assumes the file split is a single file and returns - * the path to the file as the key of a single key/value pair produced - * per file. + * Record reader, used to provide a set of key/value pairs for each file + * in a file split. This reader assumes the file split is a single file + * and creates one key/value pair per file where: + * key = the file path + * value = the output path (for results) * * @author: Bill Branan * Date: Aug 5, 2010 @@ -37,7 +32,6 @@ public class SimpleFileRecordReader implements RecordReader<Text, Text> { private FileSplit inputSplit; private JobConf jobConf; private Reporter reporter; - private String tempDir; private String filePath; public SimpleFileRecordReader(FileSplit inputSplit, @@ -46,9 +40,6 @@ public SimpleFileRecordReader(FileSplit inputSplit, this.inputSplit = inputSplit; this.jobConf = jobConf; this.reporter = reporter; - - this.tempDir = - new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); } @Override @@ -60,9 +51,8 @@ public boolean next(Text key, Text value) throws IOException { System.out.println("Record reader handling file: " + filePath); - if(filePath != null) { - String localPath = moveLocal(); - key.set(localPath); + if(filePath != null && !filePath.endsWith("-space-metadata")) { + key.set(filePath); Path outputPath = FileOutputFormat.getOutputPath(jobConf); value.set(outputPath.toString()); @@ -83,36 +73,6 @@ public boolean next(Text key, Text value) throws IOException { return result; } - public String moveLocal() throws IOException { - Path path = new Path(filePath); - String fileName = path.getName(); - - reporter.setStatus("Moving file to local system for processing: " + - fileName); - - FileSystem fs = path.getFileSystem(jobConf); - - if(fs.isFile(path)) { - // Copy file from remote file system to local storage - InputStream inputStream = fs.open(path, 2048); - File localFile = new File(tempDir, fileName); - - System.out.println("Record reader about to read S3 file (" + - filePath + ") to local file system " + - localFile.getAbsolutePath()); - - OutputStream localFileStream = new FileOutputStream(localFile); - IOUtils.copy(inputStream, localFileStream); - - System.out.println("File moved to local storage successfully"); - return localFile.getAbsolutePath(); - } else { - System.out.println("Record reader could not retrieve file " + - "from S3: " + filePath); - throw new IOException("Could not retrieve file: " + filePath); - } - } - /** * Create an empty Text object in which the key can be stored */ diff --git a/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/JobBuilderTest.java b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/JobBuilderTest.java new file mode 100644 index 000000000..972a44e86 --- /dev/null +++ b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/JobBuilderTest.java @@ -0,0 +1,48 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.fileprocessor; + +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.mapred.FileInputFormat; +import org.apache.hadoop.mapred.FileOutputFormat; +import org.apache.hadoop.mapred.JobConf; +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +/** + * @author: Bill Branan + * Date: Aug 11, 2010 + */ +public class JobBuilderTest { + + @Test + public void testJobBuilder() throws Exception { + String inputPath = "file://inputPath"; + String outputPath = "file://outputPath"; + + JobBuilder jobBuilder = new JobBuilder(inputPath, outputPath); + assertEquals("ProcessFiles", jobBuilder.getJobName()); + assertEquals(ProcessFileMapper.class, jobBuilder.getMapper()); + assertEquals(ResultsReducer.class, jobBuilder.getReducer()); + + // An unnecessary stack track is printed when creating a JobConf + // See org.apache.hadoop.conf.Configuration line 211 + System.out.println("--- BEGIN EXPECTED STACK TRACE ---"); + JobConf jobConf = jobBuilder.getJobConf(); + System.out.println("--- END EXPECTED STACK TRACE ---"); + + Path[] paths = FileInputFormat.getInputPaths(jobConf); + assertEquals(1, paths.length); + assertEquals(inputPath, paths[0].toString()); + + assertEquals(outputPath, + FileOutputFormat.getOutputPath(jobConf).toString()); + } + +} diff --git a/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/JobRunnerTest.java b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/JobRunnerTest.java new file mode 100644 index 000000000..ba121e067 --- /dev/null +++ b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/JobRunnerTest.java @@ -0,0 +1,38 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.fileprocessor; + +import org.junit.Test; + +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.fail; + +/** + * @author: Bill Branan + * Date: Aug 11, 2010 + */ +public class JobRunnerTest { + + @Test + public void testProcessArgs() throws Exception { + JobRunner jobRunner = new JobRunner(); + try { + jobRunner.processArgs(null); + fail("Job Runner should fail when no arguments are provided"); + } catch(Exception expected) { + assertNotNull(expected); + } + + String[] args = {"-input", "inputFile", "-output", "outputFile"}; + jobRunner.processArgs(args); + + String[] argsShort = {"-i", "inputFile", "-o", "outputFile"}; + jobRunner.processArgs(argsShort); + } + +} diff --git a/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/ProcessFileMapperTest.java b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/ProcessFileMapperTest.java new file mode 100644 index 000000000..e9d267291 --- /dev/null +++ b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/ProcessFileMapperTest.java @@ -0,0 +1,131 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.fileprocessor; + +import org.apache.commons.io.FileUtils; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapred.OutputCollector; +import org.apache.hadoop.mapred.Reporter; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotNull; +import static junit.framework.Assert.assertTrue; + +/** + * Tests the ProcessFileMapper. + * + * Note that there are no tests for methods copyFileLocal() and moveToOutput() + * due to the fact that these methods make calls to hadoop functions which + * use linux-specific tools to perform file transfer activities. + * + * @author: Bill Branan + * Date: Aug 11, 2010 + */ +public class ProcessFileMapperTest { + + private ArrayList<File> testFiles; + + @Before + public void setUp() throws Exception { + testFiles = new ArrayList<File>(); + } + + @After + public void tearDown() throws Exception { + for(File file : testFiles) { + FileUtils.deleteQuietly(file); + } + } + + @Test + public void testProcessFile() throws Exception { + ProcessFileMapper mapper = new ProcessFileMapper(); + + String fileContent = "This is test content"; + File fileToProcess = File.createTempFile("test", "file"); + testFiles.add(fileToProcess); + FileUtils.writeStringToFile(fileToProcess, fileContent); + + File resultFile = mapper.processFile(fileToProcess); + testFiles.add(resultFile); + + assertNotNull(resultFile); + assertTrue(resultFile.exists()); + assertTrue(resultFile.getName().endsWith(".txt")); + + String resultFileContent = FileUtils.readFileToString(resultFile); + assertTrue(resultFileContent.contains(fileToProcess.getAbsolutePath())); + } + + @Test + public void testMap() throws IOException { + Text key = new Text("/file/path"); + Text value = new Text("/output/path"); + + MockProcessFileMapper mapper = new MockProcessFileMapper(); + + SimpleOutputCollector<Text, Text> collector = + new SimpleOutputCollector<Text, Text>(); + mapper.map(key, value, collector, Reporter.NULL); + + HashMap<Text, Text> collection = collector.getCollection(); + assertNotNull(collection); + assertEquals(1, collection.size()); + + Text resultKey = collection.keySet().iterator().next(); + assertNotNull(resultKey); + assertTrue(resultKey.toString().contains("success")); + + Text resultValue = collection.get(resultKey); + assertNotNull(resultValue); + assertTrue(resultValue.toString().contains(key.toString())); + } + + private class SimpleOutputCollector<K, V> + implements OutputCollector<Text, Text> { + + HashMap<Text, Text> collection = new HashMap<Text, Text>(); + + @Override + public void collect(Text key, Text value) throws IOException { + collection.put(key, value); + } + + public HashMap<Text, Text> getCollection() { + return collection; + } + } + + private class MockProcessFileMapper extends ProcessFileMapper { + @Override + protected File copyFileLocal(String filePath) throws IOException { + return new File("/local/file"); + } + + @Override + protected File processFile(File file) throws IOException { + return new File("/processed/file"); + } + + @Override + protected String moveToOutput(File resultFile, + String fileName, + String outputPath) throws IOException { + return outputPath + "/" + fileName; + } + } + +} diff --git a/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/SimpleFileRecordReaderTest.java b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/SimpleFileRecordReaderTest.java new file mode 100644 index 000000000..0fb455f19 --- /dev/null +++ b/services/hadoop-file-processor/src/test/java/org/duracloud/services/fileprocessor/SimpleFileRecordReaderTest.java @@ -0,0 +1,68 @@ +/* + * The contents of this file are subject to the license and copyright + * detailed in the LICENSE and NOTICE files at the root of the source + * tree and available online at + * + * http://duracloud.org/license/ + */ +package org.duracloud.services.fileprocessor; + +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapred.FileOutputFormat; +import org.apache.hadoop.mapred.FileSplit; +import org.apache.hadoop.mapred.JobConf; +import org.apache.hadoop.mapred.Reporter; +import org.apache.hadoop.mapred.TextOutputFormat; +import org.junit.Test; + +import java.io.IOException; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.Assert.assertNotNull; + +/** + * @author: Bill Branan + * Date: Aug 11, 2010 + */ +public class SimpleFileRecordReaderTest { + + @Test + public void testSimpleFileRecordReader() throws Exception { + String inputPath = "file://inputPath"; + String outputPath = "file://outputPath"; + + // An unnecessary stack track is printed when creating a JobConf + // See org.apache.hadoop.conf.Configuration line 211 + System.out.println("--- BEGIN EXPECTED STACK TRACE ---"); + JobConf conf = new JobConf(); + System.out.println("--- END EXPECTED STACK TRACE ---"); + + conf.setOutputKeyClass(Text.class); + conf.setOutputValueClass(Text.class); + FileOutputFormat.setOutputPath(conf, new Path(outputPath)); + conf.setOutputFormat(TextOutputFormat.class); + + FileSplit split = new FileSplit(new Path(inputPath), 0, 10, conf); + + SimpleFileRecordReader reader = + new SimpleFileRecordReader(split, conf, Reporter.NULL); + + Text key = reader.createKey(); + Text value = reader.createValue(); + + assertNotNull(key); + assertNotNull(value); + + assertEquals(0, reader.getPos()); + assertEquals(Float.valueOf(0), reader.getProgress()); + + reader.next(key, value); + + assertEquals(inputPath, key.toString()); + assertEquals(outputPath, value.toString()); + + assertEquals(1, reader.getPos()); + assertEquals(Float.valueOf(1), reader.getProgress()); + } +}
9e2aef2de9b70ecee09cc8e9425483bf1603b9cb
isa-tools$isacreator
More work on term mapper interface. Added in more functionality. Auto annotation according to score received from BioPortal. Clear all mappings.
p
https://github.com/isa-tools/isacreator
diff --git a/trunk/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java b/trunk/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java index be20d321..4c644899 100644 --- a/trunk/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java +++ b/trunk/src/main/java/org/isatools/isacreator/mgrast/ui/ExternalIdListCellRenderer.java @@ -67,7 +67,7 @@ public ExternalIdListCellRenderer() { setLayout(new BorderLayout()); setBackground(Color.WHITE); - ResourceInjector.get("exporters-package.style").inject(this); + ResourceInjector.get("exporter-package.style").inject(this); add(new IDEnteredListCellmage(), BorderLayout.WEST); diff --git a/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserAnnotationPane.java b/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserAnnotationPane.java index d8ce5959..79ecfe7a 100644 --- a/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserAnnotationPane.java +++ b/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserAnnotationPane.java @@ -4,6 +4,7 @@ import org.isatools.isacreator.autofilteringlist.ExtendedJList; import org.isatools.isacreator.common.ClearFieldUtility; import org.isatools.isacreator.common.UIHelper; +import org.isatools.isacreator.effects.RoundedBorder; import org.isatools.isacreator.ontologiser.model.OntologisedResult; import org.isatools.isacreator.ontologiser.model.SuggestedAnnotationListItem; import org.isatools.isacreator.ontologiser.ui.listrenderer.OntologyAssignedListRenderer; @@ -15,6 +16,7 @@ import javax.swing.*; import javax.swing.border.EmptyBorder; +import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; @@ -45,7 +47,7 @@ public class OntologiserAnnotationPane extends JPanel { @InjectedResource private ImageIcon optionsIcon, clearAnnotationsIcon, clearAnnotationsIconOver, - useSuggestedIcon, useSuggestedIconOver; + useSuggestedIcon, useSuggestedIconOver, confidenceKey; private ExtendedJList freeTextList, suggestedTermsList; @@ -90,6 +92,7 @@ public void mouseExited(MouseEvent mouseEvent) { @Override public void mousePressed(MouseEvent mouseEvent) { useSuggestedButton.setIcon(useSuggestedIcon); + autoAnnotate(); } }); @@ -109,6 +112,7 @@ public void mouseExited(MouseEvent mouseEvent) { @Override public void mousePressed(MouseEvent mouseEvent) { clearAnnotationsButton.setIcon(clearAnnotationsIcon); + clearAnnotation(); } }); @@ -145,7 +149,7 @@ public void propertyChange(PropertyChangeEvent propertyChangeEvent) { } }); - listPanel.add(createListPanel(freeTextList)); + listPanel.add(createListPanel(freeTextList, "Freetext Terms")); suggestedTermsList = new ExtendedJList(new ScoringConfidenceListRenderer(), false); @@ -153,25 +157,25 @@ public void propertyChange(PropertyChangeEvent propertyChangeEvent) { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { SuggestedAnnotationListItem selectedItem = (SuggestedAnnotationListItem) suggestedTermsList.getSelectedValue(); - clearAnnotation(currentlySelectedOntologyTerm); - - currentlySelectedOntologyTerm.setAssignedOntology(selectedItem.getAnnotatorResult()); - - System.out.println("\t Adding mapping to : " + currentlySelectedOntologyTerm); - selectedItem.setMappedTo(currentlySelectedOntologyTerm); - + setAnnotation(selectedItem, currentlySelectedOntologyTerm); // should clear other selections to ensure that other suggested terms are not mapping to the ontology result too } }); - listPanel.add(createListPanel(suggestedTermsList)); + JPanel suggestedTermListContainer = createListPanel(suggestedTermsList, "Suggested terms"); + suggestedTermListContainer.add(new JLabel(confidenceKey), BorderLayout.SOUTH); + + listPanel.add(suggestedTermListContainer); + + definitionUI.setBorder(new TitledBorder(new RoundedBorder(UIHelper.LIGHT_GREEN_COLOR, 6), "Definition", + TitledBorder.DEFAULT_POSITION, TitledBorder.DEFAULT_JUSTIFICATION, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR)); listPanel.add(definitionUI); add(listPanel, BorderLayout.CENTER); } - private JPanel createListPanel(ExtendedJList list) { + private JPanel createListPanel(ExtendedJList list, String listTitle) { JPanel listContainer = new JPanel(new BorderLayout()); listContainer.setPreferredSize(new Dimension(200, 300)); @@ -193,13 +197,27 @@ private JPanel createListPanel(ExtendedJList list) { listContainer.add(fieldContainer, BorderLayout.NORTH); listContainer.add(scrollPane, BorderLayout.CENTER); + listContainer.setBorder(new TitledBorder(new RoundedBorder(UIHelper.LIGHT_GREEN_COLOR, 6), listTitle, + TitledBorder.DEFAULT_POSITION, TitledBorder.DEFAULT_JUSTIFICATION, UIHelper.VER_11_BOLD, UIHelper.DARK_GREEN_COLOR)); + return listContainer; } private void initiateFreeTextListContents() { for (String freeTextValue : searchMatches.keySet()) { - freeTextList.addItem(new OntologisedResult(freeTextValue)); + + + OntologisedResult ontologisedResult = new OntologisedResult(freeTextValue); + + freeTextList.addItem(ontologisedResult); + + annotations.put(ontologisedResult, new ArrayList<SuggestedAnnotationListItem>()); + + for (String ontologyId : searchMatches.get(ontologisedResult.getFreeTextTerm()).keySet()) { + SuggestedAnnotationListItem annotatorResult = new SuggestedAnnotationListItem(searchMatches.get(ontologisedResult.getFreeTextTerm()).get(ontologyId)); + annotations.get(ontologisedResult).add(annotatorResult); + } } } @@ -210,21 +228,25 @@ private void updateOntologySuggestionsForFreetextTerm() { if (freeTextList.getSelectedIndex() != -1) { OntologisedResult ontologyResult = (OntologisedResult) freeTextList.getSelectedValue(); + for (SuggestedAnnotationListItem listItem : annotations.get(ontologyResult)) { + suggestedTermsList.addItem(listItem); + } + } + } - if (!annotations.containsKey(ontologyResult)) { - - annotations.put(ontologyResult, new ArrayList<SuggestedAnnotationListItem>()); + private void clearAnnotation() { + for (OntologisedResult ontologisedResult : annotations.keySet()) { - for (String ontologyId : searchMatches.get(ontologyResult.getFreeTextTerm()).keySet()) { - SuggestedAnnotationListItem annotatorResult = new SuggestedAnnotationListItem(searchMatches.get(ontologyResult.getFreeTextTerm()).get(ontologyId)); - annotations.get(ontologyResult).add(annotatorResult); + if (annotations.containsKey(ontologisedResult)) { + for (SuggestedAnnotationListItem listItem : annotations.get(ontologisedResult)) { + listItem.setMappedTo(null); } } - for (SuggestedAnnotationListItem listItem : annotations.get(ontologyResult)) { - suggestedTermsList.addItem(listItem); - } + ontologisedResult.setAssignedOntology(null); } + + repaint(); } private void clearAnnotation(OntologisedResult ontologisedResult) { @@ -234,4 +256,32 @@ private void clearAnnotation(OntologisedResult ontologisedResult) { } } } + + private void autoAnnotate() { + for (OntologisedResult ontologisedResult : annotations.keySet()) { + System.out.println("Ontologised Result: " + ontologisedResult.getFreeTextTerm()); + int maxScore = Integer.MIN_VALUE; + SuggestedAnnotationListItem suggestedAnnotation = null; + + for (SuggestedAnnotationListItem listItem : annotations.get(ontologisedResult)) { + System.out.println("\tPossible annotation: " + listItem.getAnnotatorResult().toString() + " - > score = " + listItem.getAnnotatorResult().getScore()); + if (listItem.getAnnotatorResult().getScore() > maxScore) { + maxScore = listItem.getAnnotatorResult().getScore(); + suggestedAnnotation = listItem; + } + } + + setAnnotation(suggestedAnnotation, ontologisedResult); + } + + repaint(); + + } + + private void setAnnotation(SuggestedAnnotationListItem selectedAnnnotationItem, OntologisedResult ontologisedResult) { + clearAnnotation(ontologisedResult); + + ontologisedResult.setAssignedOntology(selectedAnnnotationItem.getAnnotatorResult()); + selectedAnnnotationItem.setMappedTo(ontologisedResult); + } } diff --git a/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java b/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java index 84c432b7..6638829a 100644 --- a/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java +++ b/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java @@ -74,7 +74,7 @@ public void createGUI() { setBackground(UIHelper.BG_COLOR); setUndecorated(true); setLayout(new BorderLayout()); - setPreferredSize(new Dimension(600, 450)); + setPreferredSize(new Dimension(600, 500)); ((JComponent) getContentPane()).setBorder(new EtchedBorder(UIHelper.LIGHT_GREEN_COLOR, UIHelper.LIGHT_GREEN_COLOR)); diff --git a/trunk/src/main/java/org/isatools/isacreator/ontologyselectiontool/ViewTermDefinitionUI.java b/trunk/src/main/java/org/isatools/isacreator/ontologyselectiontool/ViewTermDefinitionUI.java index ca548509..8113ec0e 100644 --- a/trunk/src/main/java/org/isatools/isacreator/ontologyselectiontool/ViewTermDefinitionUI.java +++ b/trunk/src/main/java/org/isatools/isacreator/ontologyselectiontool/ViewTermDefinitionUI.java @@ -91,7 +91,7 @@ public ViewTermDefinitionUI() { public void createGUI() { swappableContainer = new JPanel(new BorderLayout()); swappableContainer.setBackground(UIHelper.BG_COLOR); - swappableContainer.setPreferredSize(new Dimension(240, 270)); + swappableContainer.setPreferredSize(new Dimension(200, 270)); swappableContainer.add(new JLabel(placeHolder)); add(swappableContainer, BorderLayout.CENTER); } diff --git a/trunk/src/main/resources/dependency-injections/ontologiser-generator-package.properties b/trunk/src/main/resources/dependency-injections/ontologiser-generator-package.properties index 0e487e3b..241cdb3d 100644 --- a/trunk/src/main/resources/dependency-injections/ontologiser-generator-package.properties +++ b/trunk/src/main/resources/dependency-injections/ontologiser-generator-package.properties @@ -10,6 +10,7 @@ OntologiserUI.doneIconOver=/images/ontologiser/done_button_over.png OntologiserUI.buttonPanelFiller=/images/ontologiser/button_middle.png OntologiserUI.working=/images/qrcode_generator/working.png + OntologyHelpPane.helpImage=/images/ontologiser/help_text.png CheckedCellImage.ontologyAssigned=/images/ontologiser/list/ontologySelected.png @@ -20,6 +21,7 @@ OntologiserAnnotationPane.clearAnnotationsIcon=/images/ontologiser/clear_annotat OntologiserAnnotationPane.clearAnnotationsIconOver=/images/ontologiser/clear_annotations_over.png OntologiserAnnotationPane.useSuggestedIcon=/images/ontologiser/use_suggested.png OntologiserAnnotationPane.useSuggestedIconOver=/images/ontologiser/use_suggested_over.png +OntologiserAnnotationPane.confidenceKey=/images/ontologiser/list/confidence_key.png ScoringConfidenceListRenderer.high=/images/ontologiser/list/score/high.png ScoringConfidenceListRenderer.medium=/images/ontologiser/list/score/medium.png diff --git a/trunk/src/main/resources/images/ontologiser/list/score/high.png b/trunk/src/main/resources/images/ontologiser/list/score/high.png new file mode 100644 index 00000000..6a45b2e7 Binary files /dev/null and b/trunk/src/main/resources/images/ontologiser/list/score/high.png differ diff --git a/trunk/src/main/resources/images/ontologiser/list/score/low.png b/trunk/src/main/resources/images/ontologiser/list/score/low.png new file mode 100644 index 00000000..6cc01eb7 Binary files /dev/null and b/trunk/src/main/resources/images/ontologiser/list/score/low.png differ diff --git a/trunk/src/main/resources/images/ontologiser/list/score/medium.png b/trunk/src/main/resources/images/ontologiser/list/score/medium.png new file mode 100644 index 00000000..52ffaff2 Binary files /dev/null and b/trunk/src/main/resources/images/ontologiser/list/score/medium.png differ
69902e6dedbfeb4e44eace12a101169cdfb97def
restlet-framework-java
Add SpringRouter-style supplemental direct routing- via the attachments property. This allows for multiple routes for the same- bean or routes which would be illegal/unmatched as bean names.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java index 1101183992..b686612d6a 100644 --- a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java +++ b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/SpringBeanRouter.java @@ -41,6 +41,8 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import java.util.Map; + /** * Restlet {@link Router} which behaves like Spring's * {@link org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping}. It @@ -85,6 +87,9 @@ public class SpringBeanRouter extends Router implements /** If beans should be searched for higher up in the BeanFactory hierarchy */ private volatile boolean findInAncestors = true; + /** Supplemental explicit mappings */ + private Map<String, String> attachments; + /** * Creates an instance of {@link SpringBeanFinder}. This can be overriden if * necessary. @@ -130,7 +135,14 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) for (final String name : names) { final String uri = resolveUri(name, factory); if (uri != null) { - attach(uri, createFinder(bf, name)); + if (this.attachments == null || !this.attachments.containsKey(uri)) { + attach(uri, createFinder(bf, name)); + } + } + } + if (this.attachments != null) { + for (Map.Entry<String, String> attachment : this.attachments.entrySet()) { + attach(attachment.getKey(), createFinder(bf, attachment.getValue())); } } } @@ -180,4 +192,16 @@ public void setApplicationContext(ApplicationContext applicationContext) public void setFindInAncestors(boolean findInAncestors) { this.findInAncestors = findInAncestors; } + + /** + * Sets an explicit mapping of URI templates to bean IDs to use + * in addition to the usual bean name mapping behavior. If a URI template + * appears in both this mapping and as a bean name, the bean it is mapped + * to here is the one that will be used. + * + * @see SpringRouter + */ + public void setAttachments(Map<String, String> attachments) { + this.attachments = attachments; + } } diff --git a/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java index b9bd592724..847a959a5c 100644 --- a/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/spring/SpringBeanRouterTestCase.java @@ -31,6 +31,9 @@ package org.restlet.test.ext.spring; import org.restlet.Restlet; +import org.restlet.data.Method; +import org.restlet.data.Request; +import org.restlet.data.Response; import org.restlet.ext.spring.SpringBeanFinder; import org.restlet.ext.spring.SpringBeanRouter; import org.restlet.resource.Resource; @@ -41,9 +44,10 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; +import java.util.Collections; import java.util.HashSet; -import java.util.Set; import java.util.List; +import java.util.Set; /** * @author Rhett Sutphin @@ -57,7 +61,7 @@ public class SpringBeanRouterTestCase extends RestletTestCase { private SpringBeanRouter router; private void assertFinderForBean(String expectedBeanName, Restlet restlet) { - assertTrue("Restlet is not a bean finder restlet", + assertTrue("Restlet is not a bean finder restlet: " + restlet.getClass().getName(), restlet instanceof SpringBeanFinder); final SpringBeanFinder actualFinder = (SpringBeanFinder) restlet; assertEquals("Finder does not point to correct bean", expectedBeanName, @@ -90,6 +94,11 @@ private void registerResourceBeanDefinition(String id, String alias) { } } + private RouteList actualRoutes() { + this.router.postProcessBeanFactory(this.factory); + return this.router.getRoutes(); + } + private Set<String> routeUris(List<Route> routes) { final Set<String> uris = new HashSet<String>(); for (final Route actualRoute : routes) { @@ -119,15 +128,8 @@ public void testRoutesCreatedForBeanIdsIfAppropriate() throws Exception { public void testRoutesPointToFindersForBeans() throws Exception { final RouteList actualRoutes = actualRoutes(); assertEquals("Wrong number of routes", 2, actualRoutes.size()); - Route oreRoute = null, fishRoute = null; - for (final Route actualRoute : actualRoutes) { - if (actualRoute.getTemplate().getPattern().equals(FISH_URI)) { - fishRoute = actualRoute; - } - if (actualRoute.getTemplate().getPattern().equals(ORE_URI)) { - oreRoute = actualRoute; - } - } + Route oreRoute = matchRouteFor(ORE_URI); + Route fishRoute = matchRouteFor(FISH_URI); assertNotNull("ore route not present: " + actualRoutes, oreRoute); assertNotNull("fish route not present: " + actualRoutes, fishRoute); @@ -135,13 +137,6 @@ public void testRoutesPointToFindersForBeans() throws Exception { assertFinderForBean("fish", fishRoute.getNext()); } - private RouteList actualRoutes() { - this.router.postProcessBeanFactory(this.factory); - - final RouteList actualRoutes = this.router.getRoutes(); - return actualRoutes; - } - public void testRoutingSkipsResourcesWithoutAppropriateAliases() throws Exception { final BeanDefinition bd = new RootBeanDefinition(Resource.class); @@ -153,4 +148,35 @@ public void testRoutingSkipsResourcesWithoutAppropriateAliases() assertEquals("Timber resource should have been skipped", 2, actualRoutes.size()); } + + public void testRoutingIncludesSpringRouterStyleExplicitlyMappedBeans() throws Exception { + final BeanDefinition bd = new RootBeanDefinition(Resource.class); + bd.setScope(BeanDefinition.SCOPE_PROTOTYPE); + this.factory.registerBeanDefinition("timber", bd); + this.factory.registerAlias("timber", "no-slash"); + + String expectedTemplate = "/renewable/timber/{farm_type}"; + router.setAttachments(Collections.singletonMap(expectedTemplate, "timber")); + final RouteList actualRoutes = actualRoutes(); + + assertEquals("Wrong number of routes", 3, actualRoutes.size()); + Route timberRoute = matchRouteFor(expectedTemplate); + assertNotNull("Missing timber route: " + actualRoutes, timberRoute); + assertFinderForBean("timber", timberRoute.getNext()); + } + + public void testExplicitAttachmentsTrumpBeanNames() throws Exception { + this.router.setAttachments(Collections.singletonMap(ORE_URI, "fish")); + RouteList actualRoutes = actualRoutes(); + assertEquals("Wrong number of routes", 2, actualRoutes.size()); + + Route oreRoute = matchRouteFor(ORE_URI); + assertNotNull("No route for " + ORE_URI, oreRoute); + assertFinderForBean("fish", oreRoute.getNext()); + } + + private Route matchRouteFor(String uri) { + Request req = new Request(Method.GET, uri); + return (Route) router.getNext(req, new Response(req)); + } }
acbf26e896a7586aa9b7f9240ba2213611371915
Vala
libsoup-2.4: add many missing type_arguments Partially fixes bug 609875.
c
https://github.com/GNOME/vala/
diff --git a/vapi/libsoup-2.4.vapi b/vapi/libsoup-2.4.vapi index 78291b4159..dd83ee5316 100644 --- a/vapi/libsoup-2.4.vapi +++ b/vapi/libsoup-2.4.vapi @@ -33,11 +33,10 @@ namespace Soup { [CCode (has_construct_function = false)] public Auth (GLib.Type type, Soup.Message msg, string auth_header); public virtual void authenticate (string username, string password); - public void free_protection_space (GLib.SList space); public virtual unowned string get_authorization (Soup.Message msg); public unowned string get_host (); public unowned string get_info (); - public virtual unowned GLib.SList get_protection_space (Soup.URI source_uri); + public virtual GLib.SList<string> get_protection_space (Soup.URI source_uri); public unowned string get_realm (); public unowned string get_scheme_name (); public virtual bool update (Soup.Message msg, string auth_header); @@ -153,7 +152,7 @@ namespace Soup { [CCode (has_construct_function = false)] public CookieJar (); public void add_cookie (Soup.Cookie cookie); - public unowned GLib.SList all_cookies (); + public GLib.SList<Soup.Cookie> all_cookies (); public void delete_cookie (Soup.Cookie cookie); public unowned string get_cookies (Soup.URI uri, bool for_http); public virtual void save (); @@ -299,10 +298,10 @@ namespace Soup { public bool get_ranges (int64 total_length, out unowned Soup.Range ranges, int length); public void remove (string name); public void replace (string name, string value); - public void set_content_disposition (string disposition, GLib.HashTable @params); + public void set_content_disposition (string disposition, GLib.HashTable<string,string>? @params); public void set_content_length (int64 content_length); public void set_content_range (int64 start, int64 end, int64 total_length); - public void set_content_type (string content_type, GLib.HashTable @params); + public void set_content_type (string content_type, GLib.HashTable<string,string>? @params); public void set_encoding (Soup.Encoding encoding); public void set_expectations (Soup.Expectation expectations); public void set_range (int64 start, int64 end); @@ -481,7 +480,7 @@ namespace Soup { public void set_port (uint port); public void set_query (string query); public void set_query_from_fields (...); - public void set_query_from_form (GLib.HashTable form); + public void set_query_from_form (GLib.HashTable<string,string> form); public void set_scheme (string scheme); public void set_user (string user); public string to_string (bool just_path_and_query); @@ -683,7 +682,7 @@ namespace Soup { [CCode (cheader_filename = "libsoup/soup.h", has_target = false)] public delegate void ProxyResolverCallback (Soup.ProxyResolver p1, Soup.Message p2, uint p3, Soup.Address p4, void* p5); [CCode (cheader_filename = "libsoup/soup.h")] - public delegate void ServerCallback (Soup.Server server, Soup.Message msg, string path, GLib.HashTable query, Soup.ClientContext client); + public delegate void ServerCallback (Soup.Server server, Soup.Message msg, string path, GLib.HashTable<string,string> query, Soup.ClientContext client); [CCode (cheader_filename = "libsoup/soup.h")] public delegate void SessionCallback (Soup.Session session, Soup.Message msg); [CCode (cheader_filename = "libsoup/soup.h")] @@ -885,27 +884,25 @@ namespace Soup { [CCode (cheader_filename = "libsoup/soup.h")] public static unowned GLib.TimeoutSource add_timeout (GLib.MainContext async_context, uint interval, GLib.SourceFunc function, void* data); [CCode (cheader_filename = "libsoup/soup.h")] - public static void cookies_free (GLib.SList cookies); + public static GLib.SList<Soup.Cookie> cookies_from_request (Soup.Message msg); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.SList cookies_from_request (Soup.Message msg); + public static GLib.SList<Soup.Cookie> cookies_from_response (Soup.Message msg); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.SList cookies_from_response (Soup.Message msg); + public static unowned string cookies_to_cookie_header (GLib.SList<Soup.Cookie> cookies); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned string cookies_to_cookie_header (GLib.SList cookies); + public static void cookies_to_request (GLib.SList<Soup.Cookie> cookies, Soup.Message msg); [CCode (cheader_filename = "libsoup/soup.h")] - public static void cookies_to_request (GLib.SList cookies, Soup.Message msg); + public static void cookies_to_response (GLib.SList<Soup.Cookie> cookies, Soup.Message msg); [CCode (cheader_filename = "libsoup/soup.h")] - public static void cookies_to_response (GLib.SList cookies, Soup.Message msg); + public static GLib.HashTable<string,string> form_decode (string encoded_form); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.HashTable form_decode (string encoded_form); - [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.HashTable form_decode_multipart (Soup.Message msg, string file_control_name, out unowned string filename, out unowned string content_type, out unowned Soup.Buffer file); + public static GLib.HashTable<string,string> form_decode_multipart (Soup.Message msg, string file_control_name, out string filename, out string content_type, out Soup.Buffer file); [CCode (cheader_filename = "libsoup/soup.h")] public static unowned string form_encode (...); [CCode (cheader_filename = "libsoup/soup.h")] public static unowned string form_encode_datalist (void* form_data_set); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned string form_encode_hash (GLib.HashTable form_data_set); + public static unowned string form_encode_hash (GLib.HashTable<string,string> form_data_set); [CCode (cheader_filename = "libsoup/soup.h")] public static unowned string form_encode_valist (string first_field, void* args); [CCode (cheader_filename = "libsoup/soup.h")] @@ -913,25 +910,21 @@ namespace Soup { [CCode (cheader_filename = "libsoup/soup.h")] public static unowned Soup.Message form_request_new_from_datalist (string method, string uri, void* form_data_set); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned Soup.Message form_request_new_from_hash (string method, string uri, GLib.HashTable form_data_set); + public static unowned Soup.Message form_request_new_from_hash (string method, string uri, GLib.HashTable<string,string> form_data_set); [CCode (cheader_filename = "libsoup/soup.h")] public static unowned Soup.Message form_request_new_from_multipart (string uri, Soup.Multipart multipart); [CCode (cheader_filename = "libsoup/soup.h")] public static bool header_contains (string header, string token); [CCode (cheader_filename = "libsoup/soup.h")] - public static void header_free_list (GLib.SList list); - [CCode (cheader_filename = "libsoup/soup.h")] - public static void header_free_param_list (GLib.HashTable param_list); - [CCode (cheader_filename = "libsoup/soup.h")] public static void header_g_string_append_param (GLib.StringBuilder str, string name, string value); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.SList header_parse_list (string header); + public static GLib.SList<string> header_parse_list (string header); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.HashTable header_parse_param_list (string header); + public static GLib.HashTable<string,string> header_parse_param_list (string header); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.SList header_parse_quality_list (string header, GLib.SList unacceptable); + public static GLib.SList<string> header_parse_quality_list (string header, GLib.SList<string> unacceptable); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.HashTable header_parse_semi_param_list (string header); + public static GLib.HashTable<string,string> header_parse_semi_param_list (string header); [CCode (cheader_filename = "libsoup/soup.h")] public static bool headers_parse (string str, int len, Soup.MessageHeaders dest); [CCode (cheader_filename = "libsoup/soup.h")] @@ -969,19 +962,19 @@ namespace Soup { [CCode (cheader_filename = "libsoup/soup.h")] public static bool value_array_to_args (GLib.ValueArray array, void* args); [CCode (cheader_filename = "libsoup/soup.h")] - public static void value_hash_insert (GLib.HashTable hash, string key, GLib.Type type); + public static void value_hash_insert (GLib.HashTable<string,GLib.Value> hash, string key, GLib.Type type, ...); [CCode (cheader_filename = "libsoup/soup.h")] - public static void value_hash_insert_vals (GLib.HashTable hash, ...); + public static void value_hash_insert_vals (GLib.HashTable<string,GLib.Value> hash, ...); [CCode (cheader_filename = "libsoup/soup.h")] - public static void value_hash_insert_value (GLib.HashTable hash, string key, GLib.Value value); + public static void value_hash_insert_value (GLib.HashTable<string,GLib.Value> hash, string key, GLib.Value value); [CCode (cheader_filename = "libsoup/soup.h")] - public static bool value_hash_lookup (GLib.HashTable hash, string key, GLib.Type type); + public static bool value_hash_lookup (GLib.HashTable<string,GLib.Value> hash, string key, GLib.Type type); [CCode (cheader_filename = "libsoup/soup.h")] - public static bool value_hash_lookup_vals (GLib.HashTable hash, ...); + public static bool value_hash_lookup_vals (GLib.HashTable<string,GLib.Value> hash, ...); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.HashTable value_hash_new (); + public static GLib.HashTable<string,GLib.Value> value_hash_new (); [CCode (cheader_filename = "libsoup/soup.h")] - public static unowned GLib.HashTable value_hash_new_with_vals (...); + public static GLib.HashTable<string,GLib.Value> value_hash_new_with_vals (...); [PrintfFormat] [CCode (cheader_filename = "libsoup/soup.h")] public static unowned string xmlrpc_build_fault (int fault_code, string fault_format, ...); diff --git a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata index 38a275447f..4ae8b06798 100644 --- a/vapi/packages/libsoup-2.4/libsoup-2.4.metadata +++ b/vapi/packages/libsoup-2.4/libsoup-2.4.metadata @@ -1,5 +1,7 @@ Soup cheader_filename="libsoup/soup.h" soup_add_io_watch hidden="1" +soup_auth_get_protection_space type_arguments="string" transfer_ownership="1" +soup_auth_free_protection_space hidden="1" soup_auth_is_authenticated hidden="1" soup_auth_is_for_proxy hidden="1" SoupAuthDomain:add-path hidden="1" @@ -17,7 +19,25 @@ soup_auth_domain_digest_set_auth_callback.dnotify hidden="1" SoupBuffer ref_function="soup_buffer_copy" unref_function="soup_buffer_free" soup_buffer_copy transfer_ownership="1" soup_cookie_copy transfer_ownership="1" +soup_cookies_free hidden="1" +soup_cookies_to_cookie_header.cookies type_arguments="Cookie" +soup_cookies_to_request.cookies type_arguments="Cookie" +soup_cookies_to_response.cookies type_arguments="Cookie" +soup_cookie_jar_all_cookies type_arguments="Cookie" transfer_ownership="1" soup_date_copy transfer_ownership="1" +soup_form_decode type_arguments="string,string" transfer_ownership="1" +soup_form_decode_multipart type_arguments="string,string" transfer_ownership="1" +soup_form_decode_multipart.filename transfer_ownership="1" +soup_form_decode_multipart.content_type transfer_ownership="1" +soup_form_decode_multipart.file transfer_ownership="1" +soup_form_encode_hash.form_data_set type_arguments="string,string" +soup_form_request_new_from_hash.form_data_set type_arguments="string,string" +soup_header_free_param_list hidden="1" +soup_header_free_list hidden="1" +soup_header_parse_list type_arguments="string" transfer_ownership="1" +soup_header_parse_param_list type_arguments="string,string" transfer_ownership="1" +soup_header_parse_quality_list type_arguments="string" transfer_ownership="1" +soup_header_parse_quality_list.unacceptable type_arguments="string" soup_logger_set_printer.printer transfer_ownership="1" soup_logger_set_printer.printer_data hidden="1" soup_logger_set_printer.destroy hidden="1" @@ -38,15 +58,21 @@ SoupMessage::wrote_body_data has_emitter="1" SoupMessage::wrote_chunk has_emitter="1" SoupMessage::wrote_headers has_emitter="1" SoupMessage::wrote_informational has_emitter="1" +soup_cookies_from_request type_arguments="Cookie" transfer_ownership="1" +soup_cookies_from_response type_arguments="Cookie" transfer_ownership="1" +soup_header_parse_semi_param_list type_arguments="string,string" transfer_ownership="1" soup_message_headers_get_content_disposition.disposition transfer_ownership="1" soup_message_headers_get_content_disposition.params is_out="1" transfer_ownership="1" nullable="1" soup_message_headers_get_content_type.params is_out="1" transfer_ownership="1" nullable="1" soup_message_set_chunk_allocator.allocator transfer_ownership="1" soup_message_set_chunk_allocator.destroy_notify hidden="1" SoupMessageBody.data type_name="uint8" is_array="1" +soup_message_headers_set_content_disposition.params type_arguments="string,string" nullable="1" +soup_message_headers_set_content_type.params type_arguments="string,string" nullable="1" soup_server_new ellipsis="1" soup_server_add_handler.destroy hidden="1" soup_server_add_handler.callback transfer_ownership="1" +SoupServerCallback.query type_arguments="string,string" SoupSession::add_feature has_emitter="1" SoupSession::add_feature_by_type has_emitter="1" SoupSession::remove_feature_by_type has_emitter="1" @@ -58,8 +84,12 @@ soup_uri_decode transfer_ownership="1" soup_uri_encode transfer_ownership="1" soup_uri_encode.escape_extra nullable="1" soup_uri_copy transfer_ownership="1" +soup_uri_set_query_from_form.form type_arguments="string,string" soup_uri_to_string transfer_ownership="1" soup_uri_normalize transfer_ownership="1" +soup_value_hash_insert ellipsis="1" +soup_value_hash_*.hash type_arguments="string,GLib.Value" +soup_value_hash_new* type_arguments="string,GLib.Value" transfer_ownership="1" soup_xmlrpc_build_fault ellipsis="1" printf_format="1" soup_xmlrpc_extract_method_call ellipsis="1" sentinel="G_TYPE_INVALID" soup_xmlrpc_extract_method_response ellipsis="1" sentinel="G_TYPE_INVALID"
5f9b4443194d3aa3948d76956897c0a1d918d546
spring-framework
bean properties of type enum array/collection can- be populated with comma-separated String (SPR-6547)--
c
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java index 85100b836c2d..049a0694385f 100644 --- a/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java +++ b/org.springframework.beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java @@ -202,6 +202,13 @@ private <T> T convertIfNecessary(String propertyName, Object oldValue, Object ne // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { + if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && + convertedValue instanceof String && typeDescriptor.getMethodParameter() != null) { + Class elementType = GenericCollectionTypeResolver.getCollectionParameterType(typeDescriptor.getMethodParameter()); + if (elementType != null && Enum.class.isAssignableFrom(elementType)) { + convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); + } + } if (editor == null) { editor = findDefaultEditor(requiredType, typeDescriptor); } @@ -214,6 +221,9 @@ private <T> T convertIfNecessary(String propertyName, Object oldValue, Object ne if (convertedValue != null) { if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. + if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { + convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); + } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { diff --git a/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java b/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java index 43182fe69acd..d41aa7a215e6 100644 --- a/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java +++ b/org.springframework.beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2009 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. @@ -17,9 +17,7 @@ package org.springframework.beans; import static org.junit.Assert.*; - import org.junit.Test; - import test.beans.CustomEnum; import test.beans.GenericBean; @@ -53,4 +51,62 @@ public void testCustomEnumWithEmptyString() { assertEquals(null, gb.getCustomEnum()); } + @Test + public void testCustomEnumArrayWithSingleValue() { + GenericBean<?> gb = new GenericBean<Object>(); + BeanWrapper bw = new BeanWrapperImpl(gb); + bw.setPropertyValue("customEnumArray", "VALUE_1"); + assertEquals(1, gb.getCustomEnumArray().length); + assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); + } + + @Test + public void testCustomEnumArrayWithMultipleValues() { + GenericBean<?> gb = new GenericBean<Object>(); + BeanWrapper bw = new BeanWrapperImpl(gb); + bw.setPropertyValue("customEnumArray", new String[] {"VALUE_1", "VALUE_2"}); + assertEquals(2, gb.getCustomEnumArray().length); + assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); + assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]); + } + + @Test + public void testCustomEnumArrayWithMultipleValuesAsCsv() { + GenericBean<?> gb = new GenericBean<Object>(); + BeanWrapper bw = new BeanWrapperImpl(gb); + bw.setPropertyValue("customEnumArray", "VALUE_1,VALUE_2"); + assertEquals(2, gb.getCustomEnumArray().length); + assertEquals(CustomEnum.VALUE_1, gb.getCustomEnumArray()[0]); + assertEquals(CustomEnum.VALUE_2, gb.getCustomEnumArray()[1]); + } + + @Test + public void testCustomEnumSetWithSingleValue() { + GenericBean<?> gb = new GenericBean<Object>(); + BeanWrapper bw = new BeanWrapperImpl(gb); + bw.setPropertyValue("customEnumSet", "VALUE_1"); + assertEquals(1, gb.getCustomEnumSet().size()); + assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); + } + + @Test + public void testCustomEnumSetWithMultipleValues() { + GenericBean<?> gb = new GenericBean<Object>(); + BeanWrapper bw = new BeanWrapperImpl(gb); + bw.setPropertyValue("customEnumSet", new String[] {"VALUE_1", "VALUE_2"}); + assertEquals(2, gb.getCustomEnumSet().size()); + assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); + assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); + } + + @Test + public void testCustomEnumSetWithMultipleValuesAsCsv() { + GenericBean<?> gb = new GenericBean<Object>(); + BeanWrapper bw = new BeanWrapperImpl(gb); + bw.setPropertyValue("customEnumSet", "VALUE_1,VALUE_2"); + assertEquals(2, gb.getCustomEnumSet().size()); + assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_1)); + assertTrue(gb.getCustomEnumSet().contains(CustomEnum.VALUE_2)); + } + } diff --git a/org.springframework.beans/src/test/java/test/beans/GenericBean.java b/org.springframework.beans/src/test/java/test/beans/GenericBean.java index 25f61c4aa756..acb9bdb76e5a 100644 --- a/org.springframework.beans/src/test/java/test/beans/GenericBean.java +++ b/org.springframework.beans/src/test/java/test/beans/GenericBean.java @@ -60,11 +60,14 @@ public class GenericBean<T> { private CustomEnum customEnum; + private CustomEnum[] customEnumArray; + + private Set<CustomEnum> customEnumSet; + private T genericProperty; private List<T> genericListProperty; - public GenericBean() { } @@ -225,6 +228,22 @@ public void setCustomEnum(CustomEnum customEnum) { this.customEnum = customEnum; } + public CustomEnum[] getCustomEnumArray() { + return customEnumArray; + } + + public void setCustomEnumArray(CustomEnum[] customEnum) { + this.customEnumArray = customEnum; + } + + public Set<CustomEnum> getCustomEnumSet() { + return customEnumSet; + } + + public void setCustomEnumSet(Set<CustomEnum> customEnumSet) { + this.customEnumSet = customEnumSet; + } + public static GenericBean createInstance(Set<Integer> integerSet) { return new GenericBean(integerSet); }
0efa78710b4ff36dcf50457a4ec16090bc96787b
elasticsearch
Added clear scroll api.--The clear scroll api allows clear all resources associated with a `scroll_id` by deleting the `scroll_id` and its associated SearchContext.--Closes -3657-
a
https://github.com/elastic/elasticsearch
diff --git a/docs/reference/search/request/search-type.asciidoc b/docs/reference/search/request/search-type.asciidoc index bf3126fea81c7..bb98ea9ad038e 100644 --- a/docs/reference/search/request/search-type.asciidoc +++ b/docs/reference/search/request/search-type.asciidoc @@ -127,3 +127,20 @@ returned. The total_hits will be maintained between scroll requests. Note, scan search type does not support sorting (either on score or a field) or faceting. + +=== Clear scroll api + +added[0.90.4] + +Besides consuming the scroll search until no hits has been returned a scroll +search can also be aborted by deleting the `scroll_id`. This can be done via +the clear scroll api. When the the `scroll_id` has been deleted also all the +resources to keep the view open will cleaned open. Example usage: + +[source,js] +-------------------------------------------------- +curl -XDELETE 'localhost:9200/_search/scroll/c2NhbjsxOjBLMzdpWEtqU2IyZHlmVURPeFJOZnc7MzowSzM3aVhLalNiMmR5ZlVET3hSTmZ3OzU6MEszN2lYS2pTYjJkeWZVRE94Uk5mdzsyOjBLMzdpWEtqU2IyZHlmVURPeFJOZnc7NDowSzM3aVhLalNiMmR5ZlVET3hSTmZ3Ow==' +-------------------------------------------------- + +Multiple scroll ids can be specified in a comma separated manner, if no id is +specified then all scroll ids will be cleared up. \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/action/ActionModule.java b/src/main/java/org/elasticsearch/action/ActionModule.java index 9452696f12d70..18b4c5967c0b3 100644 --- a/src/main/java/org/elasticsearch/action/ActionModule.java +++ b/src/main/java/org/elasticsearch/action/ActionModule.java @@ -253,6 +253,7 @@ protected void configure() { registerAction(PercolateAction.INSTANCE, TransportPercolateAction.class); registerAction(MultiPercolateAction.INSTANCE, TransportMultiPercolateAction.class, TransportShardMultiPercolateAction.class); registerAction(ExplainAction.INSTANCE, TransportExplainAction.class); + registerAction(ClearScrollAction.INSTANCE, TransportClearScrollAction.class); // register Name -> GenericAction Map that can be injected to instances. MapBinder<String, GenericAction> actionsBinder diff --git a/src/main/java/org/elasticsearch/action/search/ClearScrollAction.java b/src/main/java/org/elasticsearch/action/search/ClearScrollAction.java new file mode 100644 index 0000000000000..917f3eb3e7b55 --- /dev/null +++ b/src/main/java/org/elasticsearch/action/search/ClearScrollAction.java @@ -0,0 +1,45 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you 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 + * + * http://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.elasticsearch.action.search; + +import org.elasticsearch.action.Action; +import org.elasticsearch.client.Client; + +/** + */ +public class ClearScrollAction extends Action<ClearScrollRequest, ClearScrollResponse, ClearScrollRequestBuilder> { + + public static final ClearScrollAction INSTANCE = new ClearScrollAction(); + public static final String NAME = "clear_sc"; + + private ClearScrollAction() { + super(NAME); + } + + @Override + public ClearScrollResponse newResponse() { + return new ClearScrollResponse(); + } + + @Override + public ClearScrollRequestBuilder newRequestBuilder(Client client) { + return new ClearScrollRequestBuilder(client); + } +} diff --git a/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java b/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java new file mode 100644 index 0000000000000..ad16a5460578a --- /dev/null +++ b/src/main/java/org/elasticsearch/action/search/ClearScrollRequest.java @@ -0,0 +1,75 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you 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 + * + * http://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.elasticsearch.action.search; + +import org.elasticsearch.action.ActionRequest; +import org.elasticsearch.action.ActionRequestValidationException; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import static com.google.common.collect.Lists.newArrayList; + +/** + */ +public class ClearScrollRequest extends ActionRequest { + + private List<String> scrollIds; + + public List<String> getScrollIds() { + return scrollIds; + } + + public void setScrollIds(List<String> scrollIds) { + this.scrollIds = scrollIds; + } + + public void addScrollId(String scrollId) { + if (scrollIds == null) { + scrollIds = newArrayList(); + } + scrollIds.add(scrollId); + } + + @Override + public ActionRequestValidationException validate() { + return null; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + scrollIds = Arrays.asList(in.readStringArray()); + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + if (scrollIds == null) { + out.writeVInt(0); + } else { + out.writeStringArray(scrollIds.toArray(new String[scrollIds.size()])); + } + } + +} diff --git a/src/main/java/org/elasticsearch/action/search/ClearScrollRequestBuilder.java b/src/main/java/org/elasticsearch/action/search/ClearScrollRequestBuilder.java new file mode 100644 index 0000000000000..e984a4f171271 --- /dev/null +++ b/src/main/java/org/elasticsearch/action/search/ClearScrollRequestBuilder.java @@ -0,0 +1,51 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you 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 + * + * http://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.elasticsearch.action.search; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.ActionRequestBuilder; +import org.elasticsearch.client.Client; +import org.elasticsearch.client.internal.InternalClient; + +import java.util.List; + +/** + */ +public class ClearScrollRequestBuilder extends ActionRequestBuilder<ClearScrollRequest, ClearScrollResponse, ClearScrollRequestBuilder> { + + public ClearScrollRequestBuilder(Client client) { + super((InternalClient) client, new ClearScrollRequest()); + } + + public ClearScrollRequestBuilder setScrollIds(List<String> cursorIds) { + request.setScrollIds(cursorIds); + return this; + } + + public ClearScrollRequestBuilder addScrollId(String cursorId) { + request.addScrollId(cursorId); + return this; + } + + @Override + protected void doExecute(ActionListener<ClearScrollResponse> listener) { + ((Client) client).clearScroll(request, listener); + } +} diff --git a/src/main/java/org/elasticsearch/action/search/ClearScrollResponse.java b/src/main/java/org/elasticsearch/action/search/ClearScrollResponse.java new file mode 100644 index 0000000000000..8dced0fb4da7f --- /dev/null +++ b/src/main/java/org/elasticsearch/action/search/ClearScrollResponse.java @@ -0,0 +1,56 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you 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 + * + * http://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.elasticsearch.action.search; + +import org.elasticsearch.action.ActionResponse; +import org.elasticsearch.common.io.stream.StreamInput; +import org.elasticsearch.common.io.stream.StreamOutput; + +import java.io.IOException; + +/** + */ +public class ClearScrollResponse extends ActionResponse { + + private boolean succeeded; + + public ClearScrollResponse(boolean succeeded) { + this.succeeded = succeeded; + } + + ClearScrollResponse() { + } + + public boolean isSucceeded() { + return succeeded; + } + + @Override + public void readFrom(StreamInput in) throws IOException { + super.readFrom(in); + succeeded = in.readBoolean(); + } + + @Override + public void writeTo(StreamOutput out) throws IOException { + super.writeTo(out); + out.writeBoolean(succeeded); + } +} diff --git a/src/main/java/org/elasticsearch/action/search/TransportClearScrollAction.java b/src/main/java/org/elasticsearch/action/search/TransportClearScrollAction.java new file mode 100644 index 0000000000000..396cae028cd86 --- /dev/null +++ b/src/main/java/org/elasticsearch/action/search/TransportClearScrollAction.java @@ -0,0 +1,153 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you 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 + * + * http://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.elasticsearch.action.search; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.support.TransportAction; +import org.elasticsearch.cluster.ClusterService; +import org.elasticsearch.cluster.ClusterState; +import org.elasticsearch.cluster.node.DiscoveryNode; +import org.elasticsearch.cluster.node.DiscoveryNodes; +import org.elasticsearch.common.collect.Tuple; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.search.action.SearchServiceTransportAction; +import org.elasticsearch.threadpool.ThreadPool; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.elasticsearch.action.search.type.TransportSearchHelper.parseScrollId; + +/** + */ +public class TransportClearScrollAction extends TransportAction<ClearScrollRequest, ClearScrollResponse> { + + private final ClusterService clusterService; + private final SearchServiceTransportAction searchServiceTransportAction; + + @Inject + public TransportClearScrollAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, SearchServiceTransportAction searchServiceTransportAction) { + super(settings, threadPool); + this.clusterService = clusterService; + this.searchServiceTransportAction = searchServiceTransportAction; + } + + @Override + protected void doExecute(ClearScrollRequest request, final ActionListener<ClearScrollResponse> listener) { + new Async(request, listener, clusterService.state()).run(); + } + + private class Async { + + final DiscoveryNodes nodes; + final AtomicInteger expectedOps; + final ClearScrollRequest request; + final List<Tuple<String, Long>[]> contexts = new ArrayList<Tuple<String, Long>[]>(); + final AtomicReference<Throwable> expHolder; + final ActionListener<ClearScrollResponse> listener; + + private Async(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener, ClusterState clusterState) { + int expectedOps = 0; + this.nodes = clusterState.nodes(); + if (request.getScrollIds() == null || request.getScrollIds().isEmpty()) { + expectedOps = nodes.size(); + } else { + for (String parsedScrollId : request.getScrollIds()) { + Tuple<String, Long>[] context = parseScrollId(parsedScrollId).getContext(); + expectedOps += context.length; + this.contexts.add(context); + } + } + + this.request = request; + this.listener = listener; + this.expHolder = new AtomicReference<Throwable>(); + this.expectedOps = new AtomicInteger(expectedOps); + } + + public void run() { + if (expectedOps.get() == 0) { + listener.onResponse(new ClearScrollResponse(true)); + return; + } + + if (contexts.isEmpty()) { + for (final DiscoveryNode node : nodes) { + searchServiceTransportAction.sendClearAllScrollContexts(node, request, new ActionListener<Boolean>() { + @Override + public void onResponse(Boolean success) { + onFreedContext(); + } + + @Override + public void onFailure(Throwable e) { + onFailedFreedContext(e, node); + } + }); + } + } else { + for (Tuple<String, Long>[] context : contexts) { + for (Tuple<String, Long> target : context) { + final DiscoveryNode node = nodes.get(target.v1()); + if (node == null) { + onFreedContext(); + continue; + } + + searchServiceTransportAction.sendFreeContext(node, target.v2(), request, new ActionListener<Boolean>() { + @Override + public void onResponse(Boolean success) { + onFreedContext(); + } + + @Override + public void onFailure(Throwable e) { + onFailedFreedContext(e, node); + } + }); + } + } + } + } + + void onFreedContext() { + assert expectedOps.get() > 0; + if (expectedOps.decrementAndGet() == 0) { + boolean succeeded = expHolder.get() == null; + listener.onResponse(new ClearScrollResponse(succeeded)); + } + } + + void onFailedFreedContext(Throwable e, DiscoveryNode node) { + logger.warn("Clear SC failed on node[{}]", e, node); + assert expectedOps.get() > 0; + if (expectedOps.decrementAndGet() == 0) { + listener.onResponse(new ClearScrollResponse(false)); + } else { + expHolder.set(e); + } + } + + } + +} diff --git a/src/main/java/org/elasticsearch/client/Client.java b/src/main/java/org/elasticsearch/client/Client.java index 98d916cc4561f..97b935e1b77d1 100644 --- a/src/main/java/org/elasticsearch/client/Client.java +++ b/src/main/java/org/elasticsearch/client/Client.java @@ -540,4 +540,19 @@ public interface Client { */ void explain(ExplainRequest request, ActionListener<ExplainResponse> listener); + /** + * Clears the search contexts associated with specified scroll ids. + */ + ClearScrollRequestBuilder prepareClearScroll(); + + /** + * Clears the search contexts associated with specified scroll ids. + */ + ActionFuture<ClearScrollResponse> clearScroll(ClearScrollRequest request); + + /** + * Clears the search contexts associated with specified scroll ids. + */ + void clearScroll(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener); + } \ No newline at end of file diff --git a/src/main/java/org/elasticsearch/client/support/AbstractClient.java b/src/main/java/org/elasticsearch/client/support/AbstractClient.java index d16ada20e3f48..c7bad1d8d289a 100644 --- a/src/main/java/org/elasticsearch/client/support/AbstractClient.java +++ b/src/main/java/org/elasticsearch/client/support/AbstractClient.java @@ -366,4 +366,19 @@ public ActionFuture<ExplainResponse> explain(ExplainRequest request) { public void explain(ExplainRequest request, ActionListener<ExplainResponse> listener) { execute(ExplainAction.INSTANCE, request, listener); } + + @Override + public void clearScroll(ClearScrollRequest request, ActionListener<ClearScrollResponse> listener) { + execute(ClearScrollAction.INSTANCE, request, listener); + } + + @Override + public ActionFuture<ClearScrollResponse> clearScroll(ClearScrollRequest request) { + return execute(ClearScrollAction.INSTANCE, request); + } + + @Override + public ClearScrollRequestBuilder prepareClearScroll() { + return new ClearScrollRequestBuilder(this); + } } diff --git a/src/main/java/org/elasticsearch/rest/action/RestActionModule.java b/src/main/java/org/elasticsearch/rest/action/RestActionModule.java index 2bea5451a5052..951ade07c5404 100644 --- a/src/main/java/org/elasticsearch/rest/action/RestActionModule.java +++ b/src/main/java/org/elasticsearch/rest/action/RestActionModule.java @@ -86,6 +86,7 @@ import org.elasticsearch.rest.action.mlt.RestMoreLikeThisAction; import org.elasticsearch.rest.action.percolate.RestMultiPercolateAction; import org.elasticsearch.rest.action.percolate.RestPercolateAction; +import org.elasticsearch.rest.action.search.RestClearScrollAction; import org.elasticsearch.rest.action.search.RestMultiSearchAction; import org.elasticsearch.rest.action.search.RestSearchAction; import org.elasticsearch.rest.action.search.RestSearchScrollAction; @@ -199,5 +200,6 @@ protected void configure() { bind(RestIndicesAction.class).asEagerSingleton(); // Fully qualified to prevent interference with rest.action.count.RestCountAction bind(org.elasticsearch.rest.action.cat.RestCountAction.class).asEagerSingleton(); + bind(RestClearScrollAction.class).asEagerSingleton();; } } diff --git a/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java b/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java new file mode 100644 index 0000000000000..1c6979dc42688 --- /dev/null +++ b/src/main/java/org/elasticsearch/rest/action/search/RestClearScrollAction.java @@ -0,0 +1,95 @@ +/* + * Licensed to ElasticSearch and Shay Banon under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. ElasticSearch licenses this + * file to you 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 + * + * http://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.elasticsearch.rest.action.search; + +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.search.ClearScrollRequest; +import org.elasticsearch.action.search.ClearScrollResponse; +import org.elasticsearch.client.Client; +import org.elasticsearch.common.Strings; +import org.elasticsearch.common.inject.Inject; +import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.common.xcontent.XContentBuilder; +import org.elasticsearch.common.xcontent.XContentBuilderString; +import org.elasticsearch.rest.*; + +import java.io.IOException; +import java.util.Arrays; + +import static org.elasticsearch.rest.RestRequest.Method.DELETE; +import static org.elasticsearch.rest.RestStatus.OK; +import static org.elasticsearch.rest.action.support.RestXContentBuilder.restContentBuilder; + +/** + */ +public class RestClearScrollAction extends BaseRestHandler { + + @Inject + public RestClearScrollAction(Settings settings, Client client, RestController controller) { + super(settings, client); + + controller.registerHandler(DELETE, "/_search/scroll", this); + controller.registerHandler(DELETE, "/_search/scroll/{scroll_id}", this); + } + + @Override + public void handleRequest(final RestRequest request, final RestChannel channel) { + String scrollIds = request.param("scroll_id"); + + ClearScrollRequest clearRequest = new ClearScrollRequest(); + clearRequest.setScrollIds(Arrays.asList(splitScrollIds(scrollIds))); + client.clearScroll(clearRequest, new ActionListener<ClearScrollResponse>() { + @Override + public void onResponse(ClearScrollResponse response) { + try { + XContentBuilder builder = restContentBuilder(request); + builder.startObject(); + builder.field(Fields.OK, response.isSucceeded()); + builder.endObject(); + channel.sendResponse(new XContentRestResponse(request, OK, builder)); + } catch (Throwable e) { + onFailure(e); + } + } + + @Override + public void onFailure(Throwable e) { + try { + channel.sendResponse(new XContentThrowableRestResponse(request, e)); + } catch (IOException e1) { + logger.error("Failed to send failure response", e1); + } + } + }); + } + + public static String[] splitScrollIds(String scrollIds) { + if (scrollIds == null) { + return Strings.EMPTY_ARRAY; + } + return Strings.splitStringByCommaToArray(scrollIds); + } + + static final class Fields { + + static final XContentBuilderString OK = new XContentBuilderString("ok"); + + } +} diff --git a/src/main/java/org/elasticsearch/search/SearchService.java b/src/main/java/org/elasticsearch/search/SearchService.java index f02a18332625f..53455a74b8ca4 100644 --- a/src/main/java/org/elasticsearch/search/SearchService.java +++ b/src/main/java/org/elasticsearch/search/SearchService.java @@ -509,6 +509,14 @@ private void freeContext(SearchContext context) { context.release(); } + public void freeAllScrollContexts() { + for (SearchContext searchContext : activeContexts.values()) { + if (searchContext.scroll() != null) { + freeContext(searchContext); + } + } + } + private void contextProcessing(SearchContext context) { // disable timeout while executing a search context.accessed(-1); diff --git a/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java b/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java index ecdd0be90a8b9..3ff0ae0c94687 100644 --- a/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java +++ b/src/main/java/org/elasticsearch/search/action/SearchServiceTransportAction.java @@ -19,6 +19,8 @@ package org.elasticsearch.search.action; +import org.elasticsearch.action.ActionListener; +import org.elasticsearch.action.search.ClearScrollRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.node.DiscoveryNode; @@ -81,6 +83,7 @@ public SearchServiceTransportAction(Settings settings, TransportService transpor this.searchService = searchService; transportService.registerHandler(SearchFreeContextTransportHandler.ACTION, new SearchFreeContextTransportHandler()); + transportService.registerHandler(ClearScrollContextsTransportHandler.ACTION, new ClearScrollContextsTransportHandler()); transportService.registerHandler(SearchDfsTransportHandler.ACTION, new SearchDfsTransportHandler()); transportService.registerHandler(SearchQueryTransportHandler.ACTION, new SearchQueryTransportHandler()); transportService.registerHandler(SearchQueryByIdTransportHandler.ACTION, new SearchQueryByIdTransportHandler()); @@ -101,6 +104,64 @@ public void sendFreeContext(DiscoveryNode node, final long contextId, SearchRequ } } + public void sendFreeContext(DiscoveryNode node, long contextId, ClearScrollRequest request, final ActionListener<Boolean> actionListener) { + if (clusterService.state().nodes().localNodeId().equals(node.id())) { + searchService.freeContext(contextId); + actionListener.onResponse(true); + } else { + transportService.sendRequest(node, SearchFreeContextTransportHandler.ACTION, new SearchFreeContextRequest(request, contextId), new TransportResponseHandler<TransportResponse>() { + @Override + public TransportResponse newInstance() { + return TransportResponse.Empty.INSTANCE; + } + + @Override + public void handleResponse(TransportResponse response) { + actionListener.onResponse(true); + } + + @Override + public void handleException(TransportException exp) { + actionListener.onFailure(exp); + } + + @Override + public String executor() { + return ThreadPool.Names.SAME; + } + }); + } + } + + public void sendClearAllScrollContexts(DiscoveryNode node, ClearScrollRequest request, final ActionListener<Boolean> actionListener) { + if (clusterService.state().nodes().localNodeId().equals(node.id())) { + searchService.freeAllScrollContexts(); + actionListener.onResponse(true); + } else { + transportService.sendRequest(node, ClearScrollContextsTransportHandler.ACTION, new ClearScrollContextsRequest(request), new TransportResponseHandler<TransportResponse>() { + @Override + public TransportResponse newInstance() { + return TransportResponse.Empty.INSTANCE; + } + + @Override + public void handleResponse(TransportResponse response) { + actionListener.onResponse(true); + } + + @Override + public void handleException(TransportException exp) { + actionListener.onFailure(exp); + } + + @Override + public String executor() { + return ThreadPool.Names.SAME; + } + }); + } + } + public void sendExecuteDfs(DiscoveryNode node, final ShardSearchRequest request, final SearchServiceListener<DfsSearchResult> listener) { if (clusterService.state().nodes().localNodeId().equals(node.id())) { try { @@ -448,7 +509,7 @@ class SearchFreeContextRequest extends TransportRequest { SearchFreeContextRequest() { } - SearchFreeContextRequest(SearchRequest request, long id) { + SearchFreeContextRequest(TransportRequest request, long id) { super(request); this.id = id; } @@ -493,6 +554,39 @@ public String executor() { } } + class ClearScrollContextsRequest extends TransportRequest { + + ClearScrollContextsRequest() { + } + + ClearScrollContextsRequest(TransportRequest request) { + super(request); + } + + } + + class ClearScrollContextsTransportHandler extends BaseTransportRequestHandler<ClearScrollContextsRequest> { + + static final String ACTION = "search/clearScrollContexts"; + + @Override + public ClearScrollContextsRequest newInstance() { + return new ClearScrollContextsRequest(); + } + + @Override + public void messageReceived(ClearScrollContextsRequest request, TransportChannel channel) throws Exception { + searchService.freeAllScrollContexts(); + channel.sendResponse(TransportResponse.Empty.INSTANCE); + } + + @Override + public String executor() { + // freeing the context is cheap, + // no need for fork it to another thread + return ThreadPool.Names.SAME; + } + } private class SearchDfsTransportHandler extends BaseTransportRequestHandler<ShardSearchRequest> { diff --git a/src/test/java/org/elasticsearch/test/integration/search/scroll/SearchScrollTests.java b/src/test/java/org/elasticsearch/test/integration/search/scroll/SearchScrollTests.java index bffc6077d4560..3f04758b6ca8c 100644 --- a/src/test/java/org/elasticsearch/test/integration/search/scroll/SearchScrollTests.java +++ b/src/test/java/org/elasticsearch/test/integration/search/scroll/SearchScrollTests.java @@ -19,6 +19,7 @@ package org.elasticsearch.test.integration.search.scroll; +import org.elasticsearch.action.search.ClearScrollResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.Priority; @@ -33,7 +34,6 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; /** @@ -217,4 +217,179 @@ public void testScrollAndUpdateIndex() throws Exception { assertThat(client().prepareCount().setQuery(termQuery("message", "update")).execute().actionGet().getCount(), equalTo(500l)); assertThat(client().prepareCount().setQuery(termQuery("message", "update")).execute().actionGet().getCount(), equalTo(500l)); } + + @Test + public void testSimpleScrollQueryThenFetch_clearScrollIds() throws Exception { + try { + client().admin().indices().prepareDelete("test").execute().actionGet(); + } catch (Exception e) { + // ignore + } + client().admin().indices().prepareCreate("test").setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 3)).execute().actionGet(); + client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); + + client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); + + for (int i = 0; i < 100; i++) { + client().prepareIndex("test", "type1", Integer.toString(i)).setSource(jsonBuilder().startObject().field("field", i).endObject()).execute().actionGet(); + } + + client().admin().indices().prepareRefresh().execute().actionGet(); + + SearchResponse searchResponse1 = client().prepareSearch() + .setQuery(matchAllQuery()) + .setSize(35) + .setScroll(TimeValue.timeValueMinutes(2)) + .addSort("field", SortOrder.ASC) + .execute().actionGet(); + + SearchResponse searchResponse2 = client().prepareSearch() + .setQuery(matchAllQuery()) + .setSize(35) + .setScroll(TimeValue.timeValueMinutes(2)) + .addSort("field", SortOrder.ASC) + .execute().actionGet(); + + long counter1 = 0; + long counter2 = 0; + + assertThat(searchResponse1.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse1.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse1.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter1++)); + } + + assertThat(searchResponse2.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse2.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse2.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter2++)); + } + + searchResponse1 = client().prepareSearchScroll(searchResponse1.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + searchResponse2 = client().prepareSearchScroll(searchResponse2.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + assertThat(searchResponse1.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse1.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse1.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter1++)); + } + + assertThat(searchResponse2.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse2.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse2.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter2++)); + } + + ClearScrollResponse clearResponse = client().prepareClearScroll() + .addScrollId(searchResponse1.getScrollId()) + .addScrollId(searchResponse2.getScrollId()) + .execute().actionGet(); + assertThat(clearResponse.isSucceeded(), equalTo(true)); + + searchResponse1 = client().prepareSearchScroll(searchResponse1.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + searchResponse2 = client().prepareSearchScroll(searchResponse2.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + assertThat(searchResponse1.getHits().getTotalHits(), equalTo(0l)); + assertThat(searchResponse1.getHits().hits().length, equalTo(0)); + + assertThat(searchResponse2.getHits().getTotalHits(), equalTo(0l)); + assertThat(searchResponse2.getHits().hits().length, equalTo(0)); + } + + @Test + public void testSimpleScrollQueryThenFetch_clearAllScrollIds() throws Exception { + try { + client().admin().indices().prepareDelete("test").execute().actionGet(); + } catch (Exception e) { + // ignore + } + client().admin().indices().prepareCreate("test").setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 3)).execute().actionGet(); + client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); + + client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); + + for (int i = 0; i < 100; i++) { + client().prepareIndex("test", "type1", Integer.toString(i)).setSource(jsonBuilder().startObject().field("field", i).endObject()).execute().actionGet(); + } + + client().admin().indices().prepareRefresh().execute().actionGet(); + + SearchResponse searchResponse1 = client().prepareSearch() + .setQuery(matchAllQuery()) + .setSize(35) + .setScroll(TimeValue.timeValueMinutes(2)) + .addSort("field", SortOrder.ASC) + .execute().actionGet(); + + SearchResponse searchResponse2 = client().prepareSearch() + .setQuery(matchAllQuery()) + .setSize(35) + .setScroll(TimeValue.timeValueMinutes(2)) + .addSort("field", SortOrder.ASC) + .execute().actionGet(); + + long counter1 = 0; + long counter2 = 0; + + assertThat(searchResponse1.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse1.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse1.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter1++)); + } + + assertThat(searchResponse2.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse2.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse2.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter2++)); + } + + searchResponse1 = client().prepareSearchScroll(searchResponse1.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + searchResponse2 = client().prepareSearchScroll(searchResponse2.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + assertThat(searchResponse1.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse1.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse1.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter1++)); + } + + assertThat(searchResponse2.getHits().getTotalHits(), equalTo(100l)); + assertThat(searchResponse2.getHits().hits().length, equalTo(35)); + for (SearchHit hit : searchResponse2.getHits()) { + assertThat(((Number) hit.sortValues()[0]).longValue(), equalTo(counter2++)); + } + + ClearScrollResponse clearResponse = client().prepareClearScroll() + .execute().actionGet(); + assertThat(clearResponse.isSucceeded(), equalTo(true)); + + searchResponse1 = client().prepareSearchScroll(searchResponse1.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + searchResponse2 = client().prepareSearchScroll(searchResponse2.getScrollId()) + .setScroll(TimeValue.timeValueMinutes(2)) + .execute().actionGet(); + + assertThat(searchResponse1.getHits().getTotalHits(), equalTo(0l)); + assertThat(searchResponse1.getHits().hits().length, equalTo(0)); + + assertThat(searchResponse2.getHits().getTotalHits(), equalTo(0l)); + assertThat(searchResponse2.getHits().hits().length, equalTo(0)); + } + }
629acade597d92dbfd8d020497a0ba523afd1754
ReactiveX-RxJava
Add operators to create Observables from- BroadcastReceiver--it allows to listen global and local (with support LocalBroadcastManager) broadcasts-
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-contrib/rxjava-android/src/main/java/rx/android/observables/AndroidObservable.java b/rxjava-contrib/rxjava-android/src/main/java/rx/android/observables/AndroidObservable.java index 498a9547f7..e891ded435 100644 --- a/rxjava-contrib/rxjava-android/src/main/java/rx/android/observables/AndroidObservable.java +++ b/rxjava-contrib/rxjava-android/src/main/java/rx/android/observables/AndroidObservable.java @@ -15,16 +15,22 @@ */ package rx.android.observables; -import static rx.android.schedulers.AndroidSchedulers.mainThread; +import android.app.Activity; +import android.app.Fragment; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Build; +import android.os.Handler; import rx.Observable; import rx.functions.Func1; -import rx.operators.OperatorObserveFromAndroidComponent; +import rx.operators.OperatorBroadcastRegister; import rx.operators.OperatorConditionalBinding; +import rx.operators.OperatorLocalBroadcastRegister; +import rx.operators.OperatorObserveFromAndroidComponent; -import android.app.Activity; -import android.app.Fragment; -import android.os.Build; +import static rx.android.schedulers.AndroidSchedulers.mainThread; public final class AndroidObservable { @@ -176,4 +182,37 @@ public static <T> Observable<T> bindFragment(Object fragment, Observable<T> sour throw new IllegalArgumentException("Target fragment is neither a native nor support library Fragment"); } } + + /** + * Create Observable that wraps BroadcastReceiver and emmit received intents. + * + * @param filter Selects the Intent broadcasts to be received. + */ + public static Observable<Intent> fromBroadcast(Context context, IntentFilter filter){ + return Observable.create(new OperatorBroadcastRegister(context, filter, null, null)); + } + + /** + * Create Observable that wraps BroadcastReceiver and emmit received intents. + * + * @param filter Selects the Intent broadcasts to be received. + * @param broadcastPermission String naming a permissions that a + * broadcaster must hold in order to send an Intent to you. If null, + * no permission is required. + * @param schedulerHandler Handler identifying the thread that will receive + * the Intent. If null, the main thread of the process will be used. + */ + public static Observable<Intent> fromBroadcast(Context context, IntentFilter filter, String broadcastPermission, Handler schedulerHandler){ + return Observable.create(new OperatorBroadcastRegister(context, filter, broadcastPermission, schedulerHandler)); + } + + /** + * Create Observable that wraps BroadcastReceiver and connects to LocalBroadcastManager + * to emmit received intents. + * + * @param filter Selects the Intent broadcasts to be received. + */ + public static Observable<Intent> fromLocalBroadcast(Context context, IntentFilter filter){ + return Observable.create(new OperatorLocalBroadcastRegister(context, filter)); + } } diff --git a/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java new file mode 100644 index 0000000000..49bc1dfaf4 --- /dev/null +++ b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorBroadcastRegister.java @@ -0,0 +1,67 @@ +/** + * Copyright 2014 Netflix, Inc. + * + * 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 + * + * http://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 rx.operators; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Handler; + +import rx.Observable; +import rx.Subscriber; +import rx.Subscription; +import rx.android.subscriptions.AndroidSubscriptions; +import rx.functions.Action0; + +public class OperatorBroadcastRegister implements Observable.OnSubscribe<Intent> { + + private final Context context; + private final IntentFilter intentFilter; + private final String broadcastPermission; + private final Handler schedulerHandler; + + public OperatorBroadcastRegister(Context context, IntentFilter intentFilter, String broadcastPermission, Handler schedulerHandler) { + this.context = context; + this.intentFilter = intentFilter; + this.broadcastPermission = broadcastPermission; + this.schedulerHandler = schedulerHandler; + } + + @Override + public void call(final Subscriber<? super Intent> subscriber) { + final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + subscriber.onNext(intent); + } + }; + + final Subscription subscription = AndroidSubscriptions.unsubscribeInUiThread(new Action0() { + @Override + public void call() { + context.unregisterReceiver(broadcastReceiver); + } + }); + + subscriber.add(subscription); + Intent stickyIntent = context.registerReceiver(broadcastReceiver, intentFilter, broadcastPermission, schedulerHandler); + if (stickyIntent != null) { + subscriber.onNext(stickyIntent); + } + + } +} diff --git a/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorLocalBroadcastRegister.java b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorLocalBroadcastRegister.java new file mode 100644 index 0000000000..22a8a8959c --- /dev/null +++ b/rxjava-contrib/rxjava-android/src/main/java/rx/operators/OperatorLocalBroadcastRegister.java @@ -0,0 +1,60 @@ +/** + * Copyright 2014 Netflix, Inc. + * + * 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 + * + * http://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 rx.operators; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.support.v4.content.LocalBroadcastManager; + +import rx.Observable; +import rx.Subscriber; +import rx.Subscription; +import rx.android.subscriptions.AndroidSubscriptions; +import rx.functions.Action0; + +public class OperatorLocalBroadcastRegister implements Observable.OnSubscribe<Intent> { + + private final Context context; + private final IntentFilter intentFilter; + + public OperatorLocalBroadcastRegister(Context context, IntentFilter intentFilter) { + this.context = context; + this.intentFilter = intentFilter; + } + + @Override + public void call(final Subscriber<? super Intent> subscriber) { + final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context); + final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + subscriber.onNext(intent); + } + }; + + final Subscription subscription = AndroidSubscriptions.unsubscribeInUiThread(new Action0() { + @Override + public void call() { + localBroadcastManager.unregisterReceiver(broadcastReceiver); + } + }); + + subscriber.add(subscription); + localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter); + } +} diff --git a/rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperatorLocalBroadcastRegisterTest.java b/rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperatorLocalBroadcastRegisterTest.java new file mode 100644 index 0000000000..902c49022d --- /dev/null +++ b/rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperatorLocalBroadcastRegisterTest.java @@ -0,0 +1,73 @@ +/** + * Copyright 2014 Netflix, Inc. + * + * 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 + * + * http://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 rx.android.operators; + +import android.app.Application; +import android.content.Intent; +import android.content.IntentFilter; +import android.support.v4.content.LocalBroadcastManager; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InOrder; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; + +import rx.Observable; +import rx.Observer; +import rx.Subscription; +import rx.android.observables.AndroidObservable; +import rx.observers.TestObserver; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; + +@RunWith(RobolectricTestRunner.class) +public class OperatorLocalBroadcastRegisterTest { + + @Test + @SuppressWarnings("unchecked") + public void testLocalBroadcast() { + String action = "TEST_ACTION"; + IntentFilter intentFilter = new IntentFilter(action); + Application application = Robolectric.application; + Observable<Intent> observable = AndroidObservable.fromLocalBroadcast(application, intentFilter); + final Observer<Intent> observer = mock(Observer.class); + final Subscription subscription = observable.subscribe(new TestObserver<Intent>(observer)); + + final InOrder inOrder = inOrder(observer); + + inOrder.verify(observer, never()).onNext(any(Intent.class)); + + Intent intent = new Intent(action); + LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(application); + localBroadcastManager.sendBroadcast(intent); + inOrder.verify(observer, times(1)).onNext(intent); + + localBroadcastManager.sendBroadcast(intent); + inOrder.verify(observer, times(1)).onNext(intent); + + subscription.unsubscribe(); + inOrder.verify(observer, never()).onNext(any(Intent.class)); + + inOrder.verify(observer, never()).onError(any(Throwable.class)); + inOrder.verify(observer, never()).onCompleted(); + } + +}
7b301d160b20e37c9bedcfed7c9d12dd7e603a6f
restlet-framework-java
Compute logged duration only if needed.--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/LogFilter.java b/modules/com.noelios.restlet/src/com/noelios/restlet/LogFilter.java index 5f935fa21b..1e97a9a1dd 100644 --- a/modules/com.noelios.restlet/src/com/noelios/restlet/LogFilter.java +++ b/modules/com.noelios.restlet/src/com/noelios/restlet/LogFilter.java @@ -49,9 +49,9 @@ * several threads at the same time and therefore must be thread-safe. You * should be especially careful when storing state in member variables. * - * @see <a + * @see <a * * href="http://www.restlet.org/documentation/1.1/tutorial#part07">Tutorial - * : Filters and call logging</a> + * * : Filters and call logging< /a> * @author Jerome Louvel */ public class LogFilter extends Filter { @@ -101,16 +101,17 @@ public LogFilter(Context context, LogService logService) { */ @Override protected void afterHandle(Request request, Response response) { - final long startTime = (Long) request.getAttributes().get( - "org.restlet.startTime"); - final int duration = (int) (System.currentTimeMillis() - startTime); - // Format the call into a log entry if (this.logTemplate != null) { this.logLogger.log(Level.INFO, format(request, response)); } else { - this.logLogger.log(Level.INFO, formatDefault(request, response, - duration)); + if (this.logLogger.isLoggable(Level.INFO)) { + final long startTime = (Long) request.getAttributes().get( + "org.restlet.startTime"); + final int duration = (int) (System.currentTimeMillis() - startTime); + this.logLogger.log(Level.INFO, formatDefault(request, response, + duration)); + } } }
859f9b8494cb6c7fec7f9b803bc975e7fb3b8ab4
Mylyn Reviews
322734: Renamed part/section to review
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java index 772324ca..a91c237a 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java @@ -73,7 +73,7 @@ public class ReviewTaskEditorPart extends AbstractTaskEditorPart { private Composite composite; public ReviewTaskEditorPart() { - setPartName("Scope"); + setPartName("Review"); setExpandVertically(true); }
76fcc81bc61342ed85f7a8a0c325e58162ff24e8
spring-framework
New method to return string representation of- typeDescriptor--
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java b/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java index 0d686c3832e2..f01863014e45 100644 --- a/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java +++ b/org.springframework.core/src/main/java/org/springframework/core/convert/TypeDescriptor.java @@ -25,6 +25,7 @@ import org.springframework.core.MethodParameter; import org.springframework.util.Assert; +// TODO doesn't support more than depth of one (eg. Map<String,List<Foo>> or List<String>[]) /** * Type metadata about a bindable target value. * @@ -269,6 +270,33 @@ public static TypeDescriptor forObject(Object object) { return valueOf(object.getClass()); } } + + /** + * @return a textual representation of the type descriptor (eg. Map<String,Foo>) for use in messages + */ + public String asString() { + StringBuffer stringValue = new StringBuffer(); + if (isArray()) { + // TODO should properly handle multi dimensional arrays + stringValue.append(getArrayComponentType().getName()).append("[]"); + } else { + stringValue.append(getType().getName()); + if (isCollection()) { + Class<?> collectionType = getCollectionElementType(); + if (collectionType!=null) { + stringValue.append("<").append(collectionType.getName()).append(">"); + } + } else if (isMap()) { + Class<?> keyType = getMapKeyType(); + Class<?> valType = getMapValueType(); + if (keyType!=null && valType!=null) { + stringValue.append("<").append(keyType.getName()).append(","); + stringValue.append(valType).append(">"); + } + } + } + return stringValue.toString(); + } // internal helpers
143e48c25abfebb6c8c6d3250c0745f5636398b4
hadoop
YARN-2493. Added node-labels page on RM web UI.- Contributed by Wangda Tan (cherry picked from commit- b7442bf92eb6e1ae64a0f9644ffc2eee4597aad5)--
a
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index e4622a136405f..d52acc79854e0 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -123,6 +123,8 @@ Release 2.7.0 - UNRELEASED YARN-2993. Several fixes (missing acl check, error log msg ...) and some refinement in AdminService. (Yi Liu via junping_du) + YARN-2943. Added node-labels page on RM web UI. (Wangda Tan via jianhe) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java index 070aa1fc85864..e888cc56d8229 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java @@ -72,8 +72,8 @@ public class CommonNodeLabelsManager extends AbstractService { protected Dispatcher dispatcher; - protected ConcurrentMap<String, Label> labelCollections = - new ConcurrentHashMap<String, Label>(); + protected ConcurrentMap<String, NodeLabel> labelCollections = + new ConcurrentHashMap<String, NodeLabel>(); protected ConcurrentMap<String, Host> nodeCollections = new ConcurrentHashMap<String, Host>(); @@ -82,19 +82,6 @@ public class CommonNodeLabelsManager extends AbstractService { protected NodeLabelsStore store; - protected static class Label { - private Resource resource; - - protected Label() { - this.resource = Resource.newInstance(0, 0); - } - - public Resource getResource() { - return this.resource; - } - - } - /** * A <code>Host</code> can have multiple <code>Node</code>s */ @@ -201,7 +188,7 @@ protected void initDispatcher(Configuration conf) { protected void serviceInit(Configuration conf) throws Exception { initNodeLabelStore(conf); - labelCollections.put(NO_LABEL, new Label()); + labelCollections.put(NO_LABEL, new NodeLabel(NO_LABEL)); } protected void initNodeLabelStore(Configuration conf) throws Exception { @@ -271,7 +258,7 @@ public void addToCluserNodeLabels(Set<String> labels) throws IOException { for (String label : labels) { // shouldn't overwrite it to avoid changing the Label.resource if (this.labelCollections.get(label) == null) { - this.labelCollections.put(label, new Label()); + this.labelCollections.put(label, new NodeLabel(label)); newLabels.add(label); } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabel.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabel.java new file mode 100644 index 0000000000000..766864887d02f --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabel.java @@ -0,0 +1,96 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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.apache.hadoop.yarn.nodelabels; + +import org.apache.commons.lang.StringUtils; +import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.util.resource.Resources; + +public class NodeLabel implements Comparable<NodeLabel> { + private Resource resource; + private int numActiveNMs; + private String labelName; + + public NodeLabel(String labelName) { + this(labelName, Resource.newInstance(0, 0), 0); + } + + protected NodeLabel(String labelName, Resource res, int activeNMs) { + this.labelName = labelName; + this.resource = res; + this.numActiveNMs = activeNMs; + } + + public void addNode(Resource nodeRes) { + Resources.addTo(resource, nodeRes); + numActiveNMs++; + } + + public void removeNode(Resource nodeRes) { + Resources.subtractFrom(resource, nodeRes); + numActiveNMs--; + } + + public Resource getResource() { + return this.resource; + } + + public int getNumActiveNMs() { + return numActiveNMs; + } + + public String getLabelName() { + return labelName; + } + + public NodeLabel getCopy() { + return new NodeLabel(labelName, resource, numActiveNMs); + } + + @Override + public int compareTo(NodeLabel o) { + // We should always put empty label entry first after sorting + if (labelName.isEmpty() != o.getLabelName().isEmpty()) { + if (labelName.isEmpty()) { + return -1; + } + return 1; + } + + return labelName.compareTo(o.getLabelName()); + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof NodeLabel) { + NodeLabel other = (NodeLabel) obj; + return Resources.equals(resource, other.getResource()) + && StringUtils.equals(labelName, other.getLabelName()) + && (other.getNumActiveNMs() == numActiveNMs); + } + return false; + } + + @Override + public int hashCode() { + final int prime = 502357; + return (int) ((((long) labelName.hashCode() << 8) + + (resource.hashCode() << 4) + numActiveNMs) % prime); + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java index 91d2a2019ab8f..62c3c7a0ef3d0 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/YarnWebParams.java @@ -32,4 +32,5 @@ public interface YarnWebParams { String APP_STATE = "app.state"; String QUEUE_NAME = "queue.name"; String NODE_STATE = "node.state"; + String NODE_LABEL = "node.label"; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java index 646441a10f78f..828d1bc34dac3 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java @@ -19,10 +19,12 @@ package org.apache.hadoop.yarn.server.resourcemanager.nodelabels; import java.io.IOException; +import java.util.ArrayList; 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.Map.Entry; import java.util.Set; @@ -37,6 +39,7 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.nodelabels.NodeLabel; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeLabelsUpdateSchedulerEvent; import org.apache.hadoop.yarn.util.resource.Resources; @@ -360,8 +363,8 @@ private void updateResourceMappings(Map<String, Host> before, // no label in the past if (oldLabels.isEmpty()) { // update labels - Label label = labelCollections.get(NO_LABEL); - Resources.subtractFrom(label.getResource(), oldNM.resource); + NodeLabel label = labelCollections.get(NO_LABEL); + label.removeNode(oldNM.resource); // update queues, all queue can access this node for (Queue q : queueCollections.values()) { @@ -370,11 +373,11 @@ private void updateResourceMappings(Map<String, Host> before, } else { // update labels for (String labelName : oldLabels) { - Label label = labelCollections.get(labelName); + NodeLabel label = labelCollections.get(labelName); if (null == label) { continue; } - Resources.subtractFrom(label.getResource(), oldNM.resource); + label.removeNode(oldNM.resource); } // update queues, only queue can access this node will be subtract @@ -395,8 +398,8 @@ private void updateResourceMappings(Map<String, Host> before, // no label in the past if (newLabels.isEmpty()) { // update labels - Label label = labelCollections.get(NO_LABEL); - Resources.addTo(label.getResource(), newNM.resource); + NodeLabel label = labelCollections.get(NO_LABEL); + label.addNode(newNM.resource); // update queues, all queue can access this node for (Queue q : queueCollections.values()) { @@ -405,8 +408,8 @@ private void updateResourceMappings(Map<String, Host> before, } else { // update labels for (String labelName : newLabels) { - Label label = labelCollections.get(labelName); - Resources.addTo(label.getResource(), newNM.resource); + NodeLabel label = labelCollections.get(labelName); + label.addNode(newNM.resource); } // update queues, only queue can access this node will be subtract @@ -475,4 +478,21 @@ public boolean checkAccess(UserGroupInformation user) { public void setRMContext(RMContext rmContext) { this.rmContext = rmContext; } + + public List<NodeLabel> pullRMNodeLabelsInfo() { + try { + readLock.lock(); + List<NodeLabel> infos = new ArrayList<NodeLabel>(); + + for (Entry<String, NodeLabel> entry : labelCollections.entrySet()) { + NodeLabel label = entry.getValue(); + infos.add(label.getCopy()); + } + + Collections.sort(infos); + return infos; + } finally { + readLock.unlock(); + } + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java index ce8fd9e2263ce..db00bb04921b1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NavBlock.java @@ -33,7 +33,8 @@ public class NavBlock extends HtmlBlock { h3("Cluster"). ul(). li().a(url("cluster"), "About")._(). - li().a(url("nodes"), "Nodes")._(); + li().a(url("nodes"), "Nodes")._(). + li().a(url("nodelabels"), "Node Labels")._(); UL<LI<UL<DIV<Hamlet>>>> subAppsList = mainList. li().a(url("apps"), "Applications"). ul(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodeLabelsPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodeLabelsPage.java new file mode 100644 index 0000000000000..5e8c1ed5bf2ec --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodeLabelsPage.java @@ -0,0 +1,91 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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.apache.hadoop.yarn.server.resourcemanager.webapp; + +import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID; + +import org.apache.hadoop.yarn.nodelabels.NodeLabel; +import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; +import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; +import org.apache.hadoop.yarn.webapp.SubView; +import org.apache.hadoop.yarn.webapp.YarnWebParams; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TABLE; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TBODY; +import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TR; +import org.apache.hadoop.yarn.webapp.view.HtmlBlock; + +import com.google.inject.Inject; + +public class NodeLabelsPage extends RmView { + static class NodeLabelsBlock extends HtmlBlock { + final ResourceManager rm; + + @Inject + NodeLabelsBlock(ResourceManager rm, ViewContext ctx) { + super(ctx); + this.rm = rm; + } + + @Override + protected void render(Block html) { + TBODY<TABLE<Hamlet>> tbody = html.table("#nodelabels"). + thead(). + tr(). + th(".name", "Label Name"). + th(".numOfActiveNMs", "Num Of Active NMs"). + th(".totalResource", "Total Resource"). + _()._(). + tbody(); + + RMNodeLabelsManager nlm = rm.getRMContext().getNodeLabelManager(); + for (NodeLabel info : nlm.pullRMNodeLabelsInfo()) { + TR<TBODY<TABLE<Hamlet>>> row = + tbody.tr().td( + info.getLabelName().isEmpty() ? "<NO_LABEL>" : info + .getLabelName()); + int nActiveNMs = info.getNumActiveNMs(); + if (nActiveNMs > 0) { + row = row.td() + .a(url("nodes", + "?" + YarnWebParams.NODE_LABEL + "=" + info.getLabelName()), + String.valueOf(nActiveNMs)) + ._(); + } else { + row = row.td(String.valueOf(nActiveNMs)); + } + row.td(info.getResource().toString())._(); + } + tbody._()._(); + } + } + + @Override protected void preHead(Page.HTML<_> html) { + commonPreHead(html); + String title = "Node labels of the cluster"; + setTitle(title); + set(DATATABLES_ID, "nodelabels"); + setTableStyles(html, "nodelabels", ".healthStatus {width:10em}", + ".healthReport {width:10em}"); + } + + @Override protected Class<? extends SubView> content() { + return NodeLabelsBlock.class; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java index d3849ae5fc495..f28a9a88bc3be 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/NodesPage.java @@ -1,24 +1,25 @@ /** -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you 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 -* -* http://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. -*/ + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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.apache.hadoop.yarn.server.resourcemanager.webapp; -import static org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebApp.NODE_STATE; +import static org.apache.hadoop.yarn.webapp.YarnWebParams.NODE_STATE; +import static org.apache.hadoop.yarn.webapp.YarnWebParams.NODE_LABEL; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID; import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initID; @@ -28,7 +29,9 @@ import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.yarn.api.records.NodeState; +import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; +import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeInfo; @@ -60,26 +63,20 @@ protected void render(Block html) { ResourceScheduler sched = rm.getResourceScheduler(); String type = $(NODE_STATE); - TBODY<TABLE<Hamlet>> tbody = html.table("#nodes"). - thead(). - tr(). - th(".nodelabels", "Node Labels"). - th(".rack", "Rack"). - th(".state", "Node State"). - th(".nodeaddress", "Node Address"). - th(".nodehttpaddress", "Node HTTP Address"). - th(".lastHealthUpdate", "Last health-update"). - th(".healthReport", "Health-report"). - th(".containers", "Containers"). - th(".mem", "Mem Used"). - th(".mem", "Mem Avail"). - th(".vcores", "VCores Used"). - th(".vcores", "VCores Avail"). - th(".nodeManagerVersion", "Version"). - _()._(). - tbody(); + String labelFilter = $(NODE_LABEL, CommonNodeLabelsManager.ANY).trim(); + TBODY<TABLE<Hamlet>> tbody = + html.table("#nodes").thead().tr().th(".nodelabels", "Node Labels") + .th(".rack", "Rack").th(".state", "Node State") + .th(".nodeaddress", "Node Address") + .th(".nodehttpaddress", "Node HTTP Address") + .th(".lastHealthUpdate", "Last health-update") + .th(".healthReport", "Health-report") + .th(".containers", "Containers").th(".mem", "Mem Used") + .th(".mem", "Mem Avail").th(".vcores", "VCores Used") + .th(".vcores", "VCores Avail") + .th(".nodeManagerVersion", "Version")._()._().tbody(); NodeState stateFilter = null; - if(type != null && !type.isEmpty()) { + if (type != null && !type.isEmpty()) { stateFilter = NodeState.valueOf(type.toUpperCase()); } Collection<RMNode> rmNodes = this.rm.getRMContext().getRMNodes().values(); @@ -97,9 +94,9 @@ protected void render(Block html) { } } for (RMNode ni : rmNodes) { - if(stateFilter != null) { + if (stateFilter != null) { NodeState state = ni.getState(); - if(!stateFilter.equals(state)) { + if (!stateFilter.equals(state)) { continue; } } else { @@ -109,61 +106,71 @@ protected void render(Block html) { continue; } } + // Besides state, we need to filter label as well. + if (!labelFilter.equals(RMNodeLabelsManager.ANY)) { + if (labelFilter.isEmpty()) { + // Empty label filter means only shows nodes without label + if (!ni.getNodeLabels().isEmpty()) { + continue; + } + } else if (!ni.getNodeLabels().contains(labelFilter)) { + // Only nodes have given label can show on web page. + continue; + } + } NodeInfo info = new NodeInfo(ni, sched); - int usedMemory = (int)info.getUsedMemory(); - int availableMemory = (int)info.getAvailableMemory(); - TR<TBODY<TABLE<Hamlet>>> row = tbody.tr(). - td(StringUtils.join(",", info.getNodeLabels())). - td(info.getRack()). - td(info.getState()). - td(info.getNodeId()); + int usedMemory = (int) info.getUsedMemory(); + int availableMemory = (int) info.getAvailableMemory(); + TR<TBODY<TABLE<Hamlet>>> row = + tbody.tr().td(StringUtils.join(",", info.getNodeLabels())) + .td(info.getRack()).td(info.getState()).td(info.getNodeId()); if (isInactive) { row.td()._("N/A")._(); } else { String httpAddress = info.getNodeHTTPAddress(); - row.td().a("//" + httpAddress, - httpAddress)._(); + row.td().a("//" + httpAddress, httpAddress)._(); } - row.td().br().$title(String.valueOf(info.getLastHealthUpdate()))._(). - _(Times.format(info.getLastHealthUpdate()))._(). - td(info.getHealthReport()). - td(String.valueOf(info.getNumContainers())). - td().br().$title(String.valueOf(usedMemory))._(). - _(StringUtils.byteDesc(usedMemory * BYTES_IN_MB))._(). - td().br().$title(String.valueOf(availableMemory))._(). - _(StringUtils.byteDesc(availableMemory * BYTES_IN_MB))._(). - td(String.valueOf(info.getUsedVirtualCores())). - td(String.valueOf(info.getAvailableVirtualCores())). - td(ni.getNodeManagerVersion()). - _(); + row.td().br().$title(String.valueOf(info.getLastHealthUpdate()))._() + ._(Times.format(info.getLastHealthUpdate()))._() + .td(info.getHealthReport()) + .td(String.valueOf(info.getNumContainers())).td().br() + .$title(String.valueOf(usedMemory))._() + ._(StringUtils.byteDesc(usedMemory * BYTES_IN_MB))._().td().br() + .$title(String.valueOf(availableMemory))._() + ._(StringUtils.byteDesc(availableMemory * BYTES_IN_MB))._() + .td(String.valueOf(info.getUsedVirtualCores())) + .td(String.valueOf(info.getAvailableVirtualCores())) + .td(ni.getNodeManagerVersion())._(); } tbody._()._(); } } - @Override protected void preHead(Page.HTML<_> html) { + @Override + protected void preHead(Page.HTML<_> html) { commonPreHead(html); String type = $(NODE_STATE); String title = "Nodes of the cluster"; - if(type != null && !type.isEmpty()) { - title = title+" ("+type+")"; + if (type != null && !type.isEmpty()) { + title = title + " (" + type + ")"; } setTitle(title); set(DATATABLES_ID, "nodes"); set(initID(DATATABLES, "nodes"), nodesTableInit()); setTableStyles(html, "nodes", ".healthStatus {width:10em}", - ".healthReport {width:10em}"); + ".healthReport {width:10em}"); } - @Override protected Class<? extends SubView> content() { + @Override + protected Class<? extends SubView> content() { return NodesBlock.class; } private String nodesTableInit() { StringBuilder b = tableInit().append(", aoColumnDefs: ["); b.append("{'bSearchable': false, 'aTargets': [ 6 ]}"); - b.append(", {'sType': 'title-numeric', 'bSearchable': false, " + - "'aTargets': [ 7, 8 ] }"); + b.append(", {'sType': 'title-numeric', 'bSearchable': false, " + + "'aTargets': [ 7, 8 ] }"); b.append(", {'sType': 'title-numeric', 'aTargets': [ 4 ]}"); b.append("]}"); return b.toString(); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java index 67c73b812737a..c0e68349e4ab5 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebApp.java @@ -61,6 +61,7 @@ public void setup() { route(pajoin("/app", APPLICATION_ID), RmController.class, "app"); route("/scheduler", RmController.class, "scheduler"); route(pajoin("/queue", QUEUE_NAME), RmController.class, "queue"); + route("/nodelabels", RmController.class, "nodelabels"); } @Override diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java index f186bf498b0f0..972432b9882d1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RmController.java @@ -28,7 +28,6 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler; import org.apache.hadoop.yarn.util.StringHelper; import org.apache.hadoop.yarn.webapp.Controller; -import org.apache.hadoop.yarn.webapp.WebAppException; import org.apache.hadoop.yarn.webapp.YarnWebParams; import com.google.inject.Inject; @@ -93,4 +92,9 @@ public void queue() { public void submit() { setTitle("Application Submission Not Allowed"); } + + public void nodelabels() { + setTitle("Node Labels"); + render(NodeLabelsPage.class); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java index 278c151ff668b..2d863d1af5c09 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockNodes.java @@ -30,11 +30,13 @@ import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.factories.RecordFactory; import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; /** @@ -53,7 +55,12 @@ public static List<RMNode> newNodes(int racks, int nodesPerRack, // One unhealthy node per rack. list.add(nodeInfo(i, perNode, NodeState.UNHEALTHY)); } - list.add(newNodeInfo(i, perNode)); + if (j == 0) { + // One node with label + list.add(nodeInfo(i, perNode, NodeState.RUNNING, ImmutableSet.of("x"))); + } else { + list.add(newNodeInfo(i, perNode)); + } } } return list; @@ -100,10 +107,12 @@ private static class MockRMNodeImpl implements RMNode { private String healthReport; private long lastHealthReportTime; private NodeState state; + private Set<String> labels; public MockRMNodeImpl(NodeId nodeId, String nodeAddr, String httpAddress, Resource perNode, String rackName, String healthReport, - long lastHealthReportTime, int cmdPort, String hostName, NodeState state) { + long lastHealthReportTime, int cmdPort, String hostName, NodeState state, + Set<String> labels) { this.nodeId = nodeId; this.nodeAddr = nodeAddr; this.httpAddress = httpAddress; @@ -114,6 +123,7 @@ public MockRMNodeImpl(NodeId nodeId, String nodeAddr, String httpAddress, this.cmdPort = cmdPort; this.hostName = hostName; this.state = state; + this.labels = labels; } @Override @@ -207,16 +217,33 @@ public long getLastHealthReportTime() { @Override public Set<String> getNodeLabels() { - return RMNodeLabelsManager.EMPTY_STRING_SET; + if (labels != null) { + return labels; + } + return CommonNodeLabelsManager.EMPTY_STRING_SET; } }; - private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr) { - return buildRMNode(rack, perNode, state, httpAddr, NODE_ID++, null, 123); + private static RMNode buildRMNode(int rack, final Resource perNode, + NodeState state, String httpAddr) { + return buildRMNode(rack, perNode, state, httpAddr, null); } - + + private static RMNode buildRMNode(int rack, final Resource perNode, + NodeState state, String httpAddr, Set<String> labels) { + return buildRMNode(rack, perNode, state, httpAddr, NODE_ID++, null, 123, + labels); + } + private static RMNode buildRMNode(int rack, final Resource perNode, NodeState state, String httpAddr, int hostnum, String hostName, int port) { + return buildRMNode(rack, perNode, state, httpAddr, hostnum, hostName, port, + null); + } + + private static RMNode buildRMNode(int rack, final Resource perNode, + NodeState state, String httpAddr, int hostnum, String hostName, int port, + Set<String> labels) { final String rackName = "rack"+ rack; final int nid = hostnum; final String nodeAddr = hostName + ":" + nid; @@ -228,13 +255,18 @@ private static RMNode buildRMNode(int rack, final Resource perNode, final String httpAddress = httpAddr; String healthReport = (state == NodeState.UNHEALTHY) ? null : "HealthyMe"; return new MockRMNodeImpl(nodeID, nodeAddr, httpAddress, perNode, - rackName, healthReport, 0, nid, hostName, state); + rackName, healthReport, 0, nid, hostName, state, labels); } public static RMNode nodeInfo(int rack, final Resource perNode, NodeState state) { return buildRMNode(rack, perNode, state, "N/A"); } + + public static RMNode nodeInfo(int rack, final Resource perNode, + NodeState state, Set<String> labels) { + return buildRMNode(rack, perNode, state, "N/A", labels); + } public static RMNode newNodeInfo(int rack, final Resource perNode) { return buildRMNode(rack, perNode, NodeState.RUNNING, "localhost:0"); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java index 842eaecad3202..e21fcf9d6ab5d 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestWorkPreservingRMRestart.java @@ -839,7 +839,7 @@ public void testRecoverSchedulerAppAndAttemptSynchronously() throws Exception { // Test if RM on recovery receives the container release request from AM // before it receives the container status reported by NM for recovery. this // container should not be recovered. - @Test (timeout = 30000) + @Test (timeout = 50000) public void testReleasedContainerNotRecovered() throws Exception { MemoryRMStateStore memStore = new MemoryRMStateStore(); memStore.init(conf); diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java index ed675f3736324..e4cdc71c781fb 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/TestRMNodeLabelsManager.java @@ -20,6 +20,7 @@ import java.io.IOException; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; @@ -27,6 +28,7 @@ import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; +import org.apache.hadoop.yarn.nodelabels.NodeLabel; import org.apache.hadoop.yarn.nodelabels.NodeLabelTestBase; import org.apache.hadoop.yarn.util.resource.Resources; import org.junit.After; @@ -428,4 +430,35 @@ public void testRemoveLabelsFromNode() throws Exception { Assert.fail("IOException from removeLabelsFromNode " + e); } } + + private void checkNodeLabelInfo(List<NodeLabel> infos, String labelName, int activeNMs, int memory) { + for (NodeLabel info : infos) { + if (info.getLabelName().equals(labelName)) { + Assert.assertEquals(activeNMs, info.getNumActiveNMs()); + Assert.assertEquals(memory, info.getResource().getMemory()); + return; + } + } + Assert.fail("Failed to find info has label=" + labelName); + } + + @Test(timeout = 5000) + public void testPullRMNodeLabelsInfo() throws IOException { + mgr.addToCluserNodeLabels(toSet("x", "y", "z")); + mgr.activateNode(NodeId.newInstance("n1", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance("n2", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance("n3", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance("n4", 1), Resource.newInstance(10, 0)); + mgr.activateNode(NodeId.newInstance("n5", 1), Resource.newInstance(10, 0)); + mgr.replaceLabelsOnNode(ImmutableMap.of(toNodeId("n1"), toSet("x"), + toNodeId("n2"), toSet("x"), toNodeId("n3"), toSet("y"))); + + // x, y, z and "" + List<NodeLabel> infos = mgr.pullRMNodeLabelsInfo(); + Assert.assertEquals(4, infos.size()); + checkNodeLabelInfo(infos, RMNodeLabelsManager.NO_LABEL, 2, 20); + checkNodeLabelInfo(infos, "x", 2, 20); + checkNodeLabelInfo(infos, "y", 1, 10); + checkNodeLabelInfo(infos, "z", 0, 0); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java index bb38079ccea50..62713cfc7c183 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestNodesPage.java @@ -106,4 +106,49 @@ public void testNodesBlockRenderForLostNodes() { * numberOfActualTableHeaders + numberOfThInMetricsTable)).print( "<td"); } + + @Test + public void testNodesBlockRenderForNodeLabelFilterWithNonEmptyLabel() { + NodesBlock nodesBlock = injector.getInstance(NodesBlock.class); + nodesBlock.set("node.label", "x"); + nodesBlock.render(); + PrintWriter writer = injector.getInstance(PrintWriter.class); + WebAppTests.flushOutput(injector); + + Mockito.verify( + writer, + Mockito.times(numberOfRacks + * numberOfActualTableHeaders + numberOfThInMetricsTable)).print( + "<td"); + } + + @Test + public void testNodesBlockRenderForNodeLabelFilterWithEmptyLabel() { + NodesBlock nodesBlock = injector.getInstance(NodesBlock.class); + nodesBlock.set("node.label", ""); + nodesBlock.render(); + PrintWriter writer = injector.getInstance(PrintWriter.class); + WebAppTests.flushOutput(injector); + + Mockito.verify( + writer, + Mockito.times(numberOfRacks * (numberOfNodesPerRack - 1) + * numberOfActualTableHeaders + numberOfThInMetricsTable)).print( + "<td"); + } + + @Test + public void testNodesBlockRenderForNodeLabelFilterWithAnyLabel() { + NodesBlock nodesBlock = injector.getInstance(NodesBlock.class); + nodesBlock.set("node.label", "*"); + nodesBlock.render(); + PrintWriter writer = injector.getInstance(PrintWriter.class); + WebAppTests.flushOutput(injector); + + Mockito.verify( + writer, + Mockito.times(numberOfRacks * numberOfNodesPerRack + * numberOfActualTableHeaders + numberOfThInMetricsTable)).print( + "<td"); + } }
e4e017feb91f71d0ad3f247c2ec55641ea3fd3d4
robotframework$swinglibrary
Added waiting in order to avoid instability issues. Issue 126.
p
https://github.com/MarketSquare/SwingLibrary
diff --git a/core/src/main/java/org/robotframework/swing/combobox/ComboBoxOperator.java b/core/src/main/java/org/robotframework/swing/combobox/ComboBoxOperator.java index 69e14fde..37b49a2d 100644 --- a/core/src/main/java/org/robotframework/swing/combobox/ComboBoxOperator.java +++ b/core/src/main/java/org/robotframework/swing/combobox/ComboBoxOperator.java @@ -2,6 +2,7 @@ import java.awt.Component; +import org.netbeans.jemmy.EventTool; import org.netbeans.jemmy.operators.JComboBoxOperator; import org.robotframework.swing.common.IdentifierSupport; import org.robotframework.swing.operator.ComponentWrapper; @@ -27,7 +28,8 @@ public Component getSource() { public void selectItem(String comboItemIdentifier) { comboboxOperator.pushComboButton(); - comboboxOperator.selectItem(findItemIndex(comboItemIdentifier)); + int itemIndex = findItemIndex(comboItemIdentifier); + comboboxOperator.selectItem(itemIndex); } public Object getSelectedItem() { @@ -51,13 +53,30 @@ private int findItemIndex(String comboItemIdentifier) { } } - public int findItemIndexFromRenderedText(String expectedText) { + private int findItemIndexFromRenderedText(String expectedText) { + try { + return findItemIndexWithRenderer(expectedText); + } finally { + hidePopup(); + } + + } + + private int findItemIndexWithRenderer(String expectedText) { for (int itemIndex = 0; itemIndex < itemTextExtractor.itemCount(); itemIndex++) { String text = itemTextExtractor.getTextFromRenderedComponent(itemIndex); if (expectedText.equals(text)) return itemIndex; } - comboboxOperator.hidePopup(); throw new RuntimeException("Couldn't find text '" + expectedText + "'"); } + + private void hidePopup() { + comboboxOperator.hidePopup(); + waitToAvoidInstability(); + } + + private void waitToAvoidInstability() { + new EventTool().waitNoEvent(200); + } }
8e9ab4143d260585d73890c6d691b18f865bd2a8
intellij-community
disable pattern configuration for the same- named packages (IDEA-151250)--
c
https://github.com/JetBrains/intellij-community
diff --git a/java/execution/impl/src/com/intellij/execution/testframework/AbstractPatternBasedConfigurationProducer.java b/java/execution/impl/src/com/intellij/execution/testframework/AbstractPatternBasedConfigurationProducer.java index 96b38a73ed650..019e96608ce0d 100644 --- a/java/execution/impl/src/com/intellij/execution/testframework/AbstractPatternBasedConfigurationProducer.java +++ b/java/execution/impl/src/com/intellij/execution/testframework/AbstractPatternBasedConfigurationProducer.java @@ -218,7 +218,7 @@ private boolean collectTestMembers(PsiElement[] elements, for (PsiElement psiClass : processor.getCollection()) { classes.add(getQName(psiClass)); } - return true; + return classes.size() > 1; } private static PsiElement[] collectLocationElements(LinkedHashSet<String> classes, DataContext dataContext) {
591f5202c621bbfedc351dff81437dcedf4b2827
intellij-community
resolve and completion for Django settings- (PY-563)--
c
https://github.com/JetBrains/intellij-community
diff --git a/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java b/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java index 415529dc9fafe..bb6500b4af68a 100644 --- a/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java +++ b/python/src/com/jetbrains/python/codeInsight/PyDynamicMember.java @@ -24,6 +24,7 @@ public class PyDynamicMember { private final String myResolveShortName; private final String myResolveModuleName; + private final PsiElement myTarget; public PyDynamicMember(final String name, final String type, final boolean resolveToInstance) { this(name, type, type, resolveToInstance); @@ -37,6 +38,17 @@ public PyDynamicMember(final String name, final String type, final String resolv int split = resolveTo.lastIndexOf('.'); myResolveShortName = resolveTo.substring(split + 1); myResolveModuleName = resolveTo.substring(0, split); + + myTarget = null; + } + + public PyDynamicMember(final String name, final PsiElement target) { + myName = name; + myTarget = target; + myResolveToInstance = false; + myTypeName = null; + myResolveModuleName = null; + myResolveShortName = null; } public String getName() { @@ -49,6 +61,9 @@ public Icon getIcon() { @Nullable public PsiElement resolve(Project project, PyClass modelClass) { + if (myTarget != null) { + return myTarget; + } PyClass targetClass = PyClassNameIndex.findClass(myTypeName, project); if (targetClass != null) { return new MyInstanceElement(targetClass, findResolveTarget(modelClass)); @@ -71,9 +86,13 @@ private PsiElement findResolveTarget(PyClass clazz) { return module; } + @Nullable public String getShortType() { + if (myTypeName == null) { + return null; + } int pos = myTypeName.lastIndexOf('.'); - return myTypeName.substring(pos+1); + return myTypeName.substring(pos + 1); } private class MyInstanceElement extends PyElementImpl implements PyExpression {
b07d6d56a0d2ace5413bc5b61ad2aa9884294924
kotlin
Escaping keywords used as identifiers in- DescriptorRenderer.-- -KT-2810 fixed-
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java index 852a414388ed2..35b528d27c8ba 100644 --- a/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java +++ b/compiler/frontend/src/org/jetbrains/jet/resolve/DescriptorRenderer.java @@ -16,6 +16,9 @@ package org.jetbrains.jet.resolve; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.intellij.psi.tree.IElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jet.lang.descriptors.*; @@ -23,8 +26,10 @@ import org.jetbrains.jet.lang.resolve.DescriptorUtils; import org.jetbrains.jet.lang.resolve.name.FqName; import org.jetbrains.jet.lang.resolve.name.FqNameUnsafe; +import org.jetbrains.jet.lang.resolve.name.Name; import org.jetbrains.jet.lang.types.*; import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns; +import org.jetbrains.jet.lexer.JetKeywordToken; import org.jetbrains.jet.lexer.JetTokens; import java.util.*; @@ -33,6 +38,14 @@ * @author abreslav */ public class DescriptorRenderer implements Renderer<DeclarationDescriptor> { + private static final Set<String> KEYWORDS = Sets.newHashSet(); + static { + for (IElementType elementType : JetTokens.KEYWORDS.getTypes()) { + assert elementType instanceof JetKeywordToken; + assert !((JetKeywordToken) elementType).isSoft(); + KEYWORDS.add(((JetKeywordToken) elementType).getValue()); + } + } public static final DescriptorRenderer COMPACT_WITH_MODIFIERS = new DescriptorRenderer() { @Override @@ -112,6 +125,28 @@ protected String renderKeyword(String keyword) { return keyword; } + private String renderName(Name identifier) { + String asString = identifier.toString(); + return escape(KEYWORDS.contains(asString) ? '`' + asString + '`' : asString); + } + + @NotNull + private String renderFqName(@NotNull FqNameUnsafe fqName) { + return renderFqName(fqName.pathSegments()); + } + + @NotNull + private String renderFqName(@NotNull List<Name> pathSegments) { + StringBuilder buf = new StringBuilder(); + for (Name element : pathSegments) { + if (buf.length() != 0) { + buf.append("."); + } + buf.append(renderName(element)); + } + return buf.toString(); + } + public String renderType(JetType type) { return renderType(type, false); } @@ -156,25 +191,32 @@ private String renderDefaultType(JetType type, boolean shortNamesOnly) { return sb.toString(); } - private static String renderTypeName(@NotNull TypeConstructor typeConstructor, boolean shortNamesOnly) { + private String renderTypeName(@NotNull TypeConstructor typeConstructor, boolean shortNamesOnly) { ClassifierDescriptor cd = typeConstructor.getDeclarationDescriptor(); - if (cd == null || cd instanceof TypeParameterDescriptor) { + if (cd == null) { return typeConstructor.toString(); } + else if (cd instanceof TypeParameterDescriptor) { + return renderName(cd.getName()); + } else { if (shortNamesOnly) { - Object typeNameObject; + List<Name> qualifiedNameElements = Lists.newArrayList(); + // for nested classes qualified name should be used - typeNameObject = cd.getName(); - DeclarationDescriptor parent = cd.getContainingDeclaration(); - while (parent instanceof ClassDescriptor) { - typeNameObject = parent.getName() + "." + typeNameObject; - parent = parent.getContainingDeclaration(); + DeclarationDescriptor current = cd; + do { + qualifiedNameElements.add(current.getName()); + current = current.getContainingDeclaration(); } - return typeNameObject.toString(); + while (current instanceof ClassDescriptor); + + Collections.reverse(qualifiedNameElements); + + return renderFqName(qualifiedNameElements); } else { - return DescriptorUtils.getFQName(cd).getFqName(); + return renderFqName(DescriptorUtils.getFQName(cd)); } } } @@ -281,7 +323,7 @@ private void appendDefinedIn(DeclarationDescriptor declarationDescriptor, String final DeclarationDescriptor containingDeclaration = declarationDescriptor.getContainingDeclaration(); if (containingDeclaration != null) { FqNameUnsafe fqName = DescriptorUtils.getFQName(containingDeclaration); - stringBuilder.append(FqName.ROOT.equalsTo(fqName) ? "root package" : escape(fqName.getFqName())); + stringBuilder.append(FqName.ROOT.equalsTo(fqName) ? "root package" : renderFqName(fqName)); } } @@ -627,7 +669,7 @@ public void renderClassDescriptor(ClassDescriptor descriptor, StringBuilder buil } protected void renderName(DeclarationDescriptor descriptor, StringBuilder stringBuilder) { - stringBuilder.append(escape(descriptor.getName().getName())); + stringBuilder.append(escape(DescriptorRenderer.this.renderName(descriptor.getName()))); } protected void renderTypeParameter(TypeParameterDescriptor descriptor, StringBuilder builder, boolean topLevel) { diff --git a/compiler/testData/renderer/KeywordsInNames.kt b/compiler/testData/renderer/KeywordsInNames.kt new file mode 100644 index 0000000000000..9f72fd68c8f08 --- /dev/null +++ b/compiler/testData/renderer/KeywordsInNames.kt @@ -0,0 +1,23 @@ +val `val` = 5 + +trait `trait` + +class `class`<`in`>(p: `in`?) { + class `class` +} + +val `is` = `class`.`class`() +val `in` = `class`<`trait`>(null) + +fun `trait`.`fun`(`false`: `trait`): `trait` + +//internal final val `val` : jet.Int defined in root package +//internal trait `trait` defined in root package +//internal final class `class`<`in`> defined in root package +//<`in`> defined in `class` +//value-parameter val p : `in`? defined in `class`.<init> +//internal final class `class` defined in `class` +//internal final val `is` : `class`.`class` defined in root package +//internal final val `in` : `class`<`trait`> defined in root package +//internal final fun `trait`.`fun`(`false` : `trait`) : `trait` defined in root package +//value-parameter val `false` : `trait` defined in `fun` \ No newline at end of file diff --git a/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java b/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java index 8f30906d08e65..26ae420df5961 100644 --- a/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java +++ b/compiler/tests/org/jetbrains/jet/jvm/compiler/LoadJavaTestGenerated.java @@ -15,13 +15,16 @@ */ package org.jetbrains.jet.jvm.compiler; +import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestSuite; + +import java.io.File; import org.jetbrains.jet.JetTestUtils; import org.jetbrains.jet.test.InnerTestClasses; import org.jetbrains.jet.test.TestMetadata; -import java.io.File; +import org.jetbrains.jet.jvm.compiler.AbstractLoadJavaTest; /** This class is generated by {@link org.jetbrains.jet.generators.tests.GenerateTests}. DO NOT MODIFY MANUALLY */ @TestMetadata("compiler/testData/loadJava") diff --git a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveDescriptorRendererTestGenerated.java b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveDescriptorRendererTestGenerated.java index e7e3a46b2b8c2..0bf4581aaaa42 100644 --- a/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveDescriptorRendererTestGenerated.java +++ b/compiler/tests/org/jetbrains/jet/lang/resolve/lazy/LazyResolveDescriptorRendererTestGenerated.java @@ -70,6 +70,11 @@ public void testInheritedMembersVisibility() throws Exception { doTest("compiler/testData/renderer/InheritedMembersVisibility.kt"); } + @TestMetadata("KeywordsInNames.kt") + public void testKeywordsInNames() throws Exception { + doTest("compiler/testData/renderer/KeywordsInNames.kt"); + } + @TestMetadata("TupleTypes.kt") public void testTupleTypes() throws Exception { doTest("compiler/testData/renderer/TupleTypes.kt"); diff --git a/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java b/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java index 10bac3b80658a..ad3c5d5345c84 100644 --- a/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java +++ b/compiler/tests/org/jetbrains/jet/resolve/DescriptorRendererTest.java @@ -80,6 +80,10 @@ public void testInheritedMembersVisibility() throws IOException { doTest(); } + public void testKeywordsInNames() throws IOException { + doTest(); + } + @Override protected String getTestDataPath() { return JetTestCaseBuilder.getTestDataPathBase() + "/renderer";
bf51cd67ad8c2ecbf3f340d840dadcb44c4949b3
tapiji
Fixes marker update problem in Messages editor. Fixes Issue 79.
c
https://github.com/tapiji/tapiji
diff --git a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java index 55ae250d..b2d18e40 100644 --- a/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java +++ b/org.eclipse.babel.core/src/org/eclipse/babel/core/message/manager/RBManager.java @@ -61,6 +61,7 @@ public class RBManager { private static final String TAPIJI_NATURE = "org.eclipse.babel.tapiji.tools.core.nature"; + // TODO: use logger of MessagesEditorPlugin private static Logger logger = Logger.getLogger(RBManager.class .getSimpleName()); diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java index 1e74af96..8801b6ce 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/MessagesEditor.java @@ -12,7 +12,6 @@ ******************************************************************************/ package org.eclipse.babel.editor.internal; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -65,307 +64,322 @@ /** * Multi-page editor for editing resource bundles. */ -public class MessagesEditor extends MultiPageEditorPart - implements IGotoMarker, IMessagesEditor { - - /** Editor ID, as defined in plugin.xml. */ - public static final String EDITOR_ID = - "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$ - - private String selectedKey; - private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>(2); - - /** MessagesBundle group. */ - private MessagesBundleGroup messagesBundleGroup; - - /** Page with key tree and text fields for all locales. */ - private I18NPage i18nPage; - private final List<Locale> localesIndex = new ArrayList<Locale>(); - private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>(); - - private MessagesBundleGroupOutline outline; - - private MessagesEditorMarkers markers; - - - private AbstractKeyTreeModel keyTreeModel; - - private IFile file; // init - - private boolean updateSelectedKey; - - /** - * Creates a multi-page editor example. - */ - public MessagesEditor() { - super(); - outline = new MessagesBundleGroupOutline(this); - } - - public MessagesEditorMarkers getMarkers() { - return markers; - } - - private IPropertyChangeListener preferenceListener; - - /** - * The <code>MultiPageEditorExample</code> implementation of this method - * checks that the input is an instance of <code>IFileEditorInput</code>. - */ - public void init(IEditorSite site, IEditorInput editorInput) - throws PartInitException { - - if (editorInput instanceof IFileEditorInput) { - file = ((IFileEditorInput) editorInput).getFile(); - if (MsgEditorPreferences.getInstance().isBuilderSetupAutomatically()) { - IProject p = file.getProject(); - if (p != null && p.isAccessible()) { - ToggleNatureAction.addOrRemoveNatureOnProject(p, true, true); - } - } - try { - messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup(site, file); - } catch (MessageException e) { - throw new PartInitException( - "Cannot create bundle group.", e); //$NON-NLS-1$ - } - markers = new MessagesEditorMarkers(messagesBundleGroup); - setPartName(messagesBundleGroup.getName()); - setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE)); - closeIfAreadyOpen(site, file); - super.init(site, editorInput); - //TODO figure out model to use based on preferences - keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup); -// markerManager = new RBEMarkerManager(this); - } else { - throw new PartInitException( - "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$ - } - } - -// public RBEMarkerManager getMarkerManager() { -// return markerManager; -// } - - /** - * Creates the pages of the multi-page editor. - */ - protected void createPages() { - // Create I18N page - i18nPage = new I18NPage( - getContainer(), SWT.NONE, this); - int index = addPage(i18nPage); - setPageText(index, MessagesEditorPlugin.getString( - "editor.properties")); //$NON-NLS-1$ - setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE)); - - // Create text editor pages for each locales - try { - Locale[] locales = messagesBundleGroup.getLocales(); - //first: sort the locales. - UIUtils.sortLocales(locales); - //second: filter+sort them according to the filter preferences. - locales = UIUtils.filterLocales(locales); - for (int i = 0; i < locales.length; i++) { - Locale locale = locales[i]; - MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup.getMessagesBundle(locale); - IMessagesResource resource = messagesBundle.getResource(); - TextEditor textEditor = (TextEditor) resource.getSource(); - index = addPage(textEditor, textEditor.getEditorInput()); - setPageText(index, UIUtils.getDisplayName( - messagesBundle.getLocale())); - setPageImage(index, - UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE)); - localesIndex.add(locale); - textEditorsIndex.add(textEditor); - } - } catch (PartInitException e) { - ErrorDialog.openError(getSite().getShell(), - "Error creating text editor page.", //$NON-NLS-1$ - null, e.getStatus()); - } - } - - /** - * Called when the editor's pages need to be reloaded. - * For example when the filters of locale is changed. - * <p> - * Currently this only reloads the index page. - * TODO: remove and add the new locales? it actually looks quite hard to do. - * </p> - */ - public void reloadDisplayedContents() { - super.removePage(0); - int currentlyActivePage = super.getActivePage(); - i18nPage.dispose(); - i18nPage = new I18NPage( - getContainer(), SWT.NONE, this); - super.addPage(0, i18nPage); - if (currentlyActivePage == 0) { - super.setActivePage(currentlyActivePage); - } - } - - /** - * Saves the multi-page editor's document. - */ - public void doSave(IProgressMonitor monitor) { - for (ITextEditor textEditor : textEditorsIndex) { - textEditor.doSave(monitor); - } - - try { // [alst] remove in near future +public class MessagesEditor extends MultiPageEditorPart implements IGotoMarker, + IMessagesEditor { + + /** Editor ID, as defined in plugin.xml. */ + public static final String EDITOR_ID = "org.eclilpse.babel.editor.editor.MessagesEditor"; //$NON-NLS-1$ + + private String selectedKey; + private List<IMessagesEditorChangeListener> changeListeners = new ArrayList<IMessagesEditorChangeListener>( + 2); + + /** MessagesBundle group. */ + private MessagesBundleGroup messagesBundleGroup; + + /** Page with key tree and text fields for all locales. */ + private I18NPage i18nPage; + private final List<Locale> localesIndex = new ArrayList<Locale>(); + private final List<ITextEditor> textEditorsIndex = new ArrayList<ITextEditor>(); + + private MessagesBundleGroupOutline outline; + + private MessagesEditorMarkers markers; + + private AbstractKeyTreeModel keyTreeModel; + + private IFile file; // init + + private boolean updateSelectedKey; + + /** + * Creates a multi-page editor example. + */ + public MessagesEditor() { + super(); + outline = new MessagesBundleGroupOutline(this); + } + + public MessagesEditorMarkers getMarkers() { + return markers; + } + + private IPropertyChangeListener preferenceListener; + + /** + * The <code>MultiPageEditorExample</code> implementation of this method + * checks that the input is an instance of <code>IFileEditorInput</code>. + */ + @Override + public void init(IEditorSite site, IEditorInput editorInput) + throws PartInitException { + + if (editorInput instanceof IFileEditorInput) { + file = ((IFileEditorInput) editorInput).getFile(); + if (MsgEditorPreferences.getInstance() + .isBuilderSetupAutomatically()) { + IProject p = file.getProject(); + if (p != null && p.isAccessible()) { + ToggleNatureAction + .addOrRemoveNatureOnProject(p, true, true); + } + } + try { + messagesBundleGroup = MessagesBundleGroupFactory + .createBundleGroup(site, file); + } catch (MessageException e) { + throw new PartInitException("Cannot create bundle group.", e); //$NON-NLS-1$ + } + markers = new MessagesEditorMarkers(messagesBundleGroup); + setPartName(messagesBundleGroup.getName()); + setTitleImage(UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE)); + closeIfAreadyOpen(site, file); + super.init(site, editorInput); + // TODO figure out model to use based on preferences + keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup); + // markerManager = new RBEMarkerManager(this); + } else { + throw new PartInitException( + "Invalid Input: Must be IFileEditorInput"); //$NON-NLS-1$ + } + } + + // public RBEMarkerManager getMarkerManager() { + // return markerManager; + // } + + /** + * Creates the pages of the multi-page editor. + */ + @Override + protected void createPages() { + // Create I18N page + i18nPage = new I18NPage(getContainer(), SWT.NONE, this); + int index = addPage(i18nPage); + setPageText(index, MessagesEditorPlugin.getString("editor.properties")); //$NON-NLS-1$ + setPageImage(index, UIUtils.getImage(UIUtils.IMAGE_RESOURCE_BUNDLE)); + + // Create text editor pages for each locales + try { + Locale[] locales = messagesBundleGroup.getLocales(); + // first: sort the locales. + UIUtils.sortLocales(locales); + // second: filter+sort them according to the filter preferences. + locales = UIUtils.filterLocales(locales); + for (int i = 0; i < locales.length; i++) { + Locale locale = locales[i]; + MessagesBundle messagesBundle = (MessagesBundle) messagesBundleGroup + .getMessagesBundle(locale); + IMessagesResource resource = messagesBundle.getResource(); + TextEditor textEditor = (TextEditor) resource.getSource(); + index = addPage(textEditor, textEditor.getEditorInput()); + setPageText(index, + UIUtils.getDisplayName(messagesBundle.getLocale())); + setPageImage(index, + UIUtils.getImage(UIUtils.IMAGE_PROPERTIES_FILE)); + localesIndex.add(locale); + textEditorsIndex.add(textEditor); + } + } catch (PartInitException e) { + ErrorDialog.openError(getSite().getShell(), + "Error creating text editor page.", //$NON-NLS-1$ + null, e.getStatus()); + } + } + + /** + * Called when the editor's pages need to be reloaded. For example when the + * filters of locale is changed. + * <p> + * Currently this only reloads the index page. TODO: remove and add the new + * locales? it actually looks quite hard to do. + * </p> + */ + public void reloadDisplayedContents() { + super.removePage(0); + int currentlyActivePage = super.getActivePage(); + i18nPage.dispose(); + i18nPage = new I18NPage(getContainer(), SWT.NONE, this); + super.addPage(0, i18nPage); + if (currentlyActivePage == 0) { + super.setActivePage(currentlyActivePage); + } + } + + /** + * Saves the multi-page editor's document. + */ + @Override + public void doSave(IProgressMonitor monitor) { + for (ITextEditor textEditor : textEditorsIndex) { + textEditor.doSave(monitor); + } + + try { // [alst] remove in near future Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } - + updateSelectedKey = true; - - RBManager instance = RBManager.getInstance(messagesBundleGroup.getProjectName()); - + + RBManager instance = RBManager.getInstance(messagesBundleGroup + .getProjectName()); + refreshKeyTreeModel(); // keeps editor and I18NPage in sync - + instance.fireEditorSaved(); - -// // maybe new init? - } - - private void refreshKeyTreeModel() { - String selectedKey = getSelectedKey(); // memorize - - messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup((IEditorSite)getSite(), file); - + + // // maybe new init? + } + + private void refreshKeyTreeModel() { + String selectedKey = getSelectedKey(); // memorize + + if (messagesBundleGroup == null) { + messagesBundleGroup = MessagesBundleGroupFactory.createBundleGroup( + (IEditorSite) getSite(), file); + } + AbstractKeyTreeModel oldModel = this.keyTreeModel; this.keyTreeModel = new AbstractKeyTreeModel(messagesBundleGroup); - + for (IMessagesEditorChangeListener listener : changeListeners) { - listener.keyTreeModelChanged(oldModel, this.keyTreeModel); - } - + listener.keyTreeModelChanged(oldModel, this.keyTreeModel); + } + i18nPage.getTreeViewer().expandAll(); - + if (selectedKey != null) { setSelectedKey(selectedKey); } - } - - /** - * @see org.eclipse.ui.ISaveablePart#doSaveAs() - */ - public void doSaveAs() { - // Save As not allowed. - } - - /** - * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed() - */ - public boolean isSaveAsAllowed() { - return false; - } - - /** - * Change current page based on locale. If there is no editors associated - * with current locale, do nothing. - * @param locale locale used to identify the page to change to - */ - public void setActivePage(Locale locale) { - int index = localesIndex.indexOf(locale); - if (index > -1) { - setActivePage(index + 1); - } - } - - /** - * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker( - * org.eclipse.core.resources.IMarker) - */ - public void gotoMarker(IMarker marker) { -// String key = marker.getAttribute(RBEMarker.KEY, ""); -// if (key != null && key.length() > 0) { -// setActivePage(0); -// setSelectedKey(key); -// getI18NPage().selectLocale(BabelUtils.parseLocale( -// marker.getAttribute(RBEMarker.LOCALE, ""))); -// } else { - IResource resource = marker.getResource(); - Locale[] locales = messagesBundleGroup.getLocales(); - for (int i = 0; i < locales.length; i++) { - IMessagesResource messagesResource = - ((MessagesBundle) messagesBundleGroup.getMessagesBundle(locales[i])).getResource(); - if (messagesResource instanceof EclipsePropertiesEditorResource) { - EclipsePropertiesEditorResource propFile = - (EclipsePropertiesEditorResource) messagesResource; - if (resource.equals(propFile.getResource())) { - //ok we got the locale. - //try to open the master i18n page and select the corresponding key. - try { - String key = (String) marker.getAttribute(IMarker.LOCATION); - if (key != null && key.length() > 0) { - getI18NPage().selectLocale(locales[i]); - setActivePage(0); - setSelectedKey(key); - return; - } - } catch (Exception e) { - e.printStackTrace();//something better.s - } - //it did not work... fall back to the text editor. - setActivePage(locales[i]); - IDE.gotoMarker( - (IEditorPart) propFile.getSource(), marker); - break; - } - } - } -// } - } - - /** - * Calculates the contents of page GUI page when it is activated. - */ - protected void pageChange(int newPageIndex) { - super.pageChange(newPageIndex); - if (newPageIndex != 0) { // if we just want the default page -> == 1 - setSelection(newPageIndex); - } else if (newPageIndex == 0 && updateSelectedKey) { - // TODO: find better way - for (IMessagesBundle bundle : messagesBundleGroup.getMessagesBundles()) { - RBManager.getInstance(messagesBundleGroup.getProjectName()).fireResourceChanged(bundle); - } - updateSelectedKey = false; - } - -// if (newPageIndex == 0) { -// resourceMediator.reloadProperties(); -// i18nPage.refreshTextBoxes(); -// } - } - - private void setSelection(int newPageIndex) { - ITextEditor editor = textEditorsIndex.get(--newPageIndex); - String selectedKey = getSelectedKey(); - if (selectedKey != null) { - if (editor.getEditorInput() instanceof FileEditorInput) { - FileEditorInput input = (FileEditorInput) editor.getEditorInput(); - try { - BufferedReader reader = new BufferedReader(new InputStreamReader(input.getFile().getContents())); + } + + /** + * @see org.eclipse.ui.ISaveablePart#doSaveAs() + */ + @Override + public void doSaveAs() { + // Save As not allowed. + } + + /** + * @see org.eclipse.ui.ISaveablePart#isSaveAsAllowed() + */ + @Override + public boolean isSaveAsAllowed() { + return false; + } + + /** + * Change current page based on locale. If there is no editors associated + * with current locale, do nothing. + * + * @param locale + * locale used to identify the page to change to + */ + public void setActivePage(Locale locale) { + int index = localesIndex.indexOf(locale); + if (index > -1) { + setActivePage(index + 1); + } + } + + /** + * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(org.eclipse.core.resources.IMarker) + */ + public void gotoMarker(IMarker marker) { + // String key = marker.getAttribute(RBEMarker.KEY, ""); + // if (key != null && key.length() > 0) { + // setActivePage(0); + // setSelectedKey(key); + // getI18NPage().selectLocale(BabelUtils.parseLocale( + // marker.getAttribute(RBEMarker.LOCALE, ""))); + // } else { + IResource resource = marker.getResource(); + Locale[] locales = messagesBundleGroup.getLocales(); + for (int i = 0; i < locales.length; i++) { + IMessagesResource messagesResource = ((MessagesBundle) messagesBundleGroup + .getMessagesBundle(locales[i])).getResource(); + if (messagesResource instanceof EclipsePropertiesEditorResource) { + EclipsePropertiesEditorResource propFile = (EclipsePropertiesEditorResource) messagesResource; + if (resource.equals(propFile.getResource())) { + // ok we got the locale. + // try to open the master i18n page and select the + // corresponding key. + try { + String key = (String) marker + .getAttribute(IMarker.LOCATION); + if (key != null && key.length() > 0) { + getI18NPage().selectLocale(locales[i]); + setActivePage(0); + setSelectedKey(key); + return; + } + } catch (Exception e) { + e.printStackTrace();// something better.s + } + // it did not work... fall back to the text editor. + setActivePage(locales[i]); + IDE.gotoMarker((IEditorPart) propFile.getSource(), marker); + break; + } + } + } + // } + } + + /** + * Calculates the contents of page GUI page when it is activated. + */ + @Override + protected void pageChange(int newPageIndex) { + super.pageChange(newPageIndex); + if (newPageIndex != 0) { // if we just want the default page -> == 1 + setSelection(newPageIndex); + } else if (newPageIndex == 0 && updateSelectedKey) { + // TODO: find better way + for (IMessagesBundle bundle : messagesBundleGroup + .getMessagesBundles()) { + RBManager.getInstance(messagesBundleGroup.getProjectName()) + .fireResourceChanged(bundle); + } + updateSelectedKey = false; + } + + // if (newPageIndex == 0) { + // resourceMediator.reloadProperties(); + // i18nPage.refreshTextBoxes(); + // } + } + + private void setSelection(int newPageIndex) { + ITextEditor editor = textEditorsIndex.get(--newPageIndex); + String selectedKey = getSelectedKey(); + if (selectedKey != null) { + if (editor.getEditorInput() instanceof FileEditorInput) { + FileEditorInput input = (FileEditorInput) editor + .getEditorInput(); + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(input.getFile().getContents())); String line = ""; int selectionIndex = 0; boolean found = false; - + while ((line = reader.readLine()) != null) { int index = line.indexOf('='); if (index != -1) { - if (selectedKey.equals(line.substring(0, index).trim())) { + if (selectedKey.equals(line.substring(0, index) + .trim())) { found = true; break; } } selectionIndex += line.length() + 2; // + \r\n } - + if (found) { editor.selectAndReveal(selectionIndex, 0); } @@ -375,149 +389,157 @@ private void setSelection(int newPageIndex) { // TODO Auto-generated catch block e.printStackTrace(); } - } - } - - } - - - /** - * Is the given file a member of this resource bundle. - * @param file file to test - * @return <code>true</code> if file is part of bundle - */ - public boolean isBundleMember(IFile file) { -// return resourceMediator.isResource(file); - return false; - } - - private void closeIfAreadyOpen(IEditorSite site, IFile file) { - IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages(); - for (int i = 0; i < pages.length; i++) { - IWorkbenchPage page = pages[i]; - IEditorReference[] editors = page.getEditorReferences(); - for (int j = 0; j < editors.length; j++) { - IEditorPart editor = editors[j].getEditor(false); - if (editor instanceof MessagesEditor) { - MessagesEditor rbe = (MessagesEditor) editor; - if (rbe.isBundleMember(file)) { - page.closeEditor(editor, true); - } - } - } - } - } - - - - /** - * @see org.eclipse.ui.IWorkbenchPart#dispose() - */ - public void dispose() { - for (IMessagesEditorChangeListener listener : changeListeners) { - listener.editorDisposed(); - } - i18nPage.dispose(); - for (ITextEditor textEditor : textEditorsIndex) { - textEditor.dispose(); - } - } - - - /** - * @return Returns the selectedKey. - */ - public String getSelectedKey() { - return selectedKey; - } - /** - * @param selectedKey The selectedKey to set. - */ - public void setSelectedKey(String activeKey) { - if ((selectedKey == null && activeKey != null) - || (selectedKey != null && activeKey == null) - || (selectedKey != null && !selectedKey.equals(activeKey))) { - String oldKey = this.selectedKey; - this.selectedKey = activeKey; - for (IMessagesEditorChangeListener listener : changeListeners) { - listener.selectedKeyChanged(oldKey, activeKey); - } - } - } - - public void addChangeListener(IMessagesEditorChangeListener listener) { - changeListeners.add(0, listener); - } - - public void removeChangeListener(IMessagesEditorChangeListener listener) { - changeListeners.remove(listener); - } - - public Collection<IMessagesEditorChangeListener> getChangeListeners() { - return changeListeners; - } - - /** - * @return Returns the messagesBundleGroup. - */ - public MessagesBundleGroup getBundleGroup() { - return messagesBundleGroup; - } - - /** - * @return Returns the keyTreeModel. - */ - public AbstractKeyTreeModel getKeyTreeModel() { - return keyTreeModel; - } - - /** - * @param keyTreeModel The keyTreeModel to set. - */ - public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) { - if ((this.keyTreeModel == null && newKeyTreeModel != null) - || (keyTreeModel != null && newKeyTreeModel == null) - || (!keyTreeModel.equals(newKeyTreeModel))) { - AbstractKeyTreeModel oldModel = this.keyTreeModel; - this.keyTreeModel = newKeyTreeModel; - for (IMessagesEditorChangeListener listener : changeListeners) { - listener.keyTreeModelChanged(oldModel, newKeyTreeModel); - } - } - } - - public I18NPage getI18NPage() { - return i18nPage; - } - - /** one of the SHOW_* constants defined in the {@link IMessagesEditorChangeListener} */ - private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL; - /** - * @return true when only unused and missing keys should be displayed. flase by default. - */ - public int isShowOnlyUnusedAndMissingKeys() { - return showOnlyMissingAndUnusedKeys; - } - - public void setShowOnlyUnusedMissingKeys(int showFlag) { - showOnlyMissingAndUnusedKeys = showFlag; - for (IMessagesEditorChangeListener listener : getChangeListeners()) { - listener.showOnlyUnusedAndMissingChanged(showFlag); - } - } - - public Object getAdapter(Class adapter) { - Object obj = super.getAdapter(adapter); - if (obj == null) { - if (IContentOutlinePage.class.equals(adapter)) { - return (outline); - } - } - return (obj); - } - - public ITextEditor getTextEditor(Locale locale) { - int index = localesIndex.indexOf(locale); - return textEditorsIndex.get(index); - } + } + } + + } + + /** + * Is the given file a member of this resource bundle. + * + * @param file + * file to test + * @return <code>true</code> if file is part of bundle + */ + public boolean isBundleMember(IFile file) { + // return resourceMediator.isResource(file); + return false; + } + + private void closeIfAreadyOpen(IEditorSite site, IFile file) { + IWorkbenchPage[] pages = site.getWorkbenchWindow().getPages(); + for (int i = 0; i < pages.length; i++) { + IWorkbenchPage page = pages[i]; + IEditorReference[] editors = page.getEditorReferences(); + for (int j = 0; j < editors.length; j++) { + IEditorPart editor = editors[j].getEditor(false); + if (editor instanceof MessagesEditor) { + MessagesEditor rbe = (MessagesEditor) editor; + if (rbe.isBundleMember(file)) { + page.closeEditor(editor, true); + } + } + } + } + } + + /** + * @see org.eclipse.ui.IWorkbenchPart#dispose() + */ + @Override + public void dispose() { + for (IMessagesEditorChangeListener listener : changeListeners) { + listener.editorDisposed(); + } + i18nPage.dispose(); + for (ITextEditor textEditor : textEditorsIndex) { + textEditor.dispose(); + } + } + + /** + * @return Returns the selectedKey. + */ + public String getSelectedKey() { + return selectedKey; + } + + /** + * @param selectedKey + * The selectedKey to set. + */ + public void setSelectedKey(String activeKey) { + if ((selectedKey == null && activeKey != null) + || (selectedKey != null && activeKey == null) + || (selectedKey != null && !selectedKey.equals(activeKey))) { + String oldKey = this.selectedKey; + this.selectedKey = activeKey; + for (IMessagesEditorChangeListener listener : changeListeners) { + listener.selectedKeyChanged(oldKey, activeKey); + } + } + } + + public void addChangeListener(IMessagesEditorChangeListener listener) { + changeListeners.add(0, listener); + } + + public void removeChangeListener(IMessagesEditorChangeListener listener) { + changeListeners.remove(listener); + } + + public Collection<IMessagesEditorChangeListener> getChangeListeners() { + return changeListeners; + } + + /** + * @return Returns the messagesBundleGroup. + */ + public MessagesBundleGroup getBundleGroup() { + return messagesBundleGroup; + } + + /** + * @return Returns the keyTreeModel. + */ + public AbstractKeyTreeModel getKeyTreeModel() { + return keyTreeModel; + } + + /** + * @param keyTreeModel + * The keyTreeModel to set. + */ + public void setKeyTreeModel(AbstractKeyTreeModel newKeyTreeModel) { + if ((this.keyTreeModel == null && newKeyTreeModel != null) + || (keyTreeModel != null && newKeyTreeModel == null) + || (!keyTreeModel.equals(newKeyTreeModel))) { + AbstractKeyTreeModel oldModel = this.keyTreeModel; + this.keyTreeModel = newKeyTreeModel; + for (IMessagesEditorChangeListener listener : changeListeners) { + listener.keyTreeModelChanged(oldModel, newKeyTreeModel); + } + } + } + + public I18NPage getI18NPage() { + return i18nPage; + } + + /** + * one of the SHOW_* constants defined in the + * {@link IMessagesEditorChangeListener} + */ + private int showOnlyMissingAndUnusedKeys = IMessagesEditorChangeListener.SHOW_ALL; + + /** + * @return true when only unused and missing keys should be displayed. flase + * by default. + */ + public int isShowOnlyUnusedAndMissingKeys() { + return showOnlyMissingAndUnusedKeys; + } + + public void setShowOnlyUnusedMissingKeys(int showFlag) { + showOnlyMissingAndUnusedKeys = showFlag; + for (IMessagesEditorChangeListener listener : getChangeListeners()) { + listener.showOnlyUnusedAndMissingChanged(showFlag); + } + } + + @Override + public Object getAdapter(Class adapter) { + Object obj = super.getAdapter(adapter); + if (obj == null) { + if (IContentOutlinePage.class.equals(adapter)) { + return (outline); + } + } + return (obj); + } + + public ITextEditor getTextEditor(Locale locale) { + int index = localesIndex.indexOf(locale); + return textEditorsIndex.get(index); + } } diff --git a/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java new file mode 100644 index 00000000..2422e95b --- /dev/null +++ b/org.eclipselabs.tapiji.translator/src/org/eclipselabs/tapiji/translator/views/menus/GlossaryEntryMenuContribution.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright (c) 2012 TapiJI. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Martin Reiterer - initial API and implementation + ******************************************************************************/ +package org.eclipselabs.tapiji.translator.views.menus; + +import org.eclipse.jface.action.ContributionItem; +import org.eclipse.jface.viewers.ISelectionChangedListener; +import org.eclipse.jface.viewers.SelectionChangedEvent; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.widgets.Menu; +import org.eclipse.swt.widgets.MenuItem; +import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.PlatformUI; +import org.eclipselabs.tapiji.translator.views.widgets.GlossaryWidget; + +public class GlossaryEntryMenuContribution extends ContributionItem implements + ISelectionChangedListener { + + private GlossaryWidget parentView; + private boolean legalSelection = false; + + // Menu-Items + private MenuItem addItem; + private MenuItem removeItem; + + public GlossaryEntryMenuContribution() { + } + + public GlossaryEntryMenuContribution(GlossaryWidget view, + boolean legalSelection) { + this.legalSelection = legalSelection; + this.parentView = view; + parentView.addSelectionChangedListener(this); + } + + @Override + public void fill(Menu menu, int index) { + + // MenuItem for adding a new entry + addItem = new MenuItem(menu, SWT.NONE, index); + addItem.setText("Add ..."); + addItem.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage()); + addItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.addNewItem(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + + if ((parentView == null && legalSelection) || parentView != null) { + // MenuItem for deleting the currently selected entry + removeItem = new MenuItem(menu, SWT.NONE, index + 1); + removeItem.setText("Remove"); + removeItem.setImage(PlatformUI.getWorkbench().getSharedImages() + .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE) + .createImage()); + removeItem.addSelectionListener(new SelectionListener() { + + @Override + public void widgetSelected(SelectionEvent e) { + parentView.deleteSelectedItems(); + } + + @Override + public void widgetDefaultSelected(SelectionEvent e) { + + } + }); + enableMenuItems(); + } + } + + protected void enableMenuItems() { + try { + removeItem.setEnabled(legalSelection); + } catch (Exception e) { + } + } + + @Override + public void selectionChanged(SelectionChangedEvent event) { + legalSelection = !event.getSelection().isEmpty(); + // enableMenuItems (); + } + +}
258afc8c809f68bd1b530e115725e0bf511e02ca
Delta Spike
DELTASPIKE-402 make DependentProvider Serializable (if possible)
c
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/DependentProvider.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/DependentProvider.java index a63fe8391..ae76a048b 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/DependentProvider.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/provider/DependentProvider.java @@ -20,7 +20,13 @@ import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.Bean; +import javax.enterprise.inject.spi.PassivationCapable; import javax.inject.Provider; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; /** * A {@link Provider} for &#064;Dependent scoped contextual instances. @@ -28,12 +34,17 @@ * needed anymore via the {@link #destroy()} method. * * Instances of this class can be retrieved using the {@link BeanProvider}. + * + * Instances of this class are Serializable if the wrapped contextual instance + * is Serializable. */ -public class DependentProvider<T> implements Provider<T> +public class DependentProvider<T> implements Provider<T>, Serializable { + private static final long serialVersionUID = 23423413412001L; + private T instance; private CreationalContext<T> creationalContext; - private Bean<T> bean; + private transient Bean<T> bean; DependentProvider(Bean<T> bean, CreationalContext<T> creationalContext, T instance) { @@ -52,4 +63,36 @@ public void destroy() { bean.destroy(instance, creationalContext); } + + private void writeObject(ObjectOutputStream out) throws IOException + { + if (!(bean instanceof PassivationCapable)) + { + throw new NotSerializableException("Bean is not PassivationCapable: " + bean.toString()); + } + String passivationId = ((PassivationCapable) bean).getId(); + if (passivationId == null) + { + throw new NotSerializableException(bean.toString()); + } + + out.writeLong(serialVersionUID); + out.writeObject(passivationId); + out.writeObject(instance); + out.writeObject(creationalContext); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException + { + long oldSerialId = in.readLong(); + if (oldSerialId != serialVersionUID) + { + throw new NotSerializableException(getClass().getName() + " serialVersion does not match"); + } + String passivationId = (String) in.readObject(); + bean = (Bean<T>) BeanManagerProvider.getInstance().getBeanManager().getPassivationCapableBean(passivationId); + instance = (T) in.readObject(); + creationalContext = (CreationalContext<T>) in.readObject(); + } + } diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/MessageContextTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/MessageContextTest.java index c4bde2f09..a0893d0ae 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/MessageContextTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/MessageContextTest.java @@ -28,7 +28,7 @@ import org.apache.deltaspike.core.api.message.MessageContext; import org.apache.deltaspike.core.impl.message.MessageBundleExtension; import org.apache.deltaspike.test.category.SeCategory; -import org.apache.deltaspike.test.category.Serializer; +import org.apache.deltaspike.test.utils.Serializer; import org.apache.deltaspike.test.util.ArchiveUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java index e5dadd8c2..8acc0952c 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/message/SimpleMessageTest.java @@ -21,7 +21,7 @@ import org.apache.deltaspike.core.api.message.LocaleResolver; import org.apache.deltaspike.core.impl.message.MessageBundleExtension; import org.apache.deltaspike.test.category.SeCategory; -import org.apache.deltaspike.test.category.Serializer; +import org.apache.deltaspike.test.utils.Serializer; import org.apache.deltaspike.test.util.ArchiveUtils; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java index abbeb9834..d9c9feba9 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/BeanProviderTest.java @@ -22,6 +22,8 @@ import org.apache.deltaspike.core.api.provider.BeanProvider; import org.apache.deltaspike.core.api.provider.DependentProvider; import org.apache.deltaspike.test.util.ArchiveUtils; +import org.apache.deltaspike.test.utils.CdiContainerUnderTest; +import org.apache.deltaspike.test.utils.Serializer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; @@ -29,6 +31,7 @@ import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; +import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,6 +41,9 @@ @RunWith(Arquillian.class) public class BeanProviderTest { + private static final String CONTAINER_OWB_1_1_x = "owb-1\\.1\\..*"; + + /** *X TODO creating a WebArchive is only a workaround because JavaArchive cannot contain other archives. */ @@ -210,6 +216,19 @@ public void testNamedDependentBeanResolving() throws Exception checkDependentProvider(dependentTestBeanProvider); } + @Test + public void testDependentBeanSerialization() throws Exception + { + // this test is known to not work under owb-1.1.x as ManagedBean for Dependent scoped classes did not implement PassivationCapable. + Assume.assumeTrue(!CdiContainerUnderTest.is(CONTAINER_OWB_1_1_x)); + + DependentProvider<DependentTestBean> dependentTestBeanProvider = BeanProvider.getDependent(DependentTestBean.class); + + Serializer<DependentProvider<DependentTestBean>> serializer = new Serializer<DependentProvider<DependentTestBean>>(); + DependentProvider<DependentTestBean> provider2 = serializer.roundTrip(dependentTestBeanProvider); + Assert.assertNotNull(provider2); + } + private void checkDependentProvider(DependentProvider<DependentTestBean> dependentTestBeanProvider) { Assert.assertNotNull(dependentTestBeanProvider); diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/DependentTestBean.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/DependentTestBean.java index 1bda0b448..b5862e805 100644 --- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/DependentTestBean.java +++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/api/provider/DependentTestBean.java @@ -21,10 +21,11 @@ import javax.annotation.PreDestroy; import javax.enterprise.context.Dependent; import javax.inject.Named; +import java.io.Serializable; @Dependent @Named -public class DependentTestBean +public class DependentTestBean implements Serializable { private int i = 42; private boolean destroyed = false; diff --git a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/category/Serializer.java b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/Serializer.java similarity index 98% rename from deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/category/Serializer.java rename to deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/Serializer.java index bd03e941d..ff0d64580 100644 --- a/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/category/Serializer.java +++ b/deltaspike/test-utils/src/main/java/org/apache/deltaspike/test/utils/Serializer.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.deltaspike.test.category; +package org.apache.deltaspike.test.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream;
b588da4eb4be8419dbffcafccc381b80dec25acb
hadoop
YARN-2269. Remove external links from YARN UI.- Contributed by Craig Welch--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1609591 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 32d88ae61bbbf..55607a612ec34 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -354,6 +354,8 @@ Release 2.5.0 - UNRELEASED YARN-2158. Improved assertion messages of TestRMWebServicesAppsModification. (Varun Vasudev via zjshen) + YARN-2269. Remove External links from YARN UI. (Craig Welch via xgong) + Release 2.4.1 - 2014-06-23 INCOMPATIBLE CHANGES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java index eedf64b276946..ba85ac69d3f60 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/FooterBlock.java @@ -25,7 +25,6 @@ public class FooterBlock extends HtmlBlock { @Override protected void render(Block html) { html. - div("#footer.ui-widget"). - a("http://hadoop.apache.org/", "About Apache Hadoop")._(); + div("#footer.ui-widget")._(); } }
ee812eba6928ff73f60a528377ddf33e8965c84c
tapiji
Cleans up the RCP translators product definition
p
https://github.com/tapiji/tapiji
diff --git a/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product b/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product index 642b63f4..c30539e2 100644 --- a/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product +++ b/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <?pde version="3.5"?> -<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.rcp.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.9.0.B1" useFeatures="false" includeLaunchers="true"> +<product name="TapiJI Translator" uid="org.eclipselabs.tapiji.translator.swt.product" id="org.eclipselabs.tapiji.translator.app" application="org.eclipselabs.tapiji.translator.application" version="0.9.0.B1" useFeatures="false" includeLaunchers="true"> <aboutInfo> <image path="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/> @@ -21,7 +21,6 @@ by Stefan Strobl &amp; Martin Reiterer <windowImages i16="/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png" i32="/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png" i48="/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png" i64="/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png" i128="/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"/> - <launcher> <solaris/> <win useIco="false"> @@ -29,7 +28,6 @@ by Stefan Strobl &amp; Martin Reiterer </win> </launcher> - <vm> </vm> diff --git a/org.eclipselabs.tapiji.translator.swt.product/pom.xml b/org.eclipselabs.tapiji.translator.swt.product/pom.xml index 67d70438..5fa8fc8c 100644 --- a/org.eclipselabs.tapiji.translator.swt.product/pom.xml +++ b/org.eclipselabs.tapiji.translator.swt.product/pom.xml @@ -19,7 +19,7 @@ <relativePath>..</relativePath> </parent> -<!-- <build> + <build> <plugins> <plugin> <groupId>org.eclipse.tycho</groupId> @@ -40,5 +40,5 @@ </plugin> </plugins> </build> - --> + </project> diff --git a/org.eclipselabs.tapiji.translator.swt/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.swt/META-INF/MANIFEST.MF index 3cd34327..e2f65d82 100644 --- a/org.eclipselabs.tapiji.translator.swt/META-INF/MANIFEST.MF +++ b/org.eclipselabs.tapiji.translator.swt/META-INF/MANIFEST.MF @@ -2,6 +2,6 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: RCP fragment for TapiJI Translator Bundle-SymbolicName: org.eclipselabs.tapiji.translator.swt;singleton:=true -Bundle-Version: 0.0.2.qualifier -Fragment-Host: org.eclipselabs.tapiji.translator;bundle-version="0.0.2" +Bundle-Version: 0.9.0.B1 +Fragment-Host: org.eclipselabs.tapiji.translator;bundle-version="0.9.0.B1" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/org.eclipselabs.tapiji.translator.swt/fragment.xml b/org.eclipselabs.tapiji.translator.swt/fragment.xml index d7f1d28d..bfa8380e 100644 --- a/org.eclipselabs.tapiji.translator.swt/fragment.xml +++ b/org.eclipselabs.tapiji.translator.swt/fragment.xml @@ -2,34 +2,6 @@ <?eclipse version="3.4"?> <fragment> - <extension - id="product" - point="org.eclipse.core.runtime.products"> - <product - application="org.eclipse.ant.core.antRunner" - name="TapiJI Translator"> - <property - name="windowImages" - value="platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"> - </property> - <property - name="appName" - value="TapiJI Translator"> - </property> - <property - name="aboutImage" - value="platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png"> - </property> - <property - name="aboutText" - value="TapiJI - Translator &#x0A;Version 1.0.0&#x0A;by Stefan Strobl &amp; Martin Reiterer"> - </property> - <property - name="preferenceCustomization" - value="plugin_customization.ini"> - </property> - </product> - </extension> <extension id="app" point="org.eclipse.core.runtime.products"> diff --git a/org.eclipselabs.tapiji.translator/plugin.xml b/org.eclipselabs.tapiji.translator/plugin.xml index 077db6a4..a70c870f 100644 --- a/org.eclipselabs.tapiji.translator/plugin.xml +++ b/org.eclipselabs.tapiji.translator/plugin.xml @@ -74,54 +74,6 @@ name="aboutImage" value="icons/TapiJI_128.png"> </property> - <property - name="appName" - value="TapiJI Translator"> - </property> - </product> - </extension> - <extension - id="product" - point="org.eclipse.core.runtime.products"> - <product - application="org.eclipselabs.tapiji.translator.application" - name="TapiJI Translator"> - <property - name="windowImages" - value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png"> - </property> - <property - name="aboutText" - value="TapiJI - Translator &#x0A;Version 1.0.0&#x0A;by Stefan Strobl &amp; Martin Reiterer"> - </property> - <property - name="aboutImage" - value="icons/TapiJI_128.png"> - </property> - </product> - </extension> - <extension - id="translator" - point="org.eclipse.core.runtime.products"> - <product - application="org.eclipselabs.tapiji.translator.application" - name="TapiJI Translator"> - <property - name="windowImages" - value="icons/TapiJI_16.png,icons/TapiJI_32.png,icons/TapiJI_48.png,icons/TapiJI_64.png,icons/TapiJI_128.png"> - </property> - <property - name="aboutText" - value="TapiJI - Translator &#x0A;Version 1.0.0&#x0A;by Stefan Strobl &amp; Martin Reiterer"> - </property> - <property - name="aboutImage" - value="icons/TapiJI_128.png"> - </property> - <property - name="appName" - value="TapiJI Translator"> - </property> </product> </extension> </plugin>
dcb491bdc8c5612f7ee5115c81312e8dc4f96709
orientdb
Fixed issue -3741--
c
https://github.com/orientechnologies/orientdb
diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java index c596810c807..874e3818eec 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java +++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/ODistributedStorage.java @@ -52,6 +52,7 @@ import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.clusterselection.OClusterSelectionStrategy; import com.orientechnologies.orient.core.record.ORecord; +import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate; import com.orientechnologies.orient.core.sql.OCommandExecutorSQLSelect; @@ -909,6 +910,14 @@ public Object call() throws Exception { } } + + // RESET DIRTY FLAGS TO AVOID CALLING AUTO-SAVE + for (ORecordOperation op : tmpEntries) { + final ORecord record = op.getRecord(); + if (record != null) + ORecordInternal.unsetDirty(record); + } + } else if (result instanceof Throwable) { // EXCEPTION: LOG IT AND ADD AS NESTED EXCEPTION if (ODistributedServerLog.isDebugEnabled())
0bcf0c77e82f8e7fd0905d0c3fe4cbabdf7ff888
Vala
gio-2.0: GLib.Converter.convert bytes_read and bytes_written are out
c
https://github.com/GNOME/vala/
diff --git a/vapi/gio-2.0.vapi b/vapi/gio-2.0.vapi index bcf450c55f..f4f9bb6006 100644 --- a/vapi/gio-2.0.vapi +++ b/vapi/gio-2.0.vapi @@ -1000,7 +1000,7 @@ namespace GLib { } [CCode (cheader_filename = "gio/gio.h")] public interface Converter : GLib.Object { - public abstract GLib.ConverterResult convert (void* inbuf, size_t inbuf_size, void* outbuf, size_t outbuf_size, GLib.ConverterFlags flags, size_t bytes_read, size_t bytes_written) throws GLib.Error; + public abstract GLib.ConverterResult convert (void* inbuf, size_t inbuf_size, void* outbuf, size_t outbuf_size, GLib.ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws GLib.Error; public abstract void reset (); } [CCode (cheader_filename = "gio/gio.h")] diff --git a/vapi/packages/gio-2.0/gio-2.0.metadata b/vapi/packages/gio-2.0/gio-2.0.metadata index feb178db58..74e9aaed51 100644 --- a/vapi/packages/gio-2.0/gio-2.0.metadata +++ b/vapi/packages/gio-2.0/gio-2.0.metadata @@ -12,6 +12,8 @@ g_buffered_input_stream_peek_buffer.count is_out="1" g_content_type_guess.data_size hidden="1" g_content_type_guess.result_uncertain is_out="1" g_content_types_get_registered type_arguments="string" transfer_ownership="1" +g_converter_convert.bytes_read is_out="1" +g_converter_convert.bytes_written is_out="1" g_data_input_stream_read_line nullable="1" transfer_ownership="1" g_data_input_stream_read_line.length is_out="1" g_data_input_stream_read_line_finish nullable="1" transfer_ownership="1"
a342029d36fc8cdd6be3ab540cd2527ddd022188
elasticsearch
Histogram Facet: Allow to define a key field and- value script
a
https://github.com/elastic/elasticsearch
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java index 7c7d7def474f9..8c1ae4e0f8b03 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facet/histogram/KeyValueScriptHistogramFacetCollector.java @@ -95,6 +95,7 @@ public KeyValueScriptHistogramFacetCollector(String facetName, String fieldName, @Override protected void doSetNextReader(IndexReader reader, int docBase) throws IOException { fieldData = (NumericFieldData) fieldDataCache.cache(fieldDataType, reader, indexFieldName); + valueScript.setNextReader(reader); } @Override public Facet facet() {
05806bf8692b3106fb669681b31a9a8298425444
ismavatar$lateralgm
Created ResourceFrame class which gives base functionality to resource editing frames Modified ScriptFrame to extend ResourceFrame - Fully Functional Created FontFrame to edit fonts - Fully functional with font preview Created IntegerEdit for checked value editing Added a few $NON-NLS tags Made GameInfo and Game Settings frames get re-created every time a new file is created Made GameInfo and Game Settings set their frame icon Game Settings now shows "Last Changed" as a date string Added some static GM date functions to Gm6File Gm6File now sets LastChanged on instantiation Added instance id and tile id defragging Changed readTree to take the Gm6File src argument again, for the future ability to merge games easily. Also, Resource names are now ignored in tree data and taken from the Resource itself. Made Listener open scripts and fonts when node is double clicked, and made the frame update when the name is edited in the tree Added openFrame() and updateFrame() methods to ResNode Resources are now completely removed from the file when deleted LGM explicitly sets the look and Feel on startup (this was just to test other LAF's) Made all Resources set their name to the relevant prefix on creation, ResourceList adds LastId to the name string when add() is called. git-svn-id: https://lateralgm.svn.sourceforge.net/svnroot/lateralgm@40 8f422083-7f27-0410-bc82-93e204be8cd2
p
https://github.com/ismavatar/lateralgm
diff --git a/LateralGM/SubFrames/FontFrame.java b/LateralGM/SubFrames/FontFrame.java new file mode 100644 index 000000000..e5dd9005e --- /dev/null +++ b/LateralGM/SubFrames/FontFrame.java @@ -0,0 +1,236 @@ +package SubFrames; + +import java.awt.BorderLayout; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.GraphicsEnvironment; +import java.awt.event.ActionEvent; + +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingConstants; + +import mainRes.LGM; +import resourcesRes.Font; + +import componentRes.IntegerField; +import componentRes.ResNode; + +public class FontFrame extends ResourceFrame<Font> + { + private static final long serialVersionUID = 1L; + private static final ImageIcon frameIcon = LGM.findIcon("font.png"); //$NON-NLS-1$ + private static final ImageIcon saveIcon = LGM.findIcon("save.png"); //$NON-NLS-1$ + + public JComboBox fonts; + public IntegerField size; + public JCheckBox italic; + public JCheckBox bold; + public IntegerField charMin; + public IntegerField charMax; + public JLabel preview; + + public FontFrame(Font res, ResNode node) + { + super(res,node); + + setSize(250,390); + setResizable(false); + setMaximizable(false); + setFrameIcon(frameIcon); + + setContentPane(new JPanel()); + setLayout(new FlowLayout()); + + JLabel label = new JLabel(Messages.getString("FontFrame.NAME")); //$NON-NLS-1$ + label.setPreferredSize(new Dimension(40,14)); + label.setHorizontalAlignment(SwingConstants.RIGHT); + add(label); + name.setPreferredSize(new Dimension(180,20)); + add(name); + + label = new JLabel(Messages.getString("FontFrame.FONT")); //$NON-NLS-1$ + label.setPreferredSize(new Dimension(40,14)); + label.setHorizontalAlignment(SwingConstants.RIGHT); + add(label); + fonts = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()); + fonts.setEditable(true); + fonts.setSelectedItem(res.FontName); + fonts.setPreferredSize(new Dimension(180,20)); + fonts.addActionListener(this); + add(fonts); + + label = new JLabel(Messages.getString("FontFrame.SIZE")); //$NON-NLS-1$ + label.setPreferredSize(new Dimension(40,14)); + label.setHorizontalAlignment(SwingConstants.RIGHT); + add(label); + + size = new IntegerField(1,99,res.Size); + size.setPreferredSize(new Dimension(180,20)); + size.addActionListener(this); + add(size); + + bold = new JCheckBox(Messages.getString("FontFrame.BOLD")); //$NON-NLS-1$ + bold.setPreferredSize(new Dimension(110,16)); + bold.addActionListener(this); + bold.setSelected(res.Bold); + add(bold); + italic = new JCheckBox(Messages.getString("FontFrame.ITALIC")); //$NON-NLS-1$ + italic.setPreferredSize(new Dimension(110,16)); + italic.addActionListener(this); + italic.setSelected(res.Italic); + add(italic); + + JPanel crange = new JPanel(); + crange.setBorder(BorderFactory.createTitledBorder(Messages.getString("FontFrame.CHARRANGE"))); //$NON-NLS-1$ + crange.setPreferredSize(new Dimension(220,110)); + + charMin = new IntegerField(0,255,res.CharRangeMin); + charMin.setPreferredSize(new Dimension(70,20)); + charMin.addActionListener(this); + crange.add(charMin); + + label = new JLabel(Messages.getString("FontFrame.TO")); //$NON-NLS-1$ + label.setPreferredSize(new Dimension(40,16)); + label.setHorizontalAlignment(SwingConstants.CENTER); + crange.add(label); + + charMax = new IntegerField(0,255,res.CharRangeMax); + charMax.setPreferredSize(new Dimension(70,20)); + charMax.addActionListener(this); + crange.add(charMax); + + JButton but = new JButton(Messages.getString("FontFrame.NORMAL")); //$NON-NLS-1$ + but.setPreferredSize(new Dimension(90,20)); + but.setActionCommand("Normal"); //$NON-NLS-1$ + but.addActionListener(this); + crange.add(but); + + but = new JButton(Messages.getString("FontFrame.ALL")); //$NON-NLS-1$ + but.setPreferredSize(new Dimension(90,20)); + but.setActionCommand("All"); //$NON-NLS-1$ + but.addActionListener(this); + crange.add(but); + + but = new JButton(Messages.getString("FontFrame.DIGITS")); //$NON-NLS-1$ + but.setPreferredSize(new Dimension(90,20)); + but.setActionCommand("Digits"); //$NON-NLS-1$ + but.addActionListener(this); + crange.add(but); + + but = new JButton(Messages.getString("FontFrame.LETTERS")); //$NON-NLS-1$ + but.setPreferredSize(new Dimension(90,20)); + but.setActionCommand("Letters"); //$NON-NLS-1$ + but.addActionListener(this); + crange.add(but); + + add(crange); + + JPanel prev = new JPanel(new BorderLayout()); + prev.setBorder(BorderFactory.createEtchedBorder()); + prev.setPreferredSize(new Dimension(220,100)); + preview = new JLabel(Messages.getString("FontFrame.FONT_PREVIEW")); //$NON-NLS-1$ + preview.setFont(new java.awt.Font(res.FontName,makeStyle(res.Bold,res.Italic),res.Size)); + preview.setHorizontalAlignment(SwingConstants.CENTER); + prev.add(preview,"Center"); //$NON-NLS-1$ + add(prev); + + save.setPreferredSize(new Dimension(100,27)); + save.setIcon(saveIcon); + save.setText(Messages.getString("FontFrame.SAVE")); //$NON-NLS-1$ + save.setAlignmentX(0.5f); + add(save); + } + + public boolean resourceChanged() + { + if (!res.name.equals(name.getText()) || !res.FontName.equals(fonts.getSelectedItem().toString()) + || res.Size != size.getIntValue() || res.Bold != bold.isSelected() + || res.Italic != italic.isSelected() || res.CharRangeMin != charMin.getIntValue() + || res.CharRangeMax != charMax.getIntValue()) return true; + return false; + } + + public void revertResource() + { + LGM.currentFile.Fonts.replace(res.Id,resOriginal); + } + + public void updateResource() + { + res.name = name.getText(); + res.FontName = fonts.getSelectedItem().toString(); + res.Size = size.getIntValue(); + res.Bold = bold.isSelected(); + res.Italic = italic.isSelected(); + res.CharRangeMin = charMin.getIntValue(); + res.CharRangeMax = charMax.getIntValue(); + resOriginal = (Font) res.copy(false,null); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getSource() == fonts || e.getSource() == bold || e.getSource() == italic || e.getSource() == size) + { + updatePreview(); + return; + } + if (e.getSource() == charMin) + { + if (charMin.getIntValue() > charMax.getIntValue()) + { + charMax.setIntValue(charMin.getIntValue()); + return; + } + } + if (e.getSource() == charMax) + { + if (charMax.getIntValue() < charMin.getIntValue()) + { + charMin.setIntValue(charMax.getIntValue()); + return; + } + } + if (e.getActionCommand() == "Normal") //$NON-NLS-1$ + { + charMin.setIntValue(32); + charMax.setIntValue(127); + return; + } + if (e.getActionCommand() == "All") //$NON-NLS-1$ + { + charMin.setIntValue(0); + charMax.setIntValue(255); + return; + } + if (e.getActionCommand() == "Digits") //$NON-NLS-1$ + { + charMin.setIntValue(48); + charMax.setIntValue(57); + return; + } + if (e.getActionCommand() == "Letters") //$NON-NLS-1$ + { + charMin.setIntValue(65); + charMax.setIntValue(122); + return; + } + super.actionPerformed(e); + } + + public void updatePreview() + { + preview.setFont(new java.awt.Font(fonts.getSelectedItem().toString(),makeStyle(bold.isSelected(),italic + .isSelected()),size.getIntValue())); + } + + private static int makeStyle(boolean bold, boolean italic) + { + return (italic ? java.awt.Font.ITALIC : 0) | (bold ? java.awt.Font.BOLD : 0); + } + } diff --git a/LateralGM/SubFrames/GameInformationFrame.java b/LateralGM/SubFrames/GameInformationFrame.java index 344daa766..781f6a378 100644 --- a/LateralGM/SubFrames/GameInformationFrame.java +++ b/LateralGM/SubFrames/GameInformationFrame.java @@ -47,6 +47,7 @@ public GameInformationFrame() super(Messages.getString("GameInformationFrame.TITLE"),true,true,true,true); //$NON-NLS-1$ setDefaultCloseOperation(HIDE_ON_CLOSE); setSize(600,400); + setFrameIcon(LGM.findIcon("info.png")); // Setup the Menu // Create the menu bar JMenuBar menuBar = new JMenuBar(); diff --git a/LateralGM/SubFrames/GameSettingFrame.java b/LateralGM/SubFrames/GameSettingFrame.java index 0065d19cb..98d3c0631 100644 --- a/LateralGM/SubFrames/GameSettingFrame.java +++ b/LateralGM/SubFrames/GameSettingFrame.java @@ -22,6 +22,7 @@ import javax.swing.JTextField; import mainRes.LGM; +import fileRes.Gm6File; public class GameSettingFrame extends JInternalFrame implements ActionListener { @@ -36,6 +37,7 @@ public GameSettingFrame() super(Messages.getString("GameSettingFrame.TITLE"),true,true,true,true); //$NON-NLS-1$ setDefaultCloseOperation(HIDE_ON_CLOSE); setSize(540,470); + setFrameIcon(LGM.findIcon("gm.png")); setLayout(new FlowLayout()); tabbedPane.setPreferredSize(new Dimension(530,400)); setResizable(false); @@ -210,9 +212,9 @@ public GameSettingFrame() label = new JLabel(Messages.getString("GameSettingFrame.LASTCHANGED")); //$NON-NLS-1$ label.setPreferredSize(new Dimension(80,25)); panel8.add(label); - box = new JTextField("" + LGM.currentFile.LastChanged); + box = new JTextField(Gm6File.gmTimeToString(LGM.currentFile.LastChanged)); box.setPreferredSize(new Dimension(390,25)); - box.setEnabled(false); + box.setEditable(false); panel8.add(box); label = new JLabel(Messages.getString("GameSettingFrame.INFORMATION")); //$NON-NLS-1$ label.setPreferredSize(new Dimension(70,25)); diff --git a/LateralGM/SubFrames/ResourceFrame.java b/LateralGM/SubFrames/ResourceFrame.java new file mode 100644 index 000000000..eb89eea86 --- /dev/null +++ b/LateralGM/SubFrames/ResourceFrame.java @@ -0,0 +1,135 @@ +package SubFrames; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JInternalFrame; +import javax.swing.JOptionPane; +import javax.swing.JTextField; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.InternalFrameEvent; + +import mainRes.LGM; +import resourcesRes.Resource; + +import componentRes.NameDocument; +import componentRes.ResNode; + +// Provides common functionality and structure to Resource editing frames +public abstract class ResourceFrame<R extends Resource> extends JInternalFrame implements DocumentListener, + ActionListener + { + private static final long serialVersionUID = 1L; + public JTextField name; // The Resource's name - setup automatically to update the title of the frame and + // the ResNode's text + public JButton save; // automatically set up to save and close the frame + public R res; // the resource this frame is editing + public R resOriginal; // backup of res as it was before changes were made + public String titlePrefix = ""; //$NON-NLS-1$ + public String titleSuffix = ""; //$NON-NLS-1$ + public ResNode node; // node this frame is linked to + + public ResourceFrame(R res, ResNode node) + { + super("",true,true,true,true); //$NON-NLS-1$ + this.res = res; + this.node = node; + resOriginal = (R) res.copy(false,null); + setTitle(res.name); + setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE); + name = new JTextField(); + name.setDocument(new NameDocument()); + name.setText(res.name); + name.getDocument().addDocumentListener(this); + save = new JButton(); + save.addActionListener(this); + } + + public abstract void updateResource(); + + public abstract void revertResource(); + + public abstract boolean resourceChanged(); + + public void changedUpdate(DocumentEvent e) + { + // Not used + } + + public void insertUpdate(DocumentEvent e) + { + if (e.getDocument() == name.getDocument()) + { + res.name = name.getText(); + setTitle(name.getText()); + node.setUserObject(name.getText()); + LGM.tree.updateUI(); + } + } + + public void removeUpdate(DocumentEvent e) + { + if (e.getDocument() == name.getDocument()) + { + res.name = name.getText(); + setTitle(name.getText()); + node.setUserObject(name.getText()); + LGM.tree.updateUI(); + } + } + + public void actionPerformed(ActionEvent e) + { + if (e.getSource() == save) + { + updateResource(); + dispose(); + } + } + + public void setTitle(String title) + { + super.setTitle(titlePrefix + title + titleSuffix); + } + + public void dispose() + { + super.dispose(); + node.frame = null;// allows a new frame to open + } + + protected void fireInternalFrameEvent(int id) + { + if (id == InternalFrameEvent.INTERNAL_FRAME_CLOSING) + { + if (resourceChanged()) + { + switch (JOptionPane.showConfirmDialog(LGM.frame,String.format(Messages + .getString("ResourceFrame.KEEPCHANGES"),res.name),Messages //$NON-NLS-1$ + .getString("ResourceFrame.KEEPCHANGES_TITLE"),JOptionPane.YES_NO_CANCEL_OPTION)) //$NON-NLS-1$ + { + case 0: // yes + updateResource(); + node.setUserObject(res.name); + dispose(); + LGM.tree.updateUI(); + break; + case 1: // no + revertResource(); + node.setUserObject(resOriginal.name); + dispose(); + LGM.tree.updateUI(); + break; + } + } + else + { + updateResource(); + dispose(); + } + } + super.fireInternalFrameEvent(id); + } + } diff --git a/LateralGM/SubFrames/ScriptFrame.java b/LateralGM/SubFrames/ScriptFrame.java index c1a39331f..0bce0ec7f 100644 --- a/LateralGM/SubFrames/ScriptFrame.java +++ b/LateralGM/SubFrames/ScriptFrame.java @@ -2,60 +2,65 @@ import java.awt.BorderLayout; -import javax.swing.JButton; -import javax.swing.JInternalFrame; +import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; -import javax.swing.JTextField; import javax.swing.JToolBar; import mainRes.LGM; import mainRes.Prefs; -import resourcesRes.GameInformation; -import resourcesRes.ResId; import resourcesRes.Script; -import componentRes.NameDocument; +import componentRes.ResNode; -public class ScriptFrame extends JInternalFrame +public class ScriptFrame extends ResourceFrame<Script> { private static final long serialVersionUID = 1L; - public static GameInformation gi = new GameInformation(); - public static JTextField name; - public static JTextArea code; + private static final ImageIcon frameIcon = LGM.findIcon("script.png"); //$NON-NLS-1$ + private static final ImageIcon saveIcon = LGM.findIcon("save.png"); //$NON-NLS-1$ + public JTextArea code; - public ScriptFrame(ResId id) + public ScriptFrame(Script res, ResNode node) { - super("ScriptName",true,true,true,true); - Script scr = LGM.currentFile.Scripts.getList(0); - this.setTitle(scr.name); + super(res,node); setSize(600,400); + setFrameIcon(frameIcon); // Setup the toolbar JToolBar tool = new JToolBar(); tool.setFloatable(false); tool.setAlignmentX(0); add("North",tool); //$NON-NLS-1$ // Setup the buttons - JButton but = new JButton(LGM.findIcon("save.png")); //$NON-NLS-1$ - but.setActionCommand("Save"); //$NON-NLS-1$ - // but.addActionListener(this); - tool.add(but); + save.setIcon(saveIcon); + tool.add(save); tool.addSeparator(); tool.add(new JLabel(Messages.getString("ScriptFrame.NAME"))); //$NON-NLS-1$ - name = new JTextField(new NameDocument(),"",13); //$NON-NLS-1$ + name.setColumns(13); name.setMaximumSize(name.getPreferredSize()); tool.add(name); // the code text area code = new JTextArea(); code.setFont(Prefs.codeFont); + code.setText(res.ScriptStr); JScrollPane codePane = new JScrollPane(code); getContentPane().add(codePane,BorderLayout.CENTER); } - public void setScript(Script s) + public void revertResource() { - name.setText(s.name); - code.setText(s.ScriptStr); + LGM.currentFile.Scripts.replace(res.Id,resOriginal); + } + + public void updateResource() + { + res.ScriptStr = code.getText(); + res.name = name.getText(); + resOriginal = (Script) res.copy(false,null); + } + + public boolean resourceChanged() + { + return (!code.getText().equals(res.ScriptStr)) || (!res.name.equals(resOriginal.name)); } } \ No newline at end of file diff --git a/LateralGM/SubFrames/messages.properties b/LateralGM/SubFrames/messages.properties index eff476612..08fe2fa1a 100644 --- a/LateralGM/SubFrames/messages.properties +++ b/LateralGM/SubFrames/messages.properties @@ -1,4 +1,5 @@ GameSettingFrame.TITLE=Game Settings + GameSettingFrame.TAB_GRAPHICS=Graphics GameSettingFrame.HINT_GRAPHICS=Configure Graphics settings GameSettingFrame.FULLSCREEN=Start in FullScreen Mode @@ -15,8 +16,10 @@ GameSettingFrame.NOBORDER=Don't draw a border in windowed mode GameSettingFrame.NOBUTTONS=Don't show the buttons in the window caption GameSettingFrame.DISPLAYCURSOR=Display Mouse GameSettingFrame.FREEZE=Freeze the game when the game loses focus + GameSettingFrame.TAB_RESOLUTION=Resolution GameSettingFrame.HINT_RESOLUTION=Configure Resolution + GameSettingFrame.TAB_OTHER=Other GameSettingFrame.HINT_OTHER=Configure Other Settings GameSettingFrame.TITLE_KEYS=Default Keys @@ -26,43 +29,69 @@ GameSettingFrame.KEY_SWITCHFULLSCREEN=Let <F4> switch between screen modes GameSettingFrame.SAVELOAD=Let <F5> save the game and <F6> load the game GameSettingFrame.TITLE_PRIORITY=Game Process Priority GameSettingFrame.PRIORITY_NORMAL=Normal -GameInformationFrame.MENU_FORMAT=Format GameSettingFrame.PRIORITY_HIGH=High GameSettingFrame.PRIORITY_HIHGEST=Highest + GameSettingFrame.TAB_LOADING=Loading GameSettingFrame.HINT_LOADING=Configure Loading Settings + GameSettingFrame.TAB_CONSTANTS=Constants -GameInformationFrame.MENU_FILE=File -GameInformationFrame.CLOSESAVE=Close saving changes -GameInformationFrame.MENU_EDIT=Edit -GameInformationFrame.SELECTALL=Select All GameSettingFrame.HINT_CONSTANTS=Configure Constants + GameSettingFrame.TAB_INCLUDE=Include GameSettingFrame.HINT_INCLUDE=Configure Includes + GameSettingFrame.TAB_ERRORS=Errors GameSettingFrame.HINT_ERRORS=Configure Error handling GameSettingFrame.ERRORS_DISPLAY=Display error messages GameSettingFrame.ERRORS_LOG=Write game error messages to file game_errors.log GameSettingFrame.ERRORS_ABORT=Abort on all error messages -GameInformationFrame.TYPE_RTF=Rich text Files GameSettingFrame.UNINITZERO=Treat uninitialized variables as 0 + GameSettingFrame.TAB_INFO=Info +GameSettingFrame.HINT_INFO=Configure Information +GameSettingFrame.AUTHOR=Author +GameSettingFrame.VERSION=Version +GameSettingFrame.LASTCHANGED=Last Changed +GameSettingFrame.INFORMATION=Information +GameSettingFrame.BUTTON_SAVE=Save +GameSettingFrame.BUTTON_DISCARD=Don't save + +GameInformationFrame.MENU_FORMAT=Format +GameInformationFrame.MENU_FILE=File +GameInformationFrame.CLOSESAVE=Close saving changes +GameInformationFrame.MENU_EDIT=Edit +GameInformationFrame.SELECTALL=Select All +GameInformationFrame.TYPE_RTF=Rich text Files GameInformationFrame.LOAD=Load from a file GameInformationFrame.SAVE=Save to a file GameInformationFrame.UNDO=Undo GameInformationFrame.COPY=Copy GameInformationFrame.GOTO=Goto line GameInformationFrame.FONT=Font... -GameSettingFrame.HINT_INFO=Configure Information GameInformationFrame.TITLE=Game Information GameInformationFrame.PRINT=Print... GameInformationFrame.PASTE=Paste -GameSettingFrame.AUTHOR=Author -GameSettingFrame.VERSION=Version GameInformationFrame.CUT=Cut -GameSettingFrame.LASTCHANGED=Last Changed -GameSettingFrame.INFORMATION=Information -GameSettingFrame.BUTTON_SAVE=Save GameInformationFrame.OPTIONS=Options... -GameSettingFrame.BUTTON_DISCARD=Don't save + +ResourceFrame.KEEPCHANGES=Changes have been made to %s. Keep the changes? +ResourceFrame.KEEPCHANGES_TITLE=Resource Changed + + ScriptFrame.NAME=Name: + +FontFrame.NAME=Name: +FontFrame.NAME=Name: +FontFrame.FONT=Font: +FontFrame.SIZE=Size: +FontFrame.BOLD=Bold +FontFrame.ITALIC=Italic +FontFrame.CHARRANGE=Character Range +FontFrame.TO=to +FontFrame.NORMAL=Normal +FontFrame.ALL=All +FontFrame.DIGITS=Digits +FontFrame.LETTERS=Letters +FontFrame.FONT_PREVIEW=AaBbCcDd +FontFrame.SAVE=Save diff --git a/LateralGM/componentRes/CustomFileFilter.java b/LateralGM/componentRes/CustomFileFilter.java index bc01ece8d..08911b74e 100644 --- a/LateralGM/componentRes/CustomFileFilter.java +++ b/LateralGM/componentRes/CustomFileFilter.java @@ -1,6 +1,7 @@ package componentRes; import java.io.File; + import javax.swing.filechooser.FileFilter; public class CustomFileFilter extends FileFilter diff --git a/LateralGM/componentRes/IntegerDocument.java b/LateralGM/componentRes/IntegerDocument.java new file mode 100644 index 000000000..0b4a4d069 --- /dev/null +++ b/LateralGM/componentRes/IntegerDocument.java @@ -0,0 +1,25 @@ +package componentRes; + +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.PlainDocument; + +public class IntegerDocument extends PlainDocument + { + private static final long serialVersionUID = 1L; + private boolean allowNegative; + + public IntegerDocument(boolean allowNegative) + { + this.allowNegative = allowNegative; + } + + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException + { + if (str == null) return; + if (allowNegative && offs == 0) + super.insertString(offs,str.replaceAll("[^0-9-]",""),a); + else + super.insertString(offs,str.replaceAll("\\D",""),a); + } + } \ No newline at end of file diff --git a/LateralGM/componentRes/IntegerField.java b/LateralGM/componentRes/IntegerField.java new file mode 100644 index 000000000..63b9a5bd0 --- /dev/null +++ b/LateralGM/componentRes/IntegerField.java @@ -0,0 +1,84 @@ +package componentRes; + +import java.awt.event.FocusEvent; + +import javax.swing.JTextField; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; + +public class IntegerField extends JTextField implements DocumentListener + { + private static final long serialVersionUID = 1L; + private int min; + private int max; + private int lastGoodVal; + private boolean setting = false;// prevents recursive calls of setText + + public IntegerField(int min, int max) + { + this(min,max,min); + } + + public IntegerField(int min, int max, int val) + { + this.min = min; + this.max = max; + lastGoodVal = Math.max(min,Math.min(val,max)); + setDocument(new IntegerDocument(min < 0)); + setText(Integer.toString(lastGoodVal)); + getDocument().addDocumentListener(this); + } + + public void changedUpdate(DocumentEvent e) + { + fireActionPerformed(); + } + + public void insertUpdate(DocumentEvent e) + { + fireActionPerformed(); + } + + public void removeUpdate(DocumentEvent e) + { + fireActionPerformed(); + } + + public int getIntValue() + { + try + { + int val = Integer.parseInt(getText()); + lastGoodVal = Math.max(min,Math.min(val,max)); + } + catch (NumberFormatException ex) + { + } + return lastGoodVal; + } + + public void setIntValue(int val) + { + lastGoodVal = Math.max(min,Math.min(val,max)); + setText(Integer.toString(lastGoodVal)); + } + + protected void processFocusEvent(FocusEvent e) + { + if (e.getID() == FocusEvent.FOCUS_LOST) + { + setText(Integer.toString(getIntValue())); + } + super.processFocusEvent(e); + } + + public void setText(String s) + { + if (!setting) + { + setting = true; + super.setText(s); + setting = false; + } + } + } diff --git a/LateralGM/componentRes/Listener.java b/LateralGM/componentRes/Listener.java index c99b0ffd8..4804005a1 100644 --- a/LateralGM/componentRes/Listener.java +++ b/LateralGM/componentRes/Listener.java @@ -7,6 +7,8 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; +import java.util.Enumeration; +import java.util.EventObject; import javax.swing.JComponent; import javax.swing.JFileChooser; @@ -15,18 +17,21 @@ import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.TransferHandler; +import javax.swing.event.CellEditorListener; +import javax.swing.event.ChangeEvent; import javax.swing.tree.TreePath; import mainRes.LGM; import mainRes.Prefs; +import resourcesRes.Font; import resourcesRes.Resource; +import resourcesRes.Script; import SubFrames.GameInformationFrame; import SubFrames.GameSettingFrame; -import SubFrames.ScriptFrame; import fileRes.Gm6File; import fileRes.Gm6FormatException; -public class Listener extends TransferHandler implements ActionListener,MouseListener +public class Listener extends TransferHandler implements ActionListener,MouseListener,CellEditorListener { private static final long serialVersionUID = 1L; @@ -42,13 +47,19 @@ public void actionPerformed(ActionEvent e) f.setOpaque(true); LGM.frame.setContentPane(f); LGM.currentFile = new Gm6File(); + LGM.gameSet.dispose(); + LGM.gameSet = new GameSettingFrame(); + LGM.MDI.add(LGM.gameSet); + LGM.gameInfo.dispose(); + LGM.gameInfo = new GameInformationFrame(); + LGM.MDI.add(LGM.gameInfo); f.updateUI(); return; } if (com.endsWith(".OPEN")) //$NON-NLS-1$ { JFileChooser fc = new JFileChooser(); - fc.setFileFilter(new CustomFileFilter(".gm6",Messages.getString("Listener.FORMAT_GM6"))); //$NON-NLS-2$ + fc.setFileFilter(new CustomFileFilter(".gm6",Messages.getString("Listener.FORMAT_GM6"))); //$NON-NLS-1$//$NON-NLS-2$ fc.showOpenDialog(LGM.frame); if (fc.getSelectedFile() != null) @@ -57,7 +68,7 @@ public void actionPerformed(ActionEvent e) { try { - ResNode newroot = new ResNode("Root",0,0,null); + ResNode newroot = new ResNode("Root",0,0,null); //$NON-NLS-1$ LGM.currentFile = new Gm6File(); LGM.currentFile.ReadGm6File(fc.getSelectedFile().getPath(),newroot); LGM f = new LGM(); @@ -74,14 +85,14 @@ public void actionPerformed(ActionEvent e) .showMessageDialog( LGM.frame, String.format( - Messages.getString("Listener.ERROR_MESSAGE"),ex.stackAsString(),ex.getMessage()),Messages.getString("Listener.ERROR_TITLE"),JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ + Messages.getString("Listener.ERROR_MESSAGE"),ex.stackAsString(),ex.getMessage()),Messages.getString("Listener.ERROR_TITLE"),JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ } } } - LGM.gameInfo.setVisible(false); + LGM.gameInfo.dispose(); LGM.gameInfo = new GameInformationFrame(); LGM.MDI.add(LGM.gameInfo); - LGM.gameSet.setVisible(false); + LGM.gameSet.dispose(); LGM.gameSet = new GameSettingFrame(); LGM.MDI.add(LGM.gameSet); return; @@ -93,12 +104,12 @@ public void actionPerformed(ActionEvent e) if (com.endsWith(".SAVEAS")) //$NON-NLS-1$ { JFileChooser fc = new JFileChooser(); - fc.setFileFilter(new CustomFileFilter(".gm6",Messages.getString("Listener.FORMAT_GM6"))); //$NON-NLS-2$ + fc.setFileFilter(new CustomFileFilter(".gm6",Messages.getString("Listener.FORMAT_GM6"))); //$NON-NLS-1$//$NON-NLS-2$ while (true) { if (fc.showSaveDialog(LGM.frame) != JFileChooser.APPROVE_OPTION) return; String filename = fc.getSelectedFile().getPath(); - if (!filename.endsWith(".gm6")) filename += ".gm6"; + if (!filename.endsWith(".gm6")) filename += ".gm6"; //$NON-NLS-1$ //$NON-NLS-2$ int result = 0; if (new File(filename).exists()) result = JOptionPane.showConfirmDialog(LGM.frame,String.format(Messages @@ -107,6 +118,12 @@ public void actionPerformed(ActionEvent e) JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE); if (result == 0) { + Enumeration<ResNode> nodes = LGM.root.preorderEnumeration(); + while (nodes.hasMoreElements()) + { + ResNode node = nodes.nextElement(); + if (node.frame != null) node.frame.updateResource(); // update open frames + } LGM.currentFile.WriteGm6File(filename,LGM.root); return; } @@ -128,7 +145,7 @@ public void actionPerformed(ActionEvent e) if (com.equals("GROUP")) //$NON-NLS-1$ { String name = JOptionPane.showInputDialog(Messages.getString("Listener.INPUT_GROUPNAME"),"group"); //$NON-NLS-1$ - if (name == "") return; + if (name == "" || name == null) return; //$NON-NLS-1$ ResNode g = new ResNode(name,parent.kind,ResNode.STATUS_GROUP); parent.insert(g,pos); tree.expandPath(new TreePath(parent.getPath())); @@ -157,18 +174,45 @@ public void actionPerformed(ActionEvent e) if (com.equals("GROUP")) //$NON-NLS-1$ { String name = JOptionPane.showInputDialog(Messages.getString("Listener.INPUT_GROUPNAME"),"Group"); //$NON-NLS-1$ - if (name == "") return; - ResNode g = new ResNode(name,parent.kind,ResNode.STATUS_GROUP); + if (name == "" || name == null) return; //$NON-NLS-1$ + ResNode g = new ResNode(name,ResNode.STATUS_GROUP,parent.kind); + parent.insert(g,pos); + tree.expandPath(new TreePath(parent.getPath())); + tree.setSelectionPath(new TreePath(g.getPath())); + tree.updateUI(); + return; + } + if (com.equals("SCRIPT")) //$NON-NLS-1$ + { + // TODO Maybe make this non-dependent on the order of nodes + if (node.kind != Resource.SCRIPT) parent = (ResNode) LGM.root.getChildAt(5); + + Script scr = LGM.currentFile.Scripts.add(); + ResNode g = new ResNode(scr.name,ResNode.STATUS_SECONDARY,Resource.SCRIPT,scr.Id); + parent.insert(g,pos); + tree.expandPath(new TreePath(parent.getPath())); + tree.setSelectionPath(new TreePath(g.getPath())); + tree.updateUI(); + g.openFrame(); + return; + } + if (com.equals("FONT")) //$NON-NLS-1$ + { + if (node.kind != Resource.FONT) parent = (ResNode) LGM.root.getChildAt(5); + Font font = LGM.currentFile.Fonts.add(); + ResNode g = new ResNode(font.name,ResNode.STATUS_SECONDARY,Resource.FONT,font.Id); parent.insert(g,pos); tree.expandPath(new TreePath(parent.getPath())); tree.setSelectionPath(new TreePath(g.getPath())); tree.updateUI(); + g.openFrame(); return; } } if (com.endsWith(".RENAME")) //$NON-NLS-1$ { - tree.startEditingAtPath(tree.getLeadSelectionPath()); + if (tree.getCellEditor().isCellEditable(new EventObject(LGM.tree))) + tree.startEditingAtPath(tree.getLeadSelectionPath()); return; } if (com.endsWith(".DELETE")) //$NON-NLS-1$ @@ -186,14 +230,15 @@ public void actionPerformed(ActionEvent e) if (next.isRoot()) next = (ResNode) next.getFirstChild(); tree.setSelectionPath(new TreePath(next.getPath())); me.removeFromParent(); + LGM.currentFile.getList(me.kind).remove(me.resourceId); tree.updateUI(); } return; } - if (com.endsWith(".DEFRAGIDS")) + if (com.endsWith(".DEFRAGIDS")) //$NON-NLS-1$ { - if (JOptionPane.showConfirmDialog(LGM.frame,Messages.getString("Listener.CONFIRM_DEFRAGIDS"),Messages - .getString("Listener.CONFIRM_DEFRAGIDS_TITLE"),JOptionPane.YES_NO_OPTION) == 0) + if (JOptionPane.showConfirmDialog(LGM.frame,Messages.getString("Listener.CONFIRM_DEFRAGIDS"),Messages //$NON-NLS-1$ + .getString("Listener.CONFIRM_DEFRAGIDS_TITLE"),JOptionPane.YES_NO_OPTION) == 0) //$NON-NLS-1$ LGM.currentFile.DefragIds(); } if (com.endsWith(".EXPAND")) //$NON-NLS-1$ @@ -285,47 +330,55 @@ else if (e.getClickCount() == 2) ResNode node = (ResNode) selPath.getLastPathComponent(); if (node.kind == Resource.GAMEINFO) { - // JInternalFrame gameinfo = new GameInformationFrame(); LGM.gameInfo.setVisible(true); return; - // LGM.MDI.add(LGM.gameInfo); } - if (node.kind == Resource.GAMESETTINGS) { LGM.gameSet.setVisible(true); - } - - if (node.kind == Resource.SCRIPT) - { - if (node.status == ResNode.STATUS_PRIMARY) return; - if (Prefs.protectLeaf && node.status != ResNode.STATUS_SECONDARY) return; - ScriptFrame sf = new ScriptFrame(node.resourceId); - // sf.setScript(); - LGM.MDI.add(sf); - sf.setVisible(true); return; } - + // kind must be a Resource kind + if (node.status == ResNode.STATUS_PRIMARY) return; + if (Prefs.protectLeaf && node.status != ResNode.STATUS_SECONDARY) return; + node.openFrame(); + return; } } } } // Unused - public void mouseReleased(MouseEvent arg0) + public void mouseReleased(MouseEvent e) { } - public void mouseClicked(MouseEvent arg0) + public void mouseClicked(MouseEvent e) { } - public void mouseEntered(MouseEvent arg0) + public void mouseEntered(MouseEvent e) { } - public void mouseExited(MouseEvent arg0) + public void mouseExited(MouseEvent e) { } + + public void editingCanceled(ChangeEvent e) + { + } + + public void editingStopped(ChangeEvent e) + { + ResNode node = (ResNode) LGM.tree.getLastSelectedPathComponent(); + if (node.status == ResNode.STATUS_SECONDARY && node.kind != Resource.GAMEINFO + && node.kind != Resource.GAMESETTINGS) + { + String txt = ((String) node.getUserObject()).replaceAll("\\W",""); //$NON-NLS-1$ //$NON-NLS-2$ + if (!Character.toString(txt.charAt(0)).matches("[A-Za-z_]")) txt = txt.substring(1); //$NON-NLS-1$ + node.setUserObject(txt); + node.updateFrame(); + } + } } \ No newline at end of file diff --git a/LateralGM/componentRes/ResNode.java b/LateralGM/componentRes/ResNode.java index d714cf0cd..9d4b2fc4d 100644 --- a/LateralGM/componentRes/ResNode.java +++ b/LateralGM/componentRes/ResNode.java @@ -3,6 +3,7 @@ import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; +import java.beans.PropertyVetoException; import java.util.Arrays; import javax.swing.tree.DefaultMutableTreeNode; @@ -10,6 +11,10 @@ import mainRes.LGM; import mainRes.Prefs; import resourcesRes.ResId; +import resourcesRes.Resource; +import SubFrames.FontFrame; +import SubFrames.ResourceFrame; +import SubFrames.ScriptFrame; public class ResNode extends DefaultMutableTreeNode implements Transferable { @@ -22,6 +27,7 @@ public class ResNode extends DefaultMutableTreeNode implements Transferable public byte status; public byte kind; public ResId resourceId; + public ResourceFrame frame = null; public ResNode(String name, byte status, byte kind, ResId res) { @@ -80,4 +86,53 @@ public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorExcepti if (flavor != NODE_FLAVOR) throw new UnsupportedFlavorException(flavor); return this; } + + public void openFrame() + { + if (frame == null) + { + ResourceFrame rf = null; + switch (kind) + { + case Resource.SCRIPT: + rf = new ScriptFrame(LGM.currentFile.Scripts.get(resourceId),this); + break; + case Resource.FONT: + rf = new FontFrame(LGM.currentFile.Fonts.get(resourceId),this); + break; + } + if (rf != null) + { + frame = rf; + LGM.MDI.add(rf); + rf.setVisible(true); + } + } + else + { + frame.toFront(); + try + { + frame.setIcon(false); + } + catch (PropertyVetoException e) + { + e.printStackTrace(); + } + } + } + + public void updateFrame() + { + if (status == STATUS_SECONDARY) + { + String txt = (String) getUserObject(); + LGM.currentFile.getList(kind).get(resourceId).name = txt; + if (frame != null) + { + frame.setTitle(txt); + frame.name.setText(txt); + } + } + } } \ No newline at end of file diff --git a/LateralGM/fileRes/Gm6File.java b/LateralGM/fileRes/Gm6File.java index cde23d9cd..7d25e9d35 100644 --- a/LateralGM/fileRes/Gm6File.java +++ b/LateralGM/fileRes/Gm6File.java @@ -8,6 +8,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; @@ -119,6 +120,25 @@ public Gm6File() } } + public static Calendar gmBaseTime() + { + Calendar res = Calendar.getInstance(); + res.set(1899,11,29,23,59,59); + return res; + } + + public static double longTimeToGmTime(long time) + { + return (time - gmBaseTime().getTimeInMillis()) / 86400000d; + } + + public static String gmTimeToString(double time) + { + Calendar base = gmBaseTime(); + base.setTimeInMillis(base.getTimeInMillis() + ((long) (time * 86400000))); + return DateFormat.getDateTimeInstance().format(base.getTime()); + } + // Constants For Resource Properties public static final byte COLOR_NOCHANGE = 0; public static final byte COLOR_16 = 1; @@ -181,7 +201,7 @@ public Gm6File() public boolean TreatUninitializedAs0 = false; public String Author = ""; //$NON-NLS-1$ public int Version = 100; - public double LastChanged = 0; + public double LastChanged = longTimeToGmTime(System.currentTimeMillis()); public String Information = ""; //$NON-NLS-1$ public int IncludeFolder = INCLUDE_MAIN; public boolean OverwriteExisting = false; @@ -894,7 +914,7 @@ public void ReadGm6File(String FileName, ResNode root) throws Gm6FormatException throw new Gm6FormatException(String.format( Messages.getString("Gm6File.ERROR_UNSUPPORTED_AFTERINFO2"),ver)); //$NON-NLS-1$ in.skip(in.readi() * 4);// room indexes in tree order; - in.readTree(root); + in.readTree(root,this); System.out.printf(Messages.getString("Gm6File.LOADTIME"),System.currentTimeMillis() - startTime); //$NON-NLS-1$ System.out.println(); } @@ -987,10 +1007,8 @@ public void WriteGm6File(String FileName, ResNode root) out.writeBool(TreatUninitializedAs0); out.writeStr(Author); out.writei(Version); - - Calendar then = Calendar.getInstance(); - then.set(1899,11,29,23,59,59); - out.writeD((savetime - then.getTimeInMillis()) / 86400000.0); + LastChanged = longTimeToGmTime(savetime); + out.writeD(LastChanged); out.writeStr(Information); out.writei(constants.size()); @@ -1498,8 +1516,17 @@ public void WriteGm6File(String FileName, ResNode root) public void DefragIds() { - Iterator iter = resMap.values().iterator(); + Iterator<ResourceList> iter = resMap.values().iterator(); while (iter.hasNext()) - ((ResourceList) iter.next()).defragIds(); + iter.next().defragIds(); + LastInstanceId = 100000; + LastTileId = 100000; + for (int i = 0; i < Rooms.count(); i++) + { + for (int j = 0; j < Rooms.getList(i).NoInstances(); j++) + Rooms.getList(i).getInstanceList(j).InstanceId = ++LastInstanceId; + for (int j = 0; j < Rooms.getList(i).NoTiles(); j++) + Rooms.getList(i).getTileList(j).TileId = ++LastTileId; + } } } \ No newline at end of file diff --git a/LateralGM/fileRes/GmStreamDecoder.java b/LateralGM/fileRes/GmStreamDecoder.java index 3e4bfb8e7..f1399b376 100644 --- a/LateralGM/fileRes/GmStreamDecoder.java +++ b/LateralGM/fileRes/GmStreamDecoder.java @@ -15,8 +15,6 @@ import resourcesRes.Resource; -import mainRes.LGM; - import componentRes.ResNode; public class GmStreamDecoder @@ -50,7 +48,7 @@ public int readi() throws IOException int c = _in.read(); int d = _in.read(); if (a == -1 || b == -1 || c == -1 || d == -1) - throw new IOException(Messages.getString("GmStreamDecoder.UNEXPECTED_EOF")); + throw new IOException(Messages.getString("GmStreamDecoder.UNEXPECTED_EOF")); //$NON-NLS-1$ long result = (a | (b << 8) | (c << 16) | (d << 24)); return (int) result; } @@ -59,7 +57,7 @@ public String readStr() throws IOException { byte data[] = new byte[readi()]; long check = _in.read(data); - if (check < data.length) throw new IOException(Messages.getString("GmStreamDecoder.UNEXPECTED_EOF")); + if (check < data.length) throw new IOException(Messages.getString("GmStreamDecoder.UNEXPECTED_EOF")); //$NON-NLS-1$ return new String(data); } @@ -67,7 +65,7 @@ public boolean readBool() throws IOException { int val = readi(); if (val != 0 && val != 1) - throw new IOException(String.format(Messages.getString("GmStreamDecoder.INVALID_BOOLEAN"),val)); + throw new IOException(String.format(Messages.getString("GmStreamDecoder.INVALID_BOOLEAN"),val)); //$NON-NLS-1$ if (val == 0) return false; return true; } @@ -125,7 +123,7 @@ public long skip(long length) throws IOException return total; } - public void readTree(ResNode root) throws IOException + public void readTree(ResNode root, Gm6File src) throws IOException { Stack<ResNode> path = new Stack<ResNode>(); Stack<Integer> left = new Stack<Integer>(); @@ -140,7 +138,9 @@ public void readTree(ResNode root) throws IOException ResNode node = path.peek().addChild(name,status,type); if (status == ResNode.STATUS_SECONDARY && type != Resource.GAMEINFO && type != Resource.GAMESETTINGS) { - node.resourceId = LGM.currentFile.getList(node.kind).getUnsafe(ind).Id; + node.resourceId = src.getList(node.kind).getUnsafe(ind).Id; + node.setUserObject(src.getList(node.kind).getUnsafe(ind).name); // GM actually ignores the name given + // in the tree data } int contents = readi(); if (contents > 0) diff --git a/LateralGM/fileRes/ResourceList.java b/LateralGM/fileRes/ResourceList.java index c2be4d732..ac9501f06 100644 --- a/LateralGM/fileRes/ResourceList.java +++ b/LateralGM/fileRes/ResourceList.java @@ -1,12 +1,11 @@ package fileRes; +import java.util.ArrayList; import java.util.Collections; import resourcesRes.ResId; import resourcesRes.Resource; -import java.util.ArrayList; - public class ResourceList<R extends Resource> { private ArrayList<R> Resources = new ArrayList<R>(); @@ -40,6 +39,7 @@ public R add()// Be careful when using this with rooms (they default to LGM.curr { res = (R) type.newInstance(); res.Id.value = ++LastId; + res.name += LastId; Resources.add(res); } catch (Exception e) @@ -149,14 +149,14 @@ public void replace(int SrcIndex, R Replacement) if (SrcIndex >= 0 && SrcIndex < Resources.size() && Replacement != null) Resources.set(SrcIndex,Replacement); } - + public void defragIds() { sort(); - for(int i=0;i<Resources.size();i++) + for (int i = 0; i < Resources.size(); i++) { - Resources.get(i).Id.value=i; + Resources.get(i).Id.value = i; } - LastId=Resources.size()-1; + LastId = Resources.size() - 1; } } \ No newline at end of file diff --git a/LateralGM/mainRes/LGM.java b/LateralGM/mainRes/LGM.java index d42a89c49..01e3cc531 100644 --- a/LateralGM/mainRes/LGM.java +++ b/LateralGM/mainRes/LGM.java @@ -36,6 +36,7 @@ import javax.swing.JSplitPane; import javax.swing.JToolBar; import javax.swing.JTree; +import javax.swing.UIManager; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; @@ -62,8 +63,8 @@ public class LGM extends JPanel public static ResNode root; public static Gm6File currentFile = new Gm6File(); public static JDesktopPane MDI; - public static GameInformationFrame gameInfo = new GameInformationFrame(); - public static GameSettingFrame gameSet = new GameSettingFrame(); + public static GameInformationFrame gameInfo; + public static GameSettingFrame gameSet; public static String[] kinds = { "","Object","Sprite","Sound","Room","","Background","Script","Path", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ "Font","Info","GM","Timeline" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ @@ -136,6 +137,7 @@ public void createTree(ResNode newroot, boolean populate) tree = new JTree(new DefaultTreeModel(root)); GmTreeGraphics renderer = new GmTreeGraphics(); GmTreeEditor editor = new GmTreeEditor(tree,renderer); + editor.addCellEditorListener(listener); tree.setEditable(true); tree.addMouseListener(listener); tree.setScrollsOnExpand(true); @@ -184,6 +186,23 @@ public void createTree(ResNode newroot, boolean populate) // gameInfo.setVisible(true); } + static + { + try + { + UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); + // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + // TODO At some point, add LAF as an option + } + catch (Exception e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + gameInfo = new GameInformationFrame(); + gameSet = new GameSettingFrame(); + } + public static void main(String[] args) { frame.setSize(600,600); diff --git a/LateralGM/mainRes/Prefs.java b/LateralGM/mainRes/Prefs.java index c519d16ab..b365c8549 100644 --- a/LateralGM/mainRes/Prefs.java +++ b/LateralGM/mainRes/Prefs.java @@ -6,7 +6,7 @@ public class Prefs { public static boolean protectRoot = true; public static boolean groupKind = true; - public static boolean protectLeaf = false; + public static boolean protectLeaf = true; public static Font codeFont = new Font("Courier New",Font.PLAIN,12); public static String[] prefixes = { "","obj_","spr_","snd_","rm_","","bk_","scr_","path_","font_","","", "time_" }; diff --git a/LateralGM/resourcesRes/Background.java b/LateralGM/resourcesRes/Background.java index 97f8c6d7e..076f95477 100644 --- a/LateralGM/resourcesRes/Background.java +++ b/LateralGM/resourcesRes/Background.java @@ -21,6 +21,11 @@ public class Background extends Resource public int VertSep = 0; public BufferedImage BackgroundImage = null; + public Background() + { + name = Prefs.prefixes[Resource.BACKGROUND]; + } + public BufferedImage copyBackgroundImage() { if (BackgroundImage != null) diff --git a/LateralGM/resourcesRes/Font.java b/LateralGM/resourcesRes/Font.java index 1d37451c7..ef661087c 100644 --- a/LateralGM/resourcesRes/Font.java +++ b/LateralGM/resourcesRes/Font.java @@ -5,7 +5,6 @@ public class Font extends Resource { - // Fonts may be a problem as they are OS dependent public String FontName = "Arial"; public int Size = 12; public boolean Bold = false; @@ -13,6 +12,11 @@ public class Font extends Resource public int CharRangeMin = 32; public int CharRangeMax = 127; + public Font() + { + name = Prefs.prefixes[Resource.FONT]; + } + public Font copy(boolean update, ResourceList src) { Font font = new Font(); diff --git a/LateralGM/resourcesRes/GmObject.java b/LateralGM/resourcesRes/GmObject.java index 41e838de0..50c36c217 100644 --- a/LateralGM/resourcesRes/GmObject.java +++ b/LateralGM/resourcesRes/GmObject.java @@ -1,10 +1,10 @@ package resourcesRes; import mainRes.Prefs; -import fileRes.ResourceList; import resourcesRes.subRes.Action; import resourcesRes.subRes.Event; import resourcesRes.subRes.MainEvent; +import fileRes.ResourceList; public class GmObject extends Resource { @@ -22,6 +22,7 @@ public class GmObject extends Resource public GmObject() { + name = Prefs.prefixes[Resource.GMOBJECT]; for (int j = 0; j < 11; j++) { MainEvents[j] = new MainEvent(); diff --git a/LateralGM/resourcesRes/Path.java b/LateralGM/resourcesRes/Path.java index ad29f6e83..dc5cdeb9a 100644 --- a/LateralGM/resourcesRes/Path.java +++ b/LateralGM/resourcesRes/Path.java @@ -3,10 +3,8 @@ import java.util.ArrayList; import mainRes.Prefs; - -import fileRes.ResourceList; - import resourcesRes.subRes.Point; +import fileRes.ResourceList; public class Path extends Resource { @@ -18,6 +16,11 @@ public class Path extends Resource public int SnapY = 16; private ArrayList<Point> Points = new ArrayList<Point>(); + public Path() + { + name = Prefs.prefixes[Resource.PATH]; + } + public int NoPoints() { return Points.size(); diff --git a/LateralGM/resourcesRes/Resource.java b/LateralGM/resourcesRes/Resource.java index 33a222ffb..41ea840f0 100644 --- a/LateralGM/resourcesRes/Resource.java +++ b/LateralGM/resourcesRes/Resource.java @@ -2,6 +2,7 @@ import fileRes.ResourceList; +//TODO Implement Resource.equals method public abstract class Resource implements Comparable<Resource> { public static final byte SPRITE = 2; diff --git a/LateralGM/resourcesRes/Room.java b/LateralGM/resourcesRes/Room.java index 9cef58e0d..5e2335509 100644 --- a/LateralGM/resourcesRes/Room.java +++ b/LateralGM/resourcesRes/Room.java @@ -2,15 +2,14 @@ import java.util.ArrayList; -import fileRes.Gm6File; -import fileRes.ResourceList; - import mainRes.LGM; import mainRes.Prefs; import resourcesRes.subRes.BackgroundDef; import resourcesRes.subRes.Instance; import resourcesRes.subRes.Tile; import resourcesRes.subRes.View; +import fileRes.Gm6File; +import fileRes.ResourceList; public class Room extends Resource { @@ -53,6 +52,7 @@ public class Room extends Resource public Room() { + name = Prefs.prefixes[Resource.ROOM]; Parent = LGM.currentFile; for (int j = 0; j < 8; j++) { diff --git a/LateralGM/resourcesRes/Script.java b/LateralGM/resourcesRes/Script.java index deb919752..677008193 100644 --- a/LateralGM/resourcesRes/Script.java +++ b/LateralGM/resourcesRes/Script.java @@ -1,12 +1,17 @@ package resourcesRes; -import fileRes.ResourceList; import mainRes.Prefs; +import fileRes.ResourceList; public class Script extends Resource { public String ScriptStr = ""; + public Script() + { + name = Prefs.prefixes[Resource.SCRIPT]; + } + public Script copy(boolean update, ResourceList src) { Script scr = new Script(); @@ -19,8 +24,8 @@ public Script copy(boolean update, ResourceList src) } else { - scr.Id = scr.Id; - scr.name = scr.name; + scr.Id = Id; + scr.name = name; } return scr; } diff --git a/LateralGM/resourcesRes/Sound.java b/LateralGM/resourcesRes/Sound.java index 621452f78..9d8be1852 100644 --- a/LateralGM/resourcesRes/Sound.java +++ b/LateralGM/resourcesRes/Sound.java @@ -23,6 +23,11 @@ public class Sound extends Resource public boolean Preload = true; public byte[] Data; + public Sound() + { + name = Prefs.prefixes[Resource.SOUND]; + } + public static boolean getReverb(int effects) { if ((effects & 16) == 16) return true; diff --git a/LateralGM/resourcesRes/Sprite.java b/LateralGM/resourcesRes/Sprite.java index 0a9c57093..57c302034 100644 --- a/LateralGM/resourcesRes/Sprite.java +++ b/LateralGM/resourcesRes/Sprite.java @@ -4,11 +4,12 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; + import javax.imageio.ImageIO; -import fileRes.ResourceList; import mainRes.LGM; import mainRes.Prefs; +import fileRes.ResourceList; public class Sprite extends Resource { @@ -31,6 +32,11 @@ public class Sprite extends Resource public int BoundingBoxBottom = 0; private ArrayList<BufferedImage> SubImages = new ArrayList<BufferedImage>(); + public Sprite() + { + name = Prefs.prefixes[Resource.SPRITE]; + } + public int NoSubImages() { return SubImages.size(); diff --git a/LateralGM/resourcesRes/Timeline.java b/LateralGM/resourcesRes/Timeline.java index 835927ecf..69760f86b 100644 --- a/LateralGM/resourcesRes/Timeline.java +++ b/LateralGM/resourcesRes/Timeline.java @@ -3,16 +3,19 @@ import java.util.ArrayList; import mainRes.Prefs; - -import fileRes.ResourceList; - import resourcesRes.subRes.Action; import resourcesRes.subRes.Moment; +import fileRes.ResourceList; public class Timeline extends Resource { private ArrayList<Moment> Moments = new ArrayList<Moment>(); + public Timeline() + { + name = Prefs.prefixes[Resource.TIMELINE]; + } + public int NoMoments() { return Moments.size();
d4d1ccc992dc500518eaf0f50f425a6d2dde2c7c
hadoop
YARN-1424. RMAppA\ttemptImpl should return the- DummyApplicationResourceUsageReport for all invalid accesses. (Ray Chiang via- kasha)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1601745 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt index 3f58ef5b34898..30ed0939a23fa 100644 --- a/hadoop-yarn-project/CHANGES.txt +++ b/hadoop-yarn-project/CHANGES.txt @@ -136,6 +136,10 @@ Release 2.5.0 - UNRELEASED YARN-2030. Augmented RMStateStore with state machine.(Binglin Chang via jianhe) + YARN-1424. RMAppAttemptImpl should return the + DummyApplicationResourceUsageReport for all invalid accesses. + (Ray Chiang via kasha) + OPTIMIZATIONS BUG FIXES diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ApplicationResourceUsageReport.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ApplicationResourceUsageReport.java index 8de9ff3baf143..6e9c76fb01207 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ApplicationResourceUsageReport.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/ApplicationResourceUsageReport.java @@ -47,7 +47,7 @@ public static ApplicationResourceUsageReport newInstance( } /** - * Get the number of used containers + * Get the number of used containers. -1 for invalid/inaccessible reports. * @return the number of used containers */ @Public @@ -63,7 +63,7 @@ public static ApplicationResourceUsageReport newInstance( public abstract void setNumUsedContainers(int num_containers); /** - * Get the number of reserved containers + * Get the number of reserved containers. -1 for invalid/inaccessible reports. * @return the number of reserved containers */ @Private @@ -79,7 +79,7 @@ public static ApplicationResourceUsageReport newInstance( public abstract void setNumReservedContainers(int num_reserved_containers); /** - * Get the used <code>Resource</code> + * Get the used <code>Resource</code>. -1 for invalid/inaccessible reports. * @return the used <code>Resource</code> */ @Public @@ -91,7 +91,7 @@ public static ApplicationResourceUsageReport newInstance( public abstract void setUsedResources(Resource resources); /** - * Get the reserved <code>Resource</code> + * Get the reserved <code>Resource</code>. -1 for invalid/inaccessible reports. * @return the reserved <code>Resource</code> */ @Public @@ -103,7 +103,7 @@ public static ApplicationResourceUsageReport newInstance( public abstract void setReservedResources(Resource reserved_resources); /** - * Get the needed <code>Resource</code> + * Get the needed <code>Resource</code>. -1 for invalid/inaccessible reports. * @return the needed <code>Resource</code> */ @Public diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java index e884d29e3039d..d93c45d0d79e9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/RMServerUtils.java @@ -28,6 +28,7 @@ import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.authorize.AccessControlList; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Resource; @@ -43,6 +44,8 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; +import org.apache.hadoop.yarn.server.utils.BuilderUtils; +import org.apache.hadoop.yarn.util.resource.Resources; /** * Utility methods to aid serving RM data through the REST and RPC APIs @@ -225,4 +228,13 @@ public static YarnApplicationAttemptState createApplicationAttemptState( } } + /** + * Statically defined dummy ApplicationResourceUsageREport. Used as + * a return value when a valid report cannot be found. + */ + public static final ApplicationResourceUsageReport + DUMMY_APPLICATION_RESOURCE_USAGE_REPORT = + BuilderUtils.newApplicationResourceUsageReport(-1, -1, + Resources.createResource(-1, -1), Resources.createResource(-1, -1), + Resources.createResource(-1, -1)); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java index bbd135b9901cd..3318f1582a0e1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/RMAppImpl.java @@ -71,6 +71,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppRemovedSchedulerEvent; +import org.apache.hadoop.yarn.server.resourcemanager.RMServerUtils; import org.apache.hadoop.yarn.server.utils.BuilderUtils; import org.apache.hadoop.yarn.state.InvalidStateTransitonException; import org.apache.hadoop.yarn.state.MultipleArcTransition; @@ -293,11 +294,6 @@ RMAppEventType.KILL, new KillAttemptTransition()) private final StateMachine<RMAppState, RMAppEventType, RMAppEvent> stateMachine; - private static final ApplicationResourceUsageReport - DUMMY_APPLICATION_RESOURCE_USAGE_REPORT = - BuilderUtils.newApplicationResourceUsageReport(-1, -1, - Resources.createResource(-1, -1), Resources.createResource(-1, -1), - Resources.createResource(-1, -1)); private static final int DUMMY_APPLICATION_ATTEMPT_NUMBER = -1; public RMAppImpl(ApplicationId applicationId, RMContext rmContext, @@ -498,7 +494,7 @@ public ApplicationReport createAndGetApplicationReport(String clientUserName, String origTrackingUrl = UNAVAILABLE; int rpcPort = -1; ApplicationResourceUsageReport appUsageReport = - DUMMY_APPLICATION_RESOURCE_USAGE_REPORT; + RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT; FinalApplicationStatus finishState = getFinalApplicationStatus(); String diags = UNAVAILABLE; float progress = 0.0f; diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java index 5b1a17d930b5b..2a1170d41df29 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java @@ -675,9 +675,7 @@ public ApplicationResourceUsageReport getApplicationResourceUsageReport() { ApplicationResourceUsageReport report = scheduler.getAppResourceUsageReport(this.getAppAttemptId()); if (report == null) { - Resource none = Resource.newInstance(0, 0); - report = ApplicationResourceUsageReport.newInstance(0, 0, none, none, - none); + report = RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT; } return report; } finally { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClientRMService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClientRMService.java index 045b5b4ae9478..4b1f59c303903 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClientRMService.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestClientRMService.java @@ -77,6 +77,7 @@ import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; +import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.Container; import org.apache.hadoop.yarn.api.records.ContainerId; @@ -258,6 +259,28 @@ public void testGetApplicationAttemptReport() throws YarnException, } } + @Test + public void testGetApplicationResourceUsageReportDummy() throws YarnException, + IOException { + ApplicationAttemptId attemptId = getApplicationAttemptId(1); + YarnScheduler yarnScheduler = mockYarnScheduler(); + RMContext rmContext = mock(RMContext.class); + mockRMContext(yarnScheduler, rmContext); + when(rmContext.getDispatcher().getEventHandler()).thenReturn( + new EventHandler<Event>() { + public void handle(Event event) { + } + }); + ApplicationSubmissionContext asContext = + mock(ApplicationSubmissionContext.class); + YarnConfiguration config = new YarnConfiguration(); + RMAppAttemptImpl rmAppAttemptImpl = new RMAppAttemptImpl(attemptId, + rmContext, yarnScheduler, null, asContext, config, false); + ApplicationResourceUsageReport report = rmAppAttemptImpl + .getApplicationResourceUsageReport(); + assertEquals(report, RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT); + } + @Test public void testGetApplicationAttempts() throws YarnException, IOException { ClientRMService rmService = createRMService(); @@ -964,6 +987,8 @@ private static YarnScheduler mockYarnScheduler() { Arrays.asList(getApplicationAttemptId(101), getApplicationAttemptId(102))); when(yarnScheduler.getAppsInQueue(QUEUE_2)).thenReturn( Arrays.asList(getApplicationAttemptId(103))); + ApplicationAttemptId attemptId = getApplicationAttemptId(1); + when(yarnScheduler.getAppResourceUsageReport(attemptId)).thenReturn(null); return yarnScheduler; } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/TestRMAppTransitions.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/TestRMAppTransitions.java index e89b71b41056f..0fd3c3c5c99aa 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/TestRMAppTransitions.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/TestRMAppTransitions.java @@ -51,6 +51,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.RMAppManagerEventType; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl; +import org.apache.hadoop.yarn.server.resourcemanager.RMServerUtils; import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationState; @@ -921,6 +922,7 @@ public void testGetAppReport() { assertAppState(RMAppState.NEW, app); ApplicationReport report = app.createAndGetApplicationReport(null, true); Assert.assertNotNull(report.getApplicationResourceUsageReport()); + Assert.assertEquals(report.getApplicationResourceUsageReport(),RMServerUtils.DUMMY_APPLICATION_RESOURCE_USAGE_REPORT); report = app.createAndGetApplicationReport("clientuser", true); Assert.assertNotNull(report.getApplicationResourceUsageReport()); }
9712fd59d05a636575303cecb4aaac62e2134f4d
Vala
Support simple generics for creation methods
a
https://github.com/GNOME/vala/
diff --git a/codegen/valaccodebasemodule.vala b/codegen/valaccodebasemodule.vala index 48d859faf6..2cfc9bbe55 100644 --- a/codegen/valaccodebasemodule.vala +++ b/codegen/valaccodebasemodule.vala @@ -4173,6 +4173,16 @@ public class Vala.CCodeBaseModule : CCodeModule { if (cl != null && !cl.is_compact) { add_generic_type_arguments (carg_map, expr.type_reference.get_type_arguments (), expr); + } else if (cl != null && m.simple_generics) { + int type_param_index = 0; + foreach (var type_arg in expr.type_reference.get_type_arguments ()) { + if (requires_copy (type_arg)) { + carg_map.set (get_param_pos (-1 + 0.1 * type_param_index + 0.03), get_destroy_func_expression (type_arg)); + } else { + carg_map.set (get_param_pos (-1 + 0.1 * type_param_index + 0.03), new CCodeConstant ("NULL")); + } + type_param_index++; + } } bool ellipsis = false;
87498b148f1a29f9538dbdb3728cdc95af7dd1a1
restlet-framework-java
Allowed custom parsing of Atom documents.--
a
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF b/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF index dc50b71c86..97a60d74b3 100644 --- a/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF +++ b/modules/org.restlet.ext.atom/META-INF/MANIFEST.MF @@ -4,8 +4,15 @@ Bundle-Name: Restlet Extension - Atom Bundle-SymbolicName: org.restlet.ext.atom Bundle-Version: 2.0 Bundle-Vendor: Noelios Technologies -Export-Package: org.restlet.ext.atom, - org.restlet.ext.atom.internal +Export-Package: org.restlet.ext.atom; + uses:="org.restlet.data, + org.restlet.resource, + org.restlet.ext.xml, + org.restlet.engine.converter, + org.restlet.representation, + org.restlet.ext.atom.contentHandler, + org.restlet", + org.restlet.ext.atom.contentHandler;uses:="org.restlet.ext.atom,org.xml.sax.helpers,org.xml.sax" Import-Package: org.restlet, org.restlet.data, org.restlet.engine.converter, diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java index cf79d995ca..508c3a54d8 100644 --- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java +++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Entry.java @@ -43,6 +43,7 @@ import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; +import org.restlet.ext.atom.contentHandler.EntryReader; import org.restlet.ext.atom.internal.EntryContentReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; @@ -72,9 +73,6 @@ public class Entry extends SaxRepresentation { /** Permanent, universally unique identifier for the entry. */ private volatile String id; - /** Representation for inline content. */ - private volatile Representation inlineContent; - /** The references from the entry to Web resources. */ private volatile List<Link> links; @@ -95,7 +93,7 @@ public class Entry extends SaxRepresentation { /** Most recent moment when the entry was modified in a significant way. */ private volatile Date updated; - + /** * Constructor. */ @@ -114,6 +112,7 @@ public Entry() { this.title = null; this.updated = null; } + /** * Constructor. * @@ -126,6 +125,7 @@ public Entry() { public Entry(Client clientDispatcher, String entryUri) throws IOException { this(clientDispatcher.get(entryUri).getEntity()); } + /** * Constructor. * @@ -152,6 +152,21 @@ public Entry(Representation xmlEntry) throws IOException { parse(new EntryContentReader(this)); } + /** + * Constructor. + * + * @param xmlEntry + * The XML entry document. + * @param entryReader + * Custom entry reader. + * @throws IOException + */ + public Entry(Representation xmlEntry, EntryReader entryReader) + throws IOException { + super(xmlEntry); + parse(new EntryContentReader(this, entryReader)); + } + /** * Constructor. * @@ -238,15 +253,6 @@ public String getId() { return this.id; } - /** - * Returns the representation for inline content. - * - * @return The representation for inline content. - */ - public Representation getInlineContent() { - return this.inlineContent; - } - /** * Returns the first available link with a given relation type. * @@ -369,16 +375,6 @@ public void setId(String id) { this.id = id; } - /** - * Sets the representation for inline content. - * - * @param inlineContent - * The representation for inline content. - */ - public void setInlineContent(Representation inlineContent) { - this.inlineContent = inlineContent; - } - /** * Sets the moment associated with an event early in the life cycle of the * entry. diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java index 6d1f6af47f..de7d592b52 100644 --- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java +++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/Feed.java @@ -40,13 +40,13 @@ import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.engine.util.DateUtils; +import org.restlet.ext.atom.contentHandler.FeedReader; import org.restlet.ext.atom.internal.FeedContentReader; import org.restlet.ext.xml.SaxRepresentation; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.Representation; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; -import org.xml.sax.helpers.DefaultHandler; /** * Atom Feed Document, acting as a component for metadata and data associated @@ -173,12 +173,14 @@ public Feed(Representation xmlFeed) throws IOException { * * @param xmlFeed * The XML feed document. + * @param feedReader + * Custom feed reader. * @throws IOException */ - public Feed(Representation xmlFeed, DefaultHandler extraFeedHandler, - DefaultHandler extraEntryHandler) throws IOException { + public Feed(Representation xmlFeed, FeedReader feedReader) + throws IOException { super(xmlFeed); - parse(new FeedContentReader(this, extraFeedHandler, extraEntryHandler)); + parse(new FeedContentReader(this, feedReader)); } /** @@ -374,18 +376,6 @@ public Date getUpdated() { return this.updated; } - /** - * Sets the base URI used to resolve relative references found within the - * scope of the xml:base attribute. - * - * @param baseUri - * The base URI used to resolve relative references found within - * the scope of the xml:base attribute. - */ - public void setBaseReference(String baseUri) { - setBaseReference(new Reference(baseUri)); - } - /** * Sets the base reference used to resolve relative references found within * the scope of the xml:base attribute. @@ -398,6 +388,18 @@ public void setBaseReference(Reference baseReference) { this.baseReference = baseReference; } + /** + * Sets the base URI used to resolve relative references found within the + * scope of the xml:base attribute. + * + * @param baseUri + * The base URI used to resolve relative references found within + * the scope of the xml:base attribute. + */ + public void setBaseReference(String baseUri) { + setBaseReference(new Reference(baseUri)); + } + /** * Sets the agent used to generate a feed. * diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/EntryReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/EntryReader.java new file mode 100644 index 0000000000..d89a38f852 --- /dev/null +++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/EntryReader.java @@ -0,0 +1,299 @@ +/** + * Copyright 2005-2010 Noelios Technologies. + * + * The contents of this file are subject to the terms of one of the following + * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or CDL 1.0 (the + * "Licenses"). You can select the license that you prefer but you may not use + * this file except in compliance with one of these Licenses. + * + * You can obtain a copy of the LGPL 3.0 license at + * http://www.opensource.org/licenses/lgpl-3.0.html + * + * You can obtain a copy of the LGPL 2.1 license at + * http://www.opensource.org/licenses/lgpl-2.1.php + * + * You can obtain a copy of the CDDL 1.0 license at + * http://www.opensource.org/licenses/cddl1.php + * + * You can obtain a copy of the EPL 1.0 license at + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * See the Licenses for the specific language governing permissions and + * limitations under the Licenses. + * + * Alternatively, you can obtain a royalty free commercial license with less + * limitations, transferable or non-transferable, directly at + * http://www.noelios.com/products/restlet-engine + * + * Restlet is a registered trademark of Noelios Technologies. + */ + +package org.restlet.ext.atom.contentHandler; + +import java.io.IOException; + +import org.restlet.ext.atom.Content; +import org.restlet.ext.atom.Entry; +import org.restlet.ext.atom.Link; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Content reader for entries that is able to transmit events to another + * EntryReader. + * + * @author Thierry Boileau + */ +public class EntryReader extends DefaultHandler { + + /** Extra entry reader. */ + private EntryReader entryReader; + + /** + * Constructor. + */ + public EntryReader() { + super(); + } + + /** + * Constructor. + * + * @param entryReader + * Additional feed reader that will receive all events. + */ + public EntryReader(EntryReader entryReader) { + super(); + this.entryReader = entryReader; + } + + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.characters(ch, start, length); + } + } + + /** + * Called at the end of the XML block that defines the given content + * element. By default, it relays the event to the extra handler. + * + * @param content + * The current content element. + */ + public void endContent(Content content) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.endContent(content); + } + } + + @Override + public void endDocument() throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.endDocument(); + } + } + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.endElement(uri, localName, qName); + } + } + + /** + * Called at the end of the XML block that defines the given entry. + * + * @param entry + * The current entry. + */ + public void endEntry(Entry entry) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.endEntry(entry); + } + } + + /** + * Called at the end of the XML block that defines the given link. + * + * @param link + * The current link. + */ + public void endLink(Link link) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.endLink(link); + } + } + + @Override + public void endPrefixMapping(String prefix) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.endPrefixMapping(prefix); + } + } + + @Override + public void error(SAXParseException e) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.error(e); + } + } + + @Override + public void fatalError(SAXParseException e) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.fatalError(e); + } + } + + @Override + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.ignorableWhitespace(ch, start, length); + } + } + + @Override + public void notationDecl(String name, String publicId, String systemId) + throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.notationDecl(name, publicId, systemId); + } + } + + @Override + public void processingInstruction(String target, String data) + throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.processingInstruction(target, data); + } + } + + @Override + public InputSource resolveEntity(String publicId, String systemId) + throws IOException, SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + return this.entryReader.resolveEntity(publicId, systemId); + } + return null; + } + + @Override + public void setDocumentLocator(Locator locator) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.setDocumentLocator(locator); + } + } + + @Override + public void skippedEntity(String name) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.skippedEntity(name); + } + } + + /** + * Called when a new content element has been detected in the Atom document. + * + * @param content + * The current content element. + */ + public void startContent(Content content) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.startContent(content); + } + } + + @Override + public void startDocument() throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.startDocument(); + } + } + + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.startElement(uri, localName, qName, attributes); + } + } + + /** + * Called when a new entry has been detected in the Atom document. + * + * @param entry + * The current entry. + */ + public void startEntry(Entry entry) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.startEntry(entry); + } + } + + /** + * Called when a new link has been detected in the Atom document. + * + * @param link + * The current link. + */ + public void startLink(Link link) { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.startLink(link); + } + } + + @Override + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.startPrefixMapping(prefix, uri); + } + } + + @Override + public void unparsedEntityDecl(String name, String publicId, + String systemId, String notationName) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.unparsedEntityDecl(name, publicId, systemId, + notationName); + } + } + + @Override + public void warning(SAXParseException e) throws SAXException { + // Send the event to the extra handler. + if (this.entryReader != null) { + this.entryReader.warning(e); + } + } +} diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/FeedReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/FeedReader.java new file mode 100644 index 0000000000..3e59c101a1 --- /dev/null +++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/contentHandler/FeedReader.java @@ -0,0 +1,326 @@ +/** + * Copyright 2005-2010 Noelios Technologies. + * + * The contents of this file are subject to the terms of one of the following + * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or CDL 1.0 (the + * "Licenses"). You can select the license that you prefer but you may not use + * this file except in compliance with one of these Licenses. + * + * You can obtain a copy of the LGPL 3.0 license at + * http://www.opensource.org/licenses/lgpl-3.0.html + * + * You can obtain a copy of the LGPL 2.1 license at + * http://www.opensource.org/licenses/lgpl-2.1.php + * + * You can obtain a copy of the CDDL 1.0 license at + * http://www.opensource.org/licenses/cddl1.php + * + * You can obtain a copy of the EPL 1.0 license at + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * See the Licenses for the specific language governing permissions and + * limitations under the Licenses. + * + * Alternatively, you can obtain a royalty free commercial license with less + * limitations, transferable or non-transferable, directly at + * http://www.noelios.com/products/restlet-engine + * + * Restlet is a registered trademark of Noelios Technologies. + */ + +package org.restlet.ext.atom.contentHandler; + +import java.io.IOException; + +import org.restlet.ext.atom.Content; +import org.restlet.ext.atom.Entry; +import org.restlet.ext.atom.Feed; +import org.restlet.ext.atom.Link; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.helpers.DefaultHandler; + +/** + * Content reader for feeds that is able to transmit events to another + * FeedReader. + * + * @author Thierry Boileau + */ +public class FeedReader extends DefaultHandler { + + /** Extra feed reader. */ + private FeedReader feedReader; + + /** + * Constructor. + */ + public FeedReader() { + super(); + } + + /** + * Constructor. + * + * @param feedReader + * Additional feed reader that will receive all events. + */ + public FeedReader(FeedReader feedReader) { + super(); + this.feedReader = feedReader; + } + + @Override + public void characters(char[] ch, int start, int length) + throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.characters(ch, start, length); + } + } + + /** + * Called at the end of the XML block that defines the given content + * element. By default, it relays the event to the extra handler. + * + * @param content + * The current content element. + */ + public void endContent(Content content) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endContent(content); + } + } + + @Override + public void endDocument() throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endDocument(); + } + } + + @Override + public void endElement(String uri, String localName, String qName) + throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endElement(uri, localName, qName); + } + } + + /** + * Called at the end of the XML block that defines the given entry. + * + * @param entry + * The current entry. + */ + public void endEntry(Entry entry) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endEntry(entry); + } + } + + /** + * Called at the end of the XML block that defines the given feed. + * + * @param feed + * The current feed. + */ + public void endFeed(Feed feed) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endFeed(feed); + } + } + + /** + * Called at the end of the XML block that defines the given link. + * + * @param link + * The current link. + */ + public void endLink(Link link) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endLink(link); + } + } + + @Override + public void endPrefixMapping(String prefix) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.endPrefixMapping(prefix); + } + } + + @Override + public void error(SAXParseException e) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.error(e); + } + } + + @Override + public void fatalError(SAXParseException e) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.fatalError(e); + } + } + + @Override + public void ignorableWhitespace(char[] ch, int start, int length) + throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.ignorableWhitespace(ch, start, length); + } + } + + @Override + public void notationDecl(String name, String publicId, String systemId) + throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.notationDecl(name, publicId, systemId); + } + } + + @Override + public void processingInstruction(String target, String data) + throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.processingInstruction(target, data); + } + } + + @Override + public InputSource resolveEntity(String publicId, String systemId) + throws IOException, SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + return this.feedReader.resolveEntity(publicId, systemId); + } + return null; + } + + @Override + public void setDocumentLocator(Locator locator) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.setDocumentLocator(locator); + } + } + + @Override + public void skippedEntity(String name) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.skippedEntity(name); + } + } + + /** + * Called when a new content element has been detected in the Atom document. + * + * @param content + * The current content element. + */ + public void startContent(Content content) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startContent(content); + } + } + + @Override + public void startDocument() throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startDocument(); + } + } + + @Override + public void startElement(String uri, String localName, String qName, + Attributes attributes) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startElement(uri, localName, qName, attributes); + } + } + + /** + * Called when a new entry has been detected in the Atom document. + * + * @param entry + * The current entry. + */ + public void startEntry(Entry entry) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startEntry(entry); + } + } + + /** + * Called when a new feed has been detected in the Atom document. + * + * @param feed + * The current feed. + */ + public void startFeed(Feed feed) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startFeed(feed); + } + } + + /** + * Called when a new link has been detected in the Atom document. + * + * @param link + * The current link. + */ + public void startLink(Link link) { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startLink(link); + } + } + + @Override + public void startPrefixMapping(String prefix, String uri) + throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.startPrefixMapping(prefix, uri); + } + } + + @Override + public void unparsedEntityDecl(String name, String publicId, + String systemId, String notationName) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.unparsedEntityDecl(name, publicId, systemId, notationName); + } + } + + @Override + public void warning(SAXParseException e) throws SAXException { + // Send the event to the extra handler. + if (this.feedReader != null) { + this.feedReader.warning(e); + } + } + +} diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java index 9a0eddb853..fb257a4f05 100644 --- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java +++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/EntryContentReader.java @@ -47,18 +47,18 @@ import org.restlet.ext.atom.Person; import org.restlet.ext.atom.Relation; import org.restlet.ext.atom.Text; +import org.restlet.ext.atom.contentHandler.EntryReader; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.StringRepresentation; import org.xml.sax.Attributes; import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; /** * Content reader for entries. * * @author Jerome Louvel */ -public class EntryContentReader extends DefaultHandler { +public class EntryContentReader extends EntryReader { private enum State { FEED_ENTRY, FEED_ENTRY_AUTHOR, FEED_ENTRY_AUTHOR_EMAIL, FEED_ENTRY_AUTHOR_NAME, FEED_ENTRY_AUTHOR_URI, FEED_ENTRY_CATEGORY, FEED_ENTRY_CONTENT, FEED_ENTRY_CONTRIBUTOR, FEED_ENTRY_ID, FEED_ENTRY_LINK, FEED_ENTRY_PUBLISHED, FEED_ENTRY_RIGHTS, FEED_ENTRY_SOURCE, FEED_ENTRY_SOURCE_AUTHOR, FEED_ENTRY_SOURCE_AUTHOR_EMAIL, FEED_ENTRY_SOURCE_AUTHOR_NAME, FEED_ENTRY_SOURCE_AUTHOR_URI, FEED_ENTRY_SOURCE_CATEGORY, FEED_ENTRY_SOURCE_CONTRIBUTOR, FEED_ENTRY_SOURCE_GENERATOR, FEED_ENTRY_SOURCE_ICON, FEED_ENTRY_SOURCE_ID, FEED_ENTRY_SOURCE_LINK, FEED_ENTRY_SOURCE_LOGO, FEED_ENTRY_SOURCE_RIGHTS, FEED_ENTRY_SOURCE_SUBTITLE, FEED_ENTRY_SOURCE_TITLE, FEED_ENTRY_SOURCE_UPDATED, FEED_ENTRY_SUMMARY, FEED_ENTRY_TITLE, FEED_ENTRY_UPDATED, NONE } @@ -106,6 +106,16 @@ private enum State { * The entry object to update during the parsing. */ public EntryContentReader(Entry entry) { + this(entry, null); + } + + /** + * Constructor. + * @param entry The entry object to update during the parsing. + * @param extraEntryHandler Custom handler of all events. + */ + public EntryContentReader(Entry entry, EntryReader extraEntryHandler) { + super(extraEntryHandler); this.state = State.NONE; this.contentDepth = -1; this.currentEntry = entry; @@ -130,12 +140,16 @@ public void characters(char[] ch, int start, int length) } else { this.contentBuffer.append(ch, start, length); } + + super.characters(ch, start, length); } @Override public void endDocument() throws SAXException { this.state = State.NONE; this.contentBuffer = null; + + super.endDocument(); } @Override @@ -243,6 +257,10 @@ public void endElement(String uri, String localName, String qName) } this.currentContentWriter = null; } + endLink(this.currentLink); + } else if (localName.equalsIgnoreCase("entry")) { + this.state = State.NONE; + endEntry(this.currentEntry); } else if (localName.equals("category")) { if (this.state == State.FEED_ENTRY_CATEGORY) { this.currentEntry.getCategories().add(this.currentCategory); @@ -270,45 +288,19 @@ public void endElement(String uri, String localName, String qName) this.state = State.FEED_ENTRY; } this.currentContentWriter = null; - } - } else if (this.state == State.FEED_ENTRY) { - // Set the inline content, if any - if (this.currentContentWriter != null) { - this.currentContentWriter.endElement(uri, localName, qName); - String content = this.currentContentWriter.getWriter() - .toString().trim(); - contentDepth = -1; - if ("".equals(content)) { - this.currentEntry.setInlineContent(null); - } else { - this.currentEntry - .setInlineContent(new StringRepresentation(content)); - } - this.currentContentWriter = null; + endContent(this.currentContent); } } this.currentText = null; this.currentDate = null; - } - - /** - * Initiates the parsing of a mixed content part of the current document. - */ - private void initiateInlineMixedContent() { - this.contentDepth = 0; - StringWriter sw = new StringWriter(); - currentContentWriter = new XmlWriter(sw); - - for (String prefix : this.prefixMappings.keySet()) { - currentContentWriter.forceNSDecl(this.prefixMappings.get(prefix), - prefix); - } + super.endElement(uri, localName, qName); } @Override public void endPrefixMapping(String prefix) throws SAXException { this.prefixMappings.remove(prefix); + super.endPrefixMapping(prefix); } /** @@ -336,9 +328,24 @@ private MediaType getMediaType(String type) { return result; } + /** + * Initiates the parsing of a mixed content part of the current document. + */ + private void initiateInlineMixedContent() { + this.contentDepth = 0; + StringWriter sw = new StringWriter(); + currentContentWriter = new XmlWriter(sw); + + for (String prefix : this.prefixMappings.keySet()) { + currentContentWriter.forceNSDecl(this.prefixMappings.get(prefix), + prefix); + } + } + @Override public void startDocument() throws SAXException { this.contentBuffer = new StringBuilder(); + super.startDocument(); } @Override @@ -423,8 +430,10 @@ public void startElement(String uri, String localName, String qName, // Content available inline initiateInlineMixedContent(); this.currentLink.setContent(currentContent); + startLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { this.state = State.FEED_ENTRY; + startEntry(this.currentEntry); } else if (localName.equals("category")) { this.currentCategory = new Category(); this.currentCategory.setTerm(attrs.getValue("", "term")); @@ -457,19 +466,19 @@ public void startElement(String uri, String localName, String qName, this.currentEntry.setContent(currentContent); this.state = State.FEED_ENTRY_CONTENT; } + startContent(this.currentContent); } - } else if (this.state == State.FEED_ENTRY) { - // Content available inline - initiateInlineMixedContent(); - this.currentContentWriter - .startElement(uri, localName, qName, attrs); } + + super.startElement(uri, localName, qName, attrs); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { this.prefixMappings.put(prefix, uri); + + super.startPrefixMapping(prefix, uri); } /** diff --git a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java index 588f58fe23..93a61e5610 100644 --- a/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java +++ b/modules/org.restlet.ext.atom/src/org/restlet/ext/atom/internal/FeedContentReader.java @@ -47,18 +47,18 @@ import org.restlet.ext.atom.Person; import org.restlet.ext.atom.Relation; import org.restlet.ext.atom.Text; +import org.restlet.ext.atom.contentHandler.FeedReader; import org.restlet.ext.xml.XmlWriter; import org.restlet.representation.StringRepresentation; import org.xml.sax.Attributes; import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; /** * Content reader for feeds. * * @author Thierry Boileau */ -public class FeedContentReader extends DefaultHandler { +public class FeedContentReader extends FeedReader { private enum State { FEED, FEED_AUTHOR, FEED_AUTHOR_EMAIL, FEED_AUTHOR_NAME, FEED_AUTHOR_URI, FEED_CATEGORY, FEED_CONTRIBUTOR, FEED_CONTRIBUTOR_EMAIL, FEED_CONTRIBUTOR_NAME, FEED_CONTRIBUTOR_URI, FEED_ENTRY, FEED_ENTRY_AUTHOR, FEED_ENTRY_AUTHOR_EMAIL, FEED_ENTRY_AUTHOR_NAME, FEED_ENTRY_AUTHOR_URI, FEED_ENTRY_CATEGORY, FEED_ENTRY_CONTENT, FEED_ENTRY_CONTRIBUTOR, FEED_ENTRY_ID, FEED_ENTRY_LINK, FEED_ENTRY_PUBLISHED, FEED_ENTRY_RIGHTS, FEED_ENTRY_SOURCE, FEED_ENTRY_SOURCE_AUTHOR, FEED_ENTRY_SOURCE_AUTHOR_EMAIL, FEED_ENTRY_SOURCE_AUTHOR_NAME, FEED_ENTRY_SOURCE_AUTHOR_URI, FEED_ENTRY_SOURCE_CATEGORY, FEED_ENTRY_SOURCE_CONTRIBUTOR, FEED_ENTRY_SOURCE_GENERATOR, FEED_ENTRY_SOURCE_ICON, FEED_ENTRY_SOURCE_ID, FEED_ENTRY_SOURCE_LINK, FEED_ENTRY_SOURCE_LOGO, FEED_ENTRY_SOURCE_RIGHTS, FEED_ENTRY_SOURCE_SUBTITLE, FEED_ENTRY_SOURCE_TITLE, FEED_ENTRY_SOURCE_UPDATED, FEED_ENTRY_SUMMARY, FEED_ENTRY_TITLE, FEED_ENTRY_UPDATED, FEED_GENERATOR, FEED_ICON, FEED_ID, FEED_LINK, FEED_LOGO, FEED_RIGHTS, FEED_SUBTITLE, FEED_TITLE, FEED_UPDATED, NONE } @@ -96,15 +96,6 @@ private enum State { /** The currently parsed Text. */ private Text currentText; - /** Extra content handler that will be notified of Entry events. */ - private DefaultHandler extraEntryHandler; - - /** Extra content handler that will be notified of Feed events. */ - private DefaultHandler extraFeedHandler; - - /** Indicates if the current event is dedicated to an entry or a feed. */ - private boolean parsingEntry = false; - /** The current list of prefix mappings. */ private Map<String, String> prefixMappings; @@ -118,6 +109,19 @@ private enum State { * The feed object to update during the parsing. */ public FeedContentReader(Feed feed) { + this(feed, null); + } + + /** + * Constructor. + * + * @param feed + * The feed object to update during the parsing. + * @param extraFeedReader + * Custom handler of all events. + */ + public FeedContentReader(Feed feed, FeedReader extraFeedReader) { + super(extraFeedReader); this.state = State.NONE; this.currentFeed = feed; this.currentEntry = null; @@ -132,19 +136,6 @@ public FeedContentReader(Feed feed) { this.contentDepth = -1; } - /** - * Constructor. - * - * @param feed - * The feed object to update during the parsing. - */ - public FeedContentReader(Feed feed, DefaultHandler extraFeedHandler, - DefaultHandler extraEntryHandler) { - this(feed); - this.extraFeedHandler = extraFeedHandler; - this.extraEntryHandler = extraEntryHandler; - } - @Override public void characters(char[] ch, int start, int length) throws SAXException { @@ -156,17 +147,7 @@ public void characters(char[] ch, int start, int length) } else { this.contentBuffer.append(ch, start, length); } - - // Send the event to the right extra handler. - if (parsingEntry) { - if (this.extraEntryHandler != null) { - this.extraEntryHandler.characters(ch, start, length); - } - } else { - if (this.extraFeedHandler != null) { - this.extraFeedHandler.characters(ch, start, length); - } - } + super.characters(ch, start, length); } @Override @@ -175,13 +156,7 @@ public void endDocument() throws SAXException { this.currentEntry = null; this.contentBuffer = null; - // Send the event to the extra handlers. - if (this.extraEntryHandler != null) { - this.extraEntryHandler.endDocument(); - } - if (this.extraFeedHandler != null) { - this.extraFeedHandler.endDocument(); - } + super.endDocument(); } @Override @@ -212,6 +187,7 @@ public void endElement(String uri, String localName, String qName) } else if (uri.equalsIgnoreCase(Feed.ATOM_NAMESPACE)) { if (localName.equals("feed")) { this.state = State.NONE; + endFeed(this.currentFeed); } else if (localName.equals("title")) { if (this.state == State.FEED_TITLE) { this.currentFeed.setTitle(this.currentText); @@ -305,12 +281,13 @@ public void endElement(String uri, String localName, String qName) } this.currentContentWriter = null; } + endLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { if (this.state == State.FEED_ENTRY) { this.currentFeed.getEntries().add(this.currentEntry); this.state = State.FEED; - this.parsingEntry = false; } + endEntry(this.currentEntry); } else if (localName.equals("category")) { if (this.state == State.FEED_CATEGORY) { this.currentFeed.getCategories().add(this.currentCategory); @@ -341,37 +318,13 @@ public void endElement(String uri, String localName, String qName) this.state = State.FEED_ENTRY; } this.currentContentWriter = null; - } - } else if (this.state == State.FEED_ENTRY) { - // Set the inline content, if any - if (this.currentContentWriter != null) { - this.currentContentWriter.endElement(uri, localName, qName); - String content = this.currentContentWriter.getWriter() - .toString().trim(); - contentDepth = -1; - if ("".equals(content)) { - this.currentEntry.setInlineContent(null); - } else { - this.currentEntry - .setInlineContent(new StringRepresentation(content)); - } - this.currentContentWriter = null; + endContent(this.currentContent); } } this.currentText = null; this.currentDate = null; - - // Send the event to the right extra handler. - if (parsingEntry) { - if (this.extraEntryHandler != null) { - this.extraEntryHandler.endElement(uri, localName, qName); - } - } else { - if (this.extraFeedHandler != null) { - this.extraFeedHandler.endElement(uri, localName, qName); - } - } + super.endElement(uri, localName, qName); } @Override @@ -379,15 +332,7 @@ public void endPrefixMapping(String prefix) throws SAXException { this.prefixMappings.remove(prefix); // Send the event to the right extra handler. - if (parsingEntry) { - if (this.extraEntryHandler != null) { - this.extraEntryHandler.endPrefixMapping(prefix); - } - } else { - if (this.extraFeedHandler != null) { - this.extraFeedHandler.endPrefixMapping(prefix); - } - } + super.endPrefixMapping(prefix); } /** @@ -432,14 +377,7 @@ private void initiateInlineMixedContent() { @Override public void startDocument() throws SAXException { this.contentBuffer = new StringBuilder(); - - // Send the event to the extra handlers. - if (this.extraEntryHandler != null) { - this.extraEntryHandler.startDocument(); - } - if (this.extraFeedHandler != null) { - this.extraFeedHandler.startDocument(); - } + super.startDocument(); } @Override @@ -461,6 +399,7 @@ public void startElement(String uri, String localName, String qName, this.currentFeed.setBaseReference(new Reference(attr)); } this.state = State.FEED; + startFeed(this.currentFeed); } else if (localName.equals("title")) { startTextElement(attrs); @@ -543,12 +482,13 @@ public void startElement(String uri, String localName, String qName, // Content available inline initiateInlineMixedContent(); this.currentLink.setContent(currentContent); + startLink(this.currentLink); } else if (localName.equalsIgnoreCase("entry")) { if (this.state == State.FEED) { this.currentEntry = new Entry(); this.state = State.FEED_ENTRY; - this.parsingEntry = true; } + startEntry(this.currentEntry); } else if (localName.equals("category")) { this.currentCategory = new Category(); this.currentCategory.setTerm(attrs.getValue("", "term")); @@ -583,26 +523,11 @@ public void startElement(String uri, String localName, String qName, this.currentEntry.setContent(currentContent); this.state = State.FEED_ENTRY_CONTENT; } + startContent(this.currentContent); } - } else if (this.state == State.FEED_ENTRY) { - // Content available inline - initiateInlineMixedContent(); - this.currentContentWriter - .startElement(uri, localName, qName, attrs); } - // Send the event to the right extra handler. - if (parsingEntry) { - if (this.extraEntryHandler != null) { - this.extraEntryHandler.startElement(uri, localName, qName, - attrs); - } - } else { - if (this.extraFeedHandler != null) { - this.extraFeedHandler - .startElement(uri, localName, qName, attrs); - } - } + super.startElement(uri, localName, qName, attrs); } @Override @@ -610,16 +535,7 @@ public void startPrefixMapping(String prefix, String uri) throws SAXException { this.prefixMappings.put(prefix, uri); - // Send the event to the right extra handler. - if (parsingEntry) { - if (this.extraEntryHandler != null) { - this.extraEntryHandler.startPrefixMapping(prefix, uri); - } - } else { - if (this.extraFeedHandler != null) { - this.extraFeedHandler.startPrefixMapping(prefix, uri); - } - } + super.startPrefixMapping(prefix, uri); } /** @@ -631,4 +547,5 @@ public void startPrefixMapping(String prefix, String uri) public void startTextElement(Attributes attrs) { this.currentText = new Text(getMediaType(attrs.getValue("", "type"))); } + } \ No newline at end of file
125562e7f4ee0b404f84491fffead5baaf9745ab
Vala
Make argument of NullType constructor nullable
c
https://github.com/GNOME/vala/
diff --git a/vala/valanulltype.vala b/vala/valanulltype.vala index cbe0419535..ca2bce61f7 100644 --- a/vala/valanulltype.vala +++ b/vala/valanulltype.vala @@ -26,7 +26,7 @@ using GLib; * The type of the null literal. */ public class Vala.NullType : ReferenceType { - public NullType (SourceReference source_reference) { + public NullType (SourceReference? source_reference) { this.nullable = true; this.source_reference = source_reference; }
621bcfcdaabb8d99af5547948aa46c06bfeec0c4
eclipse$rmf
moved functionality from StringFilter to abstract TextFilter
p
https://github.com/eclipse-rmf/org.eclipse.rmf
diff --git a/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/StringFilterTest.java b/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/StringFilterTest.java index 379fd35a..cb6bc647 100644 --- a/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/StringFilterTest.java +++ b/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/StringFilterTest.java @@ -25,10 +25,10 @@ import org.eclipse.rmf.reqif10.SpecObject; import org.eclipse.rmf.reqif10.Specification; import org.eclipse.rmf.reqif10.pror.testframework.AbstractItemProviderTest; +import org.eclipse.rmf.reqif10.search.filter.AbstractTextFilter.InternalAttribute; import org.eclipse.rmf.reqif10.search.filter.IFilter; import org.eclipse.rmf.reqif10.search.filter.IFilter.Operator; import org.eclipse.rmf.reqif10.search.filter.StringFilter; -import org.eclipse.rmf.reqif10.search.filter.StringFilter.InternalAttribute; import org.eclipse.rmf.reqif10.search.testdata.TestData; import org.junit.Before; import org.junit.Rule; @@ -49,11 +49,15 @@ public void init(){ } - @Test public void testEquals() throws Exception { - StringFilter stringFilter = new StringFilter(IFilter.Operator.EQUALS, "abcDEF", attributeDefinition, true); - assertTrue(stringFilter.match(specObject)); + StringFilter stringFilter; + try{ + stringFilter = new StringFilter(IFilter.Operator.EQUALS, "abcDEF", attributeDefinition, true); + assertTrue(stringFilter.match(specObject)); + }catch (Exception e) { + e.printStackTrace(); + } stringFilter = new StringFilter(IFilter.Operator.EQUALS, "abcDEF", attributeDefinition, false); assertTrue(stringFilter.match(specObject)); @@ -100,7 +104,18 @@ public void testNotContains() throws Exception { @Test public void testRegExp() throws Exception { - fail("Not yet implemented"); + StringFilter stringFilter; + + stringFilter= new StringFilter(IFilter.Operator.REGEXP, ".*b.*", attributeDefinition, true); + assertTrue(stringFilter.match(specObject)); + + stringFilter= new StringFilter(IFilter.Operator.REGEXP, ".*ABC.*", attributeDefinition, true); + assertFalse(stringFilter.match(specObject)); + + stringFilter= new StringFilter(IFilter.Operator.REGEXP, ".*ABC.*", attributeDefinition, false); + assertTrue(stringFilter.match(specObject)); + + //fail("Not yet implemented"); } @Test @@ -162,6 +177,13 @@ public void testExceptionsUnsupportedOperation() throws Exception { new StringFilter(IFilter.Operator.BEFORE, "abcdef", attributeDefinition, false); } + @Test + public void testExceptionsUnsupportedOperation2() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage(Operator.REGEXP_PLAIN.toString()); + new StringFilter(IFilter.Operator.REGEXP_PLAIN, "abcdef", attributeDefinition, false); + } + @Test public void testHowtoLoadAReqif() throws Exception { diff --git a/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/AbstractTextFilter.java b/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/AbstractTextFilter.java new file mode 100644 index 00000000..45f45049 --- /dev/null +++ b/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/AbstractTextFilter.java @@ -0,0 +1,214 @@ +/******************************************************************************* + * Copyright (c) 2014 Formal Mind GmbH. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Ingo Weigelt - initial API and implementation + * Michael Jastram - adding SUPPORTED_OPERATIONS + ******************************************************************************/ +package org.eclipse.rmf.reqif10.search.filter; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.rmf.reqif10.AttributeDefinition; +import org.eclipse.rmf.reqif10.AttributeDefinitionString; +import org.eclipse.rmf.reqif10.AttributeValue; +import org.eclipse.rmf.reqif10.AttributeValueString; +import org.eclipse.rmf.reqif10.SpecElementWithAttributes; +import org.eclipse.rmf.reqif10.common.util.ReqIF10Util; +import org.eclipse.rmf.reqif10.search.filter.IFilter.Operator; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + +/** + * Filter for String-based values. + */ +public abstract class AbstractTextFilter implements IFilter { + + public enum InternalAttribute { + IDENTIFIER, DESC, LONG_NAME + } + + // TODO cross-check this with supported operators. + public static final ImmutableSet<Operator> SUPPORTED_OPERATORS = Sets + .immutableEnumSet(Operator.EQUALS, Operator.NOT_EQUALS, + Operator.CONTAINS, Operator.NOT_CONTAINS, Operator.REGEXP); + + protected Operator operator; + protected String filterValue; + protected AttributeDefinition attributeDefinition; + protected InternalAttribute internalAttribute; + protected boolean caseSensitive; + protected boolean isInternal; + + + /** + * Constructor used to create a filter for an {@link AttributeDefinitionString} + * + * @param operator the filter operator to use + * @param value the value to match + * @param attributeDefinition the attributeDefinition that defines the value of a SpecObject that should be matched + * @param caseSensitive + */ + public AbstractTextFilter(Operator operator, String value, + AttributeDefinition attributeDefinition, boolean caseSensitive) { + this(operator, value, null, attributeDefinition, caseSensitive); + this.isInternal = false; + if (null == attributeDefinition){ + throw new IllegalArgumentException("AttributeDefinition can not be null"); + } + } + + /** + * Constructor used to create a filter for an {@link InternalAttribute} + * + * @param operator the filter operator to use + * @param value the value to match + * @param attributeDefinition the attributeDefinition that defines the value of a SpecObject that should be matched + * @param caseSensitive + */ + public AbstractTextFilter(Operator operator, String value, + InternalAttribute internalFeature, boolean caseSensitive) { + this(operator, value, internalFeature, null, caseSensitive); + this.isInternal = true; + if (null == internalFeature){ + throw new IllegalArgumentException("AttributeDefinition can not be null"); + } + } + + + protected AbstractTextFilter(Operator operator, String value, + InternalAttribute internalFeature, AttributeDefinition attributeDefinition, boolean caseSensitive){ + + if (!getSupportedOperators().contains(operator)){ + throw new IllegalArgumentException( + "This filter does not support the " + operator.toString() + + " operation"); + } + if (null == value){ + throw new IllegalArgumentException( + "Value can not be null"); + } + + if (internalFeature != null && attributeDefinition == null){ + isInternal = true; + }else if(attributeDefinition != null && internalFeature == null){ + isInternal = false; + }else{ + throw new IllegalArgumentException( + "internalFeature and attribute definition can not be null or set at the same time"); + } + + this.operator = operator; + this.filterValue = (null == value ? "" : value); + this.internalAttribute = internalFeature; + this.attributeDefinition = attributeDefinition; + this.caseSensitive = caseSensitive; + } + + + @Override + public boolean match(SpecElementWithAttributes element) { + + String theValue; + + // retrieve the value to check depending on this is a filter on an + // internal Attribute or a value + if (isInternal) { + theValue = getInternalAttributeValue(element); + } else { + theValue = getAttributeValue(element); + } + + /* 1. handle empty attribute case */ + if (theValue == null){ + switch (operator) { + case EQUALS: + case CONTAINS: + return false; + case NOT_EQUALS: + case NOT_CONTAINS: + return true; + case REGEXP: + // apply regexp to the empty string + //return "".matches(filterValue); + return matchRegexp(""); + default: + break; + } + } + + /* 2. handle non-empty attribute case */ + switch (operator) { + case EQUALS: + return (caseSensitive ? theValue.equals(filterValue) + : theValue.equalsIgnoreCase(filterValue)); + case NOT_EQUALS: + return (caseSensitive ? !theValue.equals(filterValue) + : !theValue.equalsIgnoreCase(filterValue)); + case CONTAINS: + return (caseSensitive ? theValue.contains(filterValue) + : theValue.toLowerCase().contains(filterValue.toLowerCase())); + case NOT_CONTAINS: + return (caseSensitive ? !theValue.contains(filterValue) + : !theValue.toLowerCase().contains(filterValue.toLowerCase())); + case REGEXP: +// return (caseSensitive ? theValue.matches(filterValue) +// : theValue.toLowerCase().matches(filterValue.toLowerCase())); + return matchRegexp(theValue); + default: + throw new IllegalArgumentException( + "This filter does not support the " + this.operator + + " operation"); + } + } + + + /** + * returns the value of the Internal Attribute that is defined by this.internalAttribute + * + * @return + */ + protected abstract String getInternalAttributeValue(SpecElementWithAttributes element); + + /** + * returns the value of the element that is defined by this.attributeDefinition + * + * @param element + * @return + */ + protected abstract String getAttributeValue(SpecElementWithAttributes element); + + + /** + * Has to return the instance of this.SUPPORTED_OPERATORS + * @return + */ + protected abstract ImmutableSet<Operator> getSupportedOperators(); + + + + /** + * matches this.filterValue to the String value + * takes this.caseSensitive into account + * + * @return + */ + protected boolean matchRegexp(String value){ + Pattern p; + if (caseSensitive){ + p = Pattern.compile(filterValue); + }else{ + p = Pattern.compile(filterValue, Pattern.CASE_INSENSITIVE); + } + Matcher matcher = p.matcher(value); + return matcher.find(); + } + + +} diff --git a/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/StringFilter.java b/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/StringFilter.java index 6d73da10..2cc05a20 100644 --- a/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/StringFilter.java +++ b/org.eclipse.rmf.reqif10.search/src/org/eclipse/rmf/reqif10/search/filter/StringFilter.java @@ -11,8 +11,8 @@ ******************************************************************************/ package org.eclipse.rmf.reqif10.search.filter; +import org.eclipse.rmf.reqif10.AttributeDefinition; import org.eclipse.rmf.reqif10.AttributeDefinitionString; -import org.eclipse.rmf.reqif10.AttributeValue; import org.eclipse.rmf.reqif10.AttributeValueString; import org.eclipse.rmf.reqif10.SpecElementWithAttributes; import org.eclipse.rmf.reqif10.common.util.ReqIF10Util; @@ -23,132 +23,47 @@ /** * Filter for String-based values. */ -public class StringFilter implements IFilter { - - public enum InternalAttribute { - IDENTIFIER, DESC, LONG_NAME - } +public class StringFilter extends AbstractTextFilter { // TODO cross-check this with supported operators. public static final ImmutableSet<Operator> SUPPORTED_OPERATORS = Sets .immutableEnumSet(Operator.EQUALS, Operator.NOT_EQUALS, Operator.CONTAINS, Operator.NOT_CONTAINS, Operator.REGEXP); - private Operator operator; - private String filterValue; - private AttributeDefinitionString attributeDefinition; - private InternalAttribute internalAttribute; - private boolean caseSensitive; - private boolean isInternal; - - /** - * Constructor used to create a filter for an {@link AttributeDefinitionString} + * Constructor used to create a filter for an + * {@link AttributeDefinitionString} * - * @param operator the filter operator to use - * @param value the value to match - * @param attributeDefinition the attributeDefinition that defines the value of a SpecObject that should be matched - * @param caseSensitive + * @param operator + * the filter operator to use + * @param value + * the value to match + * @param attributeDefinition + * the attributeDefinition that defines the value of a SpecObject + * that should be matched + * @param caseSensitive */ public StringFilter(Operator operator, String value, AttributeDefinitionString attributeDefinition, boolean caseSensitive) { - this(operator, value, null, attributeDefinition, caseSensitive); - this.isInternal = false; - if (null == attributeDefinition){ - throw new IllegalArgumentException("AttributeDefinition can not be null"); - } + super(operator, value, null, (AttributeDefinition) attributeDefinition, + caseSensitive); } /** * Constructor used to create a filter for an {@link InternalAttribute} * - * @param operator the filter operator to use - * @param value the value to match - * @param attributeDefinition the attributeDefinition that defines the value of a SpecObject that should be matched - * @param caseSensitive + * @param operator + * the filter operator to use + * @param value + * the value to match + * @param attributeDefinition + * the attributeDefinition that defines the value of a SpecObject + * that should be matched + * @param caseSensitive */ public StringFilter(Operator operator, String value, InternalAttribute internalFeature, boolean caseSensitive) { - this(operator, value, internalFeature, null, caseSensitive); - this.isInternal = true; - if (null == internalFeature){ - throw new IllegalArgumentException("AttributeDefinition can not be null"); - } - } - - private StringFilter(Operator operator, String value, - InternalAttribute internalFeature, AttributeDefinitionString ad, boolean caseSensitive){ - - if (!SUPPORTED_OPERATORS.contains(operator)){ - throw new IllegalArgumentException( - "This filter does not support the " + operator.toString() - + " operation"); - } - if (null == value){ - throw new IllegalArgumentException( - "Value can not be null"); - } - - this.operator = operator; - this.filterValue = (null == value ? "" : value); - this.internalAttribute = internalFeature; - this.attributeDefinition = ad; - this.caseSensitive = caseSensitive; - } - - - @Override - public boolean match(SpecElementWithAttributes element) { - - String theValue; - - // retrieve the value to check depending on this is a filter on an - // internal Attribute or a value - if (isInternal) { - theValue = getInternalAttributeValue(element); - } else { - AttributeValue attributeValue = ReqIF10Util.getAttributeValue( - element, attributeDefinition); - theValue = (null == attributeValue ? null : ((AttributeValueString) attributeValue).getTheValue()); - } - - if (theValue == null){ - switch (operator) { - case EQUALS: - case CONTAINS: - return false; - case NOT_EQUALS: - case NOT_CONTAINS: - return true; - case REGEXP: - // apply regexp to the empty string - return "".matches(filterValue); - default: - break; - } - } - - switch (operator) { - case EQUALS: - return (caseSensitive ? theValue.equals(filterValue) - : theValue.equalsIgnoreCase(filterValue)); - case NOT_EQUALS: - return (caseSensitive ? !theValue.equals(filterValue) - : !theValue.equalsIgnoreCase(filterValue)); - case CONTAINS: - return (caseSensitive ? theValue.contains(filterValue) - : theValue.toLowerCase().contains(filterValue.toLowerCase())); - case NOT_CONTAINS: - return (caseSensitive ? !theValue.contains(filterValue) - : !theValue.toLowerCase().contains(filterValue.toLowerCase())); - case REGEXP: - return (caseSensitive ? theValue.matches(filterValue) - : theValue.toLowerCase().matches(filterValue.toLowerCase())); - default: - throw new IllegalArgumentException( - "This filter does not support the " + this.operator - + " operation"); - } + super(operator, value, internalFeature, null, caseSensitive); } /** @@ -157,7 +72,7 @@ public boolean match(SpecElementWithAttributes element) { * * @return */ - private String getInternalAttributeValue(SpecElementWithAttributes element) { + protected String getInternalAttributeValue(SpecElementWithAttributes element) { switch (internalAttribute) { case IDENTIFIER: return element.getIdentifier(); @@ -170,5 +85,20 @@ private String getInternalAttributeValue(SpecElementWithAttributes element) { } } + @Override + protected String getAttributeValue(SpecElementWithAttributes element) { + AttributeValueString attributeValue = (AttributeValueString) ReqIF10Util + .getAttributeValue(element, attributeDefinition); + if (attributeValue == null) { + return null; + } + + return attributeValue.getTheValue(); + } + + @Override + protected ImmutableSet<Operator> getSupportedOperators() { + return SUPPORTED_OPERATORS; + } }
a8dbce159679cd031f60e6151399fa2cd5ac9374
hadoop
HADOOP-7223. FileContext createFlag combinations- are not clearly defined. Contributed by Suresh Srinivas.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1092565 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/hadoop
diff --git a/CHANGES.txt b/CHANGES.txt index a6186537bdbb6..7a2ece8c71744 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,4 @@ -Hadoop Change Log +Hn jaadoop Change Log Trunk (unreleased changes) @@ -139,6 +139,10 @@ Trunk (unreleased changes) HADOOP-7207. fs member of FSShell is not really needed (boryas) + HADOOP-7223. FileContext createFlag combinations are not clearly defined. + (suresh) + + Release 0.22.0 - Unreleased INCOMPATIBLE CHANGES diff --git a/src/java/org/apache/hadoop/fs/ChecksumFs.java b/src/java/org/apache/hadoop/fs/ChecksumFs.java index a55108598becd..87cd5a77dec39 100644 --- a/src/java/org/apache/hadoop/fs/ChecksumFs.java +++ b/src/java/org/apache/hadoop/fs/ChecksumFs.java @@ -337,8 +337,9 @@ public ChecksumFSOutputSummer(final ChecksumFs fs, final Path file, int bytesPerSum = fs.getBytesPerSum(); int sumBufferSize = fs.getSumBufferSize(bytesPerSum, bufferSize); this.sums = fs.getRawFs().createInternal(fs.getChecksumFile(file), - EnumSet.of(CreateFlag.OVERWRITE), absolutePermission, sumBufferSize, - replication, blockSize, progress, bytesPerChecksum, createParent); + EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), + absolutePermission, sumBufferSize, replication, blockSize, progress, + bytesPerChecksum, createParent); sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length); sums.writeInt(bytesPerSum); } diff --git a/src/java/org/apache/hadoop/fs/CreateFlag.java b/src/java/org/apache/hadoop/fs/CreateFlag.java index 375876a8bdb40..4373124caabf4 100644 --- a/src/java/org/apache/hadoop/fs/CreateFlag.java +++ b/src/java/org/apache/hadoop/fs/CreateFlag.java @@ -17,49 +17,63 @@ */ package org.apache.hadoop.fs; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.EnumSet; + +import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /**************************************************************** - *CreateFlag specifies the file create semantic. Users can combine flags like:<br> - *<code> + * CreateFlag specifies the file create semantic. Users can combine flags like: <br> + * <code> * EnumSet.of(CreateFlag.CREATE, CreateFlag.APPEND) * <code> - * and pass it to {@link org.apache.hadoop.fs.FileSystem #create(Path f, FsPermission permission, - * EnumSet<CreateFlag> flag, int bufferSize, short replication, long blockSize, - * Progressable progress)}. - * * <p> - * Combine {@link #OVERWRITE} with either {@link #CREATE} - * or {@link #APPEND} does the same as only use - * {@link #OVERWRITE}. <br> - * Combine {@link #CREATE} with {@link #APPEND} has the semantic: + * + * Use the CreateFlag as follows: + * <ol> + * <li> CREATE - to create a file if it does not exist, + * else throw FileAlreadyExists.</li> + * <li> APPEND - to append to a file if it exists, + * else throw FileNotFoundException.</li> + * <li> OVERWRITE - to truncate a file if it exists, + * else throw FileNotFoundException.</li> + * <li> CREATE|APPEND - to create a file if it does not exist, + * else append to an existing file.</li> + * <li> CREATE|OVERWRITE - to create a file if it does not exist, + * else overwrite an existing file.</li> + * </ol> + * + * Following combination is not valid and will result in + * {@link HadoopIllegalArgumentException}: * <ol> - * <li> create the file if it does not exist; - * <li> append the file if it already exists. + * <li> APPEND|OVERWRITE</li> + * <li> CREATE|APPEND|OVERWRITE</li> * </ol> *****************************************************************/ @InterfaceAudience.Public [email protected] [email protected] public enum CreateFlag { /** - * create the file if it does not exist, and throw an IOException if it + * Create a file. See javadoc for more description * already exists */ CREATE((short) 0x01), /** - * create the file if it does not exist, if it exists, overwrite it. + * Truncate/overwrite a file. Same as POSIX O_TRUNC. See javadoc for description. */ OVERWRITE((short) 0x02), /** - * append to a file, and throw an IOException if it does not exist + * Append to a file. See javadoc for more description. */ APPEND((short) 0x04); - private short mode; + private final short mode; private CreateFlag(short mode) { this.mode = mode; @@ -68,4 +82,49 @@ private CreateFlag(short mode) { short getMode() { return mode; } + + /** + * Validate the CreateFlag and throw exception if it is invalid + * @param flag set of CreateFlag + * @throws HadoopIllegalArgumentException if the CreateFlag is invalid + */ + public static void validate(EnumSet<CreateFlag> flag) { + if (flag == null || flag.isEmpty()) { + throw new HadoopIllegalArgumentException(flag + + " does not specify any options"); + } + final boolean append = flag.contains(APPEND); + final boolean overwrite = flag.contains(OVERWRITE); + + // Both append and overwrite is an error + if (append && overwrite) { + throw new HadoopIllegalArgumentException( + flag + "Both append and overwrite options cannot be enabled."); + } + } + + /** + * Validate the CreateFlag for create operation + * @param path Object representing the path; usually String or {@link Path} + * @param pathExists pass true if the path exists in the file system + * @param flag set of CreateFlag + * @throws IOException on error + * @throws HadoopIllegalArgumentException if the CreateFlag is invalid + */ + public static void validate(Object path, boolean pathExists, + EnumSet<CreateFlag> flag) throws IOException { + validate(flag); + final boolean append = flag.contains(APPEND); + final boolean overwrite = flag.contains(OVERWRITE); + if (pathExists) { + if (!(append || overwrite)) { + throw new FileAlreadyExistsException("File already exists: " + + path.toString() + + ". Append or overwrite option must be specified in " + flag); + } + } else if (!flag.contains(CREATE)) { + throw new FileNotFoundException("Non existing file: " + path.toString() + + ". Create option is not specified in " + flag); + } + } } \ No newline at end of file diff --git a/src/java/org/apache/hadoop/fs/FileContext.java b/src/java/org/apache/hadoop/fs/FileContext.java index 2596daae5e7b4..e3163ea75e5b7 100644 --- a/src/java/org/apache/hadoop/fs/FileContext.java +++ b/src/java/org/apache/hadoop/fs/FileContext.java @@ -511,7 +511,7 @@ public Path makeQualified(final Path path) { * writing into the file. * * @param f the file name to open - * @param createFlag gives the semantics of create: overwrite, append etc. + * @param createFlag gives the semantics of create; see {@link CreateFlag} * @param opts file creation options; see {@link Options.CreateOpts}. * <ul> * <li>Progress - to report progress on the operation - default null @@ -2057,7 +2057,10 @@ public boolean copy(final Path src, final Path dst, boolean deleteSource, OutputStream out = null; try { in = open(qSrc); - out = create(qDst, EnumSet.of(CreateFlag.OVERWRITE)); + EnumSet<CreateFlag> createFlag = overwrite ? EnumSet.of( + CreateFlag.CREATE, CreateFlag.OVERWRITE) : + EnumSet.of(CreateFlag.CREATE); + out = create(qDst, createFlag); IOUtils.copyBytes(in, out, conf, true); } catch (IOException e) { IOUtils.closeStream(out); diff --git a/src/java/org/apache/hadoop/fs/FileSystem.java b/src/java/org/apache/hadoop/fs/FileSystem.java index be1c796a4caa3..8708b7d62de03 100644 --- a/src/java/org/apache/hadoop/fs/FileSystem.java +++ b/src/java/org/apache/hadoop/fs/FileSystem.java @@ -717,24 +717,21 @@ protected FSDataOutputStream primitiveCreate(Path f, FsPermission absolutePermission, EnumSet<CreateFlag> flag, int bufferSize, short replication, long blockSize, Progressable progress, int bytesPerChecksum) throws IOException { + + boolean pathExists = exists(f); + CreateFlag.validate(f, pathExists, flag); // Default impl assumes that permissions do not matter and // nor does the bytesPerChecksum hence // calling the regular create is good enough. // FSs that implement permissions should override this. - if (exists(f)) { - if (flag.contains(CreateFlag.APPEND)) { - return append(f, bufferSize, progress); - } else if (!flag.contains(CreateFlag.OVERWRITE)) { - throw new IOException("File already exists: " + f); - } - } else { - if (flag.contains(CreateFlag.APPEND) && !flag.contains(CreateFlag.CREATE)) - throw new IOException("File already exists: " + f.toString()); + if (pathExists && flag.contains(CreateFlag.APPEND)) { + return append(f, bufferSize, progress); } - return this.create(f, absolutePermission, flag.contains(CreateFlag.OVERWRITE), bufferSize, replication, + return this.create(f, absolutePermission, + flag.contains(CreateFlag.OVERWRITE), bufferSize, replication, blockSize, progress); } diff --git a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java index 18ef152baf35c..3a54fae955b7e 100644 --- a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java +++ b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java @@ -264,28 +264,6 @@ public FSDataOutputStream create(Path f, FsPermission permission, return out; } - - @Override - protected FSDataOutputStream primitiveCreate(Path f, - FsPermission absolutePermission, EnumSet<CreateFlag> flag, - int bufferSize, short replication, long blockSize, Progressable progress, - int bytesPerChecksum) throws IOException { - - if(flag.contains(CreateFlag.APPEND)){ - if (!exists(f)){ - if(flag.contains(CreateFlag.CREATE)) { - return create(f, false, bufferSize, replication, blockSize, null); - } - } - return append(f, bufferSize, null); - } - - FSDataOutputStream out = create(f, flag.contains(CreateFlag.OVERWRITE), - bufferSize, replication, blockSize, progress); - setPermission(f, absolutePermission); - return out; - } - public boolean rename(Path src, Path dst) throws IOException { if (pathToFile(src).renameTo(pathToFile(dst))) { return true; diff --git a/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java b/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java index 1af5a6391bca2..b88f5b5c5d9ae 100644 --- a/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java +++ b/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java @@ -21,8 +21,8 @@ import java.io.FileNotFoundException; import java.io.IOException; import java.util.EnumSet; -import java.util.Iterator; +import org.apache.hadoop.HadoopIllegalArgumentException; import org.apache.hadoop.fs.Options.CreateOpts; import org.apache.hadoop.fs.Options.Rename; import org.apache.hadoop.fs.permission.FsPermission; @@ -32,6 +32,7 @@ import org.junit.Test; import static org.apache.hadoop.fs.FileContextTestHelper.*; +import static org.apache.hadoop.fs.CreateFlag.*; /** * <p> @@ -155,7 +156,7 @@ public void testWorkingDirectory() throws Exception { // Now open a file relative to the wd we just set above. Path absolutePath = new Path(absoluteDir, "foo"); - fc.create(absolutePath, EnumSet.of(CreateFlag.CREATE)).close(); + fc.create(absolutePath, EnumSet.of(CREATE)).close(); fc.open(new Path("foo")).close(); @@ -645,7 +646,7 @@ private void writeReadAndDelete(int len) throws IOException { fc.mkdir(path.getParent(), FsPermission.getDefault(), true); - FSDataOutputStream out = fc.create(path, EnumSet.of(CreateFlag.CREATE), + FSDataOutputStream out = fc.create(path, EnumSet.of(CREATE), CreateOpts.repFac((short) 1), CreateOpts .blockSize(getDefaultBlockSize())); out.write(data, 0, len); @@ -670,31 +671,93 @@ private void writeReadAndDelete(int len) throws IOException { } + @Test(expected=HadoopIllegalArgumentException.class) + public void testNullCreateFlag() throws IOException { + Path p = getTestRootPath(fc, "test/file"); + fc.create(p, null); + Assert.fail("Excepted exception not thrown"); + } + + @Test(expected=HadoopIllegalArgumentException.class) + public void testEmptyCreateFlag() throws IOException { + Path p = getTestRootPath(fc, "test/file"); + fc.create(p, EnumSet.noneOf(CreateFlag.class)); + Assert.fail("Excepted exception not thrown"); + } + + @Test(expected=FileAlreadyExistsException.class) + public void testCreateFlagCreateExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagCreateExistingFile"); + createFile(p); + fc.create(p, EnumSet.of(CREATE)); + Assert.fail("Excepted exception not thrown"); + } + + @Test(expected=FileNotFoundException.class) + public void testCreateFlagOverwriteNonExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagOverwriteNonExistingFile"); + fc.create(p, EnumSet.of(OVERWRITE)); + Assert.fail("Excepted exception not thrown"); + } + @Test - public void testOverwrite() throws IOException { - Path path = getTestRootPath(fc, "test/hadoop/file"); - - fc.mkdir(path.getParent(), FsPermission.getDefault(), true); - - createFile(path); - - Assert.assertTrue("Exists", exists(fc, path)); - Assert.assertEquals("Length", data.length, fc.getFileStatus(path).getLen()); - - try { - fc.create(path, EnumSet.of(CreateFlag.CREATE)); - Assert.fail("Should throw IOException."); - } catch (IOException e) { - // Expected - } - - FSDataOutputStream out = fc.create(path,EnumSet.of(CreateFlag.OVERWRITE)); + public void testCreateFlagOverwriteExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagOverwriteExistingFile"); + createFile(p); + FSDataOutputStream out = fc.create(p, EnumSet.of(OVERWRITE)); + writeData(fc, p, out, data, data.length); + } + + @Test(expected=FileNotFoundException.class) + public void testCreateFlagAppendNonExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagAppendNonExistingFile"); + fc.create(p, EnumSet.of(APPEND)); + Assert.fail("Excepted exception not thrown"); + } + + @Test + public void testCreateFlagAppendExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagAppendExistingFile"); + createFile(p); + FSDataOutputStream out = fc.create(p, EnumSet.of(APPEND)); + writeData(fc, p, out, data, 2 * data.length); + } + + @Test + public void testCreateFlagCreateAppendNonExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagCreateAppendNonExistingFile"); + FSDataOutputStream out = fc.create(p, EnumSet.of(CREATE, APPEND)); + writeData(fc, p, out, data, data.length); + } + + @Test + public void testCreateFlagCreateAppendExistingFile() throws IOException { + Path p = getTestRootPath(fc, "test/testCreateFlagCreateAppendExistingFile"); + createFile(p); + FSDataOutputStream out = fc.create(p, EnumSet.of(CREATE, APPEND)); + writeData(fc, p, out, data, 2*data.length); + } + + @Test(expected=HadoopIllegalArgumentException.class) + public void testCreateFlagAppendOverwrite() throws IOException { + Path p = getTestRootPath(fc, "test/nonExistent"); + fc.create(p, EnumSet.of(APPEND, OVERWRITE)); + Assert.fail("Excepted exception not thrown"); + } + + @Test(expected=HadoopIllegalArgumentException.class) + public void testCreateFlagAppendCreateOverwrite() throws IOException { + Path p = getTestRootPath(fc, "test/nonExistent"); + fc.create(p, EnumSet.of(CREATE, APPEND, OVERWRITE)); + Assert.fail("Excepted exception not thrown"); + } + + private static void writeData(FileContext fc, Path p, FSDataOutputStream out, + byte[] data, long expectedLen) throws IOException { out.write(data, 0, data.length); out.close(); - - Assert.assertTrue("Exists", exists(fc, path)); - Assert.assertEquals("Length", data.length, fc.getFileStatus(path).getLen()); - + Assert.assertTrue("Exists", exists(fc, p)); + Assert.assertEquals("Length", expectedLen, fc.getFileStatus(p).getLen()); } @Test @@ -1057,7 +1120,7 @@ public void testOutputStreamClosedTwice() throws IOException { //HADOOP-4760 according to Closeable#close() closing already-closed //streams should have no effect. Path src = getTestRootPath(fc, "test/hadoop/file"); - FSDataOutputStream out = fc.create(src, EnumSet.of(CreateFlag.CREATE), + FSDataOutputStream out = fc.create(src, EnumSet.of(CREATE), Options.CreateOpts.createParent()); out.writeChar('H'); //write some data @@ -1091,7 +1154,7 @@ public void testUnsupportedSymlink() throws IOException { } protected void createFile(Path path) throws IOException { - FSDataOutputStream out = fc.create(path, EnumSet.of(CreateFlag.CREATE), + FSDataOutputStream out = fc.create(path, EnumSet.of(CREATE), Options.CreateOpts.createParent()); out.write(data, 0, data.length); out.close(); diff --git a/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java b/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java index 97342951579ca..5124211d344db 100644 --- a/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java +++ b/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java @@ -140,7 +140,8 @@ private void genFiles() throws IOException { * a length of <code>fileSize</code>. The file is filled with character 'a'. */ private void genFile(Path file, long fileSize) throws IOException { - FSDataOutputStream out = fc.create(file, EnumSet.of(CreateFlag.OVERWRITE), + FSDataOutputStream out = fc.create(file, + EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), CreateOpts.createParent(), CreateOpts.bufferSize(4096), CreateOpts.repFac((short) 3)); for(long i=0; i<fileSize; i++) { diff --git a/src/test/core/org/apache/hadoop/fs/loadGenerator/LoadGenerator.java b/src/test/core/org/apache/hadoop/fs/loadGenerator/LoadGenerator.java index cdbcff22d1379..51d4bc38b8c49 100644 --- a/src/test/core/org/apache/hadoop/fs/loadGenerator/LoadGenerator.java +++ b/src/test/core/org/apache/hadoop/fs/loadGenerator/LoadGenerator.java @@ -584,7 +584,8 @@ private void barrier() { */ private void genFile(Path file, long fileSize) throws IOException { long startTime = System.currentTimeMillis(); - FSDataOutputStream out = fc.create(file, EnumSet.of(CreateFlag.OVERWRITE), + FSDataOutputStream out = fc.create(file, + EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), CreateOpts.createParent(), CreateOpts.bufferSize(4096), CreateOpts.repFac((short) 3)); executionTime[CREATE] += (System.currentTimeMillis()-startTime);
0e8a141437a6645deb85a730bc9adfb757bb27b8
hbase
HBASE-10010 eliminate the put latency spike on- the new log file beginning--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1549384 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java index 7c32ce611f5c..1c69d0ff890c 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/wal/FSHLog.java @@ -532,6 +532,13 @@ OutputStream getOutputStream() { FSDataOutputStream nextHdfsOut = null; if (nextWriter instanceof ProtobufLogWriter) { nextHdfsOut = ((ProtobufLogWriter)nextWriter).getStream(); + // perform the costly sync before we get the lock to roll writers. + try { + nextWriter.sync(); + } catch (IOException e) { + // optimization failed, no need to abort here. + LOG.warn("pre-sync failed", e); + } } Path oldFile = null; diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationHLogReaderManager.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationHLogReaderManager.java index 705b3ae9ab64..dfc89bc32df5 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationHLogReaderManager.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/replication/regionserver/TestReplicationHLogReaderManager.java @@ -141,12 +141,6 @@ public void test() throws Exception { // Grab the path that was generated when the log rolled as part of its creation Path path = pathWatcher.currentPath; - // open it, it's empty so it fails - try { - logManager.openReader(path); - fail("Shouldn't be able to open an empty file"); - } catch (EOFException ex) {} - assertEquals(0, logManager.getPosition()); appendToLog(); @@ -184,12 +178,6 @@ public void test() throws Exception { path = pathWatcher.currentPath; - // Finally we have a new empty log, which should still give us EOFs - try { - logManager.openReader(path); - fail(); - } catch (EOFException ex) {} - for (int i = 0; i < nbRows; i++) { appendToLogPlus(walEditKVs); } log.rollWriter(); logManager.openReader(path);
538d245ba9744f57d66724982db4850e6d3ba226
ReactiveX-RxJava
Implement a cached thread scheduler using event- loops--
a
https://github.com/ReactiveX/RxJava
diff --git a/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java b/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java new file mode 100644 index 0000000000..92dd486d92 --- /dev/null +++ b/rxjava-core/src/main/java/rx/schedulers/CachedThreadScheduler.java @@ -0,0 +1,180 @@ +/** + * Copyright 2014 Netflix, Inc. + * + * 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 + * + * http://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 rx.schedulers; + +import rx.Scheduler; +import rx.Subscription; +import rx.functions.Action0; +import rx.subscriptions.CompositeSubscription; +import rx.subscriptions.Subscriptions; + +import java.util.Iterator; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/* package */class CachedThreadScheduler extends Scheduler { + private static final class CachedWorkerPool { + final ThreadFactory factory = new ThreadFactory() { + final AtomicInteger counter = new AtomicInteger(); + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, "RxCachedThreadScheduler-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; + } + }; + + private final long keepAliveTime; + private final ConcurrentLinkedQueue<PoolWorker> expiringQueue; + private final ScheduledExecutorService evictExpiredWorkerExecutor; + + CachedWorkerPool(long keepAliveTime, TimeUnit unit) { + this.keepAliveTime = unit.toNanos(keepAliveTime); + this.expiringQueue = new ConcurrentLinkedQueue<PoolWorker>(); + + evictExpiredWorkerExecutor = Executors.newScheduledThreadPool(1, new ThreadFactory() { + final AtomicInteger counter = new AtomicInteger(); + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r, "RxCachedWorkerPoolEvictor-" + counter.incrementAndGet()); + t.setDaemon(true); + return t; + } + }); + evictExpiredWorkerExecutor.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + evictExpiredWorkers(); + } + }, this.keepAliveTime, this.keepAliveTime, TimeUnit.NANOSECONDS + ); + } + + private static CachedWorkerPool INSTANCE = new CachedWorkerPool( + 60L, TimeUnit.SECONDS + ); + + PoolWorker get() { + while (!expiringQueue.isEmpty()) { + PoolWorker poolWorker = expiringQueue.poll(); + if (poolWorker != null) { + return poolWorker; + } + } + + // No cached worker found, so create a new one. + return new PoolWorker(factory); + } + + void release(PoolWorker poolWorker) { + // Refresh expire time before putting worker back in pool + poolWorker.setExpirationTime(now() + keepAliveTime); + + expiringQueue.add(poolWorker); + } + + void evictExpiredWorkers() { + if (!expiringQueue.isEmpty()) { + long currentTimestamp = now(); + + Iterator<PoolWorker> poolWorkerIterator = expiringQueue.iterator(); + while (poolWorkerIterator.hasNext()) { + PoolWorker poolWorker = poolWorkerIterator.next(); + if (poolWorker.getExpirationTime() <= currentTimestamp) { + poolWorkerIterator.remove(); + poolWorker.unsubscribe(); + } else { + // Queue is ordered with the worker that will expire first in the beginning, so when we + // find a non-expired worker we can stop evicting. + break; + } + } + } + } + + long now() { + return System.nanoTime(); + } + } + + @Override + public Worker createWorker() { + return new EventLoopWorker(CachedWorkerPool.INSTANCE.get()); + } + + private static class EventLoopWorker extends Scheduler.Worker { + private final CompositeSubscription innerSubscription = new CompositeSubscription(); + private final PoolWorker poolWorker; + private final AtomicBoolean releasePoolWorkerOnce = new AtomicBoolean(false); + + EventLoopWorker(PoolWorker poolWorker) { + this.poolWorker = poolWorker; + } + + @Override + public void unsubscribe() { + if (releasePoolWorkerOnce.compareAndSet(false, true)) { + // unsubscribe should be idempotent, so only do this once + CachedWorkerPool.INSTANCE.release(poolWorker); + } + innerSubscription.unsubscribe(); + } + + @Override + public boolean isUnsubscribed() { + return innerSubscription.isUnsubscribed(); + } + + @Override + public Subscription schedule(Action0 action) { + return schedule(action, 0, null); + } + + @Override + public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) { + if (innerSubscription.isUnsubscribed()) { + // don't schedule, we are unsubscribed + return Subscriptions.empty(); + } + + NewThreadScheduler.NewThreadWorker.ScheduledAction s = poolWorker.scheduleActual(action, delayTime, unit); + innerSubscription.add(s); + s.addParent(innerSubscription); + return s; + } + } + + private static final class PoolWorker extends NewThreadScheduler.NewThreadWorker { + private long expirationTime; + + PoolWorker(ThreadFactory threadFactory) { + super(threadFactory); + this.expirationTime = 0L; + } + + public long getExpirationTime() { + return expirationTime; + } + + public void setExpirationTime(long expirationTime) { + this.expirationTime = expirationTime; + } + } +} diff --git a/rxjava-core/src/main/java/rx/schedulers/Schedulers.java b/rxjava-core/src/main/java/rx/schedulers/Schedulers.java index d7096b7751..53bed75151 100644 --- a/rxjava-core/src/main/java/rx/schedulers/Schedulers.java +++ b/rxjava-core/src/main/java/rx/schedulers/Schedulers.java @@ -15,11 +15,11 @@ */ package rx.schedulers; -import java.util.concurrent.Executor; - import rx.Scheduler; import rx.plugins.RxJavaPlugins; +import java.util.concurrent.Executor; + /** * Static factory methods for creating Schedulers. */ @@ -43,7 +43,7 @@ private Schedulers() { if (io != null) { ioScheduler = io; } else { - ioScheduler = NewThreadScheduler.instance(); // defaults to new thread + ioScheduler = new CachedThreadScheduler(); } Scheduler nt = RxJavaPlugins.getInstance().getDefaultSchedulers().getNewThreadScheduler(); diff --git a/rxjava-core/src/test/java/rx/schedulers/CachedThreadSchedulerTest.java b/rxjava-core/src/test/java/rx/schedulers/CachedThreadSchedulerTest.java new file mode 100644 index 0000000000..f9f8ca161c --- /dev/null +++ b/rxjava-core/src/test/java/rx/schedulers/CachedThreadSchedulerTest.java @@ -0,0 +1,60 @@ +/** + * Copyright 2014 Netflix, Inc. + * + * 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 + * + * http://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 rx.schedulers; + +import org.junit.Test; +import rx.Observable; +import rx.Scheduler; +import rx.functions.Action1; +import rx.functions.Func1; + +import static org.junit.Assert.assertTrue; + +public class CachedThreadSchedulerTest extends AbstractSchedulerConcurrencyTests { + + @Override + protected Scheduler getScheduler() { + return Schedulers.io(); + } + + /** + * IO scheduler defaults to using CachedThreadScheduler + */ + @Test + public final void testIOScheduler() { + + Observable<Integer> o1 = Observable.from(1, 2, 3, 4, 5); + Observable<Integer> o2 = Observable.from(6, 7, 8, 9, 10); + Observable<String> o = Observable.merge(o1, o2).map(new Func1<Integer, String>() { + + @Override + public String call(Integer t) { + assertTrue(Thread.currentThread().getName().startsWith("RxCachedThreadScheduler")); + return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); + } + }); + + o.subscribeOn(Schedulers.io()).toBlocking().forEach(new Action1<String>() { + + @Override + public void call(String t) { + System.out.println("t: " + t); + } + }); + } + +} \ No newline at end of file diff --git a/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java b/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java index 37b314a0dd..963ee50fa9 100644 --- a/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java +++ b/rxjava-core/src/test/java/rx/schedulers/NewThreadSchedulerTest.java @@ -16,14 +16,7 @@ package rx.schedulers; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import rx.Observable; import rx.Scheduler; -import rx.functions.Action1; -import rx.functions.Func1; public class NewThreadSchedulerTest extends AbstractSchedulerConcurrencyTests { @@ -31,31 +24,4 @@ public class NewThreadSchedulerTest extends AbstractSchedulerConcurrencyTests { protected Scheduler getScheduler() { return Schedulers.newThread(); } - - /** - * IO scheduler defaults to using NewThreadScheduler - */ - @Test - public final void testIOScheduler() { - - Observable<Integer> o1 = Observable.<Integer> from(1, 2, 3, 4, 5); - Observable<Integer> o2 = Observable.<Integer> from(6, 7, 8, 9, 10); - Observable<String> o = Observable.<Integer> merge(o1, o2).map(new Func1<Integer, String>() { - - @Override - public String call(Integer t) { - assertTrue(Thread.currentThread().getName().startsWith("RxNewThreadScheduler")); - return "Value_" + t + "_Thread_" + Thread.currentThread().getName(); - } - }); - - o.subscribeOn(Schedulers.io()).toBlocking().forEach(new Action1<String>() { - - @Override - public void call(String t) { - System.out.println("t: " + t); - } - }); - } - }
3181d96ec864a467d4259e31c64f2b7554afc3d4
hbase
HBASE-2397 Bytes.toStringBinary escapes printable- chars--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@951840 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/CHANGES.txt b/CHANGES.txt index 280daa7fb5ce..8ad8e5601edf 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -23,6 +23,7 @@ Release 0.21.0 - Unreleased HBASE-2541 Remove transactional contrib (Clint Morgan via Stack) HBASE-2542 Fold stargate contrib into core HBASE-2565 Remove contrib module from hbase + HBASE-2397 Bytes.toStringBinary escapes printable chars BUG FIXES HBASE-1791 Timeout in IndexRecordWriter (Bradford Stephens via Andrew diff --git a/src/main/java/org/apache/hadoop/hbase/util/Bytes.java b/src/main/java/org/apache/hadoop/hbase/util/Bytes.java index bed859f48e62..1b46f2d892a4 100644 --- a/src/main/java/org/apache/hadoop/hbase/util/Bytes.java +++ b/src/main/java/org/apache/hadoop/hbase/util/Bytes.java @@ -320,16 +320,7 @@ public static String toStringBinary(final byte [] b, int off, int len) { if ( (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') - || ch == ',' - || ch == '_' - || ch == '-' - || ch == ':' - || ch == ' ' - || ch == '<' - || ch == '>' - || ch == '=' - || ch == '/' - || ch == '.') { + || " `~!@#$%^&*()-_=+[]{}\\|;:'\",.<>/?".indexOf(ch) >= 0 ) { result.append(first.charAt(i)); } else { result.append(String.format("\\x%02X", ch));
c0e6bbe105a34e9effb8674d5611a9ea9bb6f32e
Mylyn Reviews
Removed TBR site
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews-site/.project b/tbr/org.eclipse.mylyn.reviews-site/.project deleted file mode 100644 index e7305348..00000000 --- a/tbr/org.eclipse.mylyn.reviews-site/.project +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.mylyn.reviews-site</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.pde.UpdateSiteBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.UpdateSiteNature</nature> - </natures> -</projectDescription> diff --git a/tbr/org.eclipse.mylyn.reviews-site/site.xml b/tbr/org.eclipse.mylyn.reviews-site/site.xml deleted file mode 100644 index 5ca060f2..00000000 --- a/tbr/org.eclipse.mylyn.reviews-site/site.xml +++ /dev/null @@ -1,7 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<site> - <feature url="features/org.eclipse.mylyn.reviews_0.0.1.jar" id="org.eclipse.mylyn.reviews" version="0.0.1"> - <category name="mylyn.reviews"/> - </feature> - <category-def name="mylyn.reviews" label="Mylyn Reviews (Incubation)"/> -</site>
21ee77a4383f5c970e8c73967d38615f5bfb48af
camel
Checkstyle--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1228067 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/components/camel-websocket/src/main/java/org/apache/camel/component/websocket/WebsocketConstants.java b/components/camel-websocket/src/main/java/org/apache/camel/component/websocket/WebsocketConstants.java index e49dd3d85084d..91e4e0b902a95 100644 --- a/components/camel-websocket/src/main/java/org/apache/camel/component/websocket/WebsocketConstants.java +++ b/components/camel-websocket/src/main/java/org/apache/camel/component/websocket/WebsocketConstants.java @@ -16,12 +16,15 @@ */ package org.apache.camel.component.websocket; -public class WebsocketConstants { +public final class WebsocketConstants { + public static final int DEFAULT_PORT = 9292; public static final String CONNECTION_KEY = "websocket.connectionKey"; public static final String SEND_TO_ALL = "websocket.sendToAll"; - public static final String DEFAULT_HOST = "0.0.0.0"; - public static final int DEFAULT_PORT = 9292; + + private WebsocketConstants() { + }; + } diff --git a/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketConfigurationTest.java b/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketConfigurationTest.java index 26a03865350d0..d542417a1f74f 100644 --- a/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketConfigurationTest.java +++ b/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketConfigurationTest.java @@ -23,7 +23,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertEquals; public class WebsocketConfigurationTest { @@ -61,10 +60,6 @@ public void testParameters() throws Exception { assertNotNull(websocketEndpoint); assertNotNull(REMAINING); assertNotNull(wsConfig.getGlobalStore()); - // System.out.println(URI); - // System.out.println(component); - // System.out.println(REMAINING); - // System.out.println(wsConfig.getGlobalStore()); }
fc189d16c1df40cee26e19fcec95cecf2d93d875
tapiji
Adds build support using tycho and maven This changeset adds the following new projects: * `org.eclipse.babel.tapiji.tools.parent`: Encapsulates the root pom file for maven and all commom pom settings * `org.eclipse.babel.tapiji.tools.target`: Specifies the target platform used for building the babel tool suite Moreover, each project has been enhanced with a pom build definition that inherits from the pom located in `org.eclipse.babel.tapiji.tools.parent`. (cherry picked from commit 48aed06137da06e7adaa9ba66b0ea674d33a2a24) Conflicts: .gitignore org.eclipse.babel.core/.classpath org.eclipse.babel.core/.project org.eclipse.babel.core/build.properties org.eclipse.babel.editor.nls/.project org.eclipse.babel.editor/.classpath org.eclipse.babel.editor/.project org.eclipse.babel.editor/build.properties org.eclipse.babel.tapiji.tools.feature/.project org.eclipse.babel.tapiji.tools.java.feature/build.properties
a
https://github.com/tapiji/tapiji
diff --git a/.gitignore b/.gitignore index 90beae66..a4a9433d 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,8 @@ /*/tmp/** /*/local.properties /*/.settings/ +/*/target/ + +# binaries for PDE editor extension +org.eclipse.babel.core.pdeutils/org.eclipse.babel.core.pdeutils.jar + diff --git a/org.eclipse.babel.core.pdeutils/.project b/org.eclipse.babel.core.pdeutils/.project index 86318d62..d9a92ce1 100644 --- a/org.eclipse.babel.core.pdeutils/.project +++ b/org.eclipse.babel.core.pdeutils/.project @@ -20,8 +20,14 @@ <arguments> </arguments> </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.pde.PluginNature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> diff --git a/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF b/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF index a2f896f5..13ab4e98 100644 --- a/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.core.pdeutils/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: Pdeutils Bundle-SymbolicName: org.eclipse.babel.core.pdeutils -Bundle-Version: 1.0.0.qualifier +Bundle-Version: 0.8.0.qualifier Fragment-Host: org.eclipse.babel.core;bundle-version="0.8.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Eclipse-PatchFragment: true diff --git a/org.eclipse.babel.core.pdeutils/pom.xml b/org.eclipse.babel.core.pdeutils/pom.xml new file mode 100644 index 00000000..0e6c86ae --- /dev/null +++ b/org.eclipse.babel.core.pdeutils/pom.xml @@ -0,0 +1,13 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipse.babel.core</groupId> + <artifactId>org.eclipse.babel.core.pdeutils</artifactId> + <version>0.8.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.core/.classpath b/org.eclipse.babel.core/.classpath index 2d1a4302..3a95b200 100644 --- a/org.eclipse.babel.core/.classpath +++ b/org.eclipse.babel.core/.classpath @@ -1,7 +1,8 @@ -<?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/J2SE-1.5"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> +<?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.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src/"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> + diff --git a/org.eclipse.babel.core/.project b/org.eclipse.babel.core/.project index f69c0d43..dfe6f27c 100644 --- a/org.eclipse.babel.core/.project +++ b/org.eclipse.babel.core/.project @@ -1,34 +1,41 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.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> - <buildCommand> - <name>org.eclipse.babel.editor.rbeBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - <nature>org.eclipse.babel.editor.rbeNature</nature> - </natures> -</projectDescription> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.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> + <buildCommand> + <name>org.eclipse.babel.editor.rbeBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + <nature>org.eclipse.babel.editor.rbeNature</nature> + </natures> +</projectDescription> + diff --git a/org.eclipse.babel.core/META-INF/MANIFEST.MF b/org.eclipse.babel.core/META-INF/MANIFEST.MF index 63fb4ed7..73746cd6 100644 --- a/org.eclipse.babel.core/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.core/META-INF/MANIFEST.MF @@ -22,6 +22,7 @@ Export-Package: org.eclipse.babel.core.configuration;uses:="org.eclipse.babel.co org.eclipse.babel.core.message.tree, org.eclipse.babel.core.message.tree.internal, org.eclipse.babel.core.message.tree.visitor;uses:="org.eclipse.babel.core.message,org.eclipselabs.tapiji.translator.rbe.babel.bundle", + org.eclipse.babel.core.refactoring, org.eclipse.babel.core.util;uses:="org.eclipse.core.resources" Require-Bundle: org.eclipse.core.databinding, org.eclipse.core.resources, diff --git a/org.eclipse.babel.core/build.properties b/org.eclipse.babel.core/build.properties index 638542e9..580b822b 100644 --- a/org.eclipse.babel.core/build.properties +++ b/org.eclipse.babel.core/build.properties @@ -1,15 +1,14 @@ -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - org.eclipse.babel.core.pdeutils.jar,\ - plugin.xml,\ - schema/ -src.includes = bin/,\ - src/,\ - schema/,\ - plugin.xml,\ - META-INF/ -source.org.eclipse.babel.core.pedutils.jar = -jars.compile.order = org.eclipse.babel.core.pedutils.jar,\ - . +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + org.eclipse.babel.core.pdeutils.jar,\ + plugin.xml,\ + schema/ +src.includes = src/,\ + schema/,\ + plugin.xml,\ + META-INF/ +source.org.eclipse.babel.core.pedutils.jar = +jars.compile.order = org.eclipse.babel.core.pedutils.jar,\ + . diff --git a/org.eclipse.babel.core/pom.xml b/org.eclipse.babel.core/pom.xml new file mode 100644 index 00000000..94aca175 --- /dev/null +++ b/org.eclipse.babel.core/pom.xml @@ -0,0 +1,38 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipse.babel.core</groupId> + <artifactId>org.eclipse.babel.core</artifactId> + <version>0.8.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + + <properties> + <tycho-version>0.16.0</tycho-version> + </properties> + + <build> + <plugins> + <plugin> + <!-- enable tycho build extension --> + <groupId>org.eclipse.tycho</groupId> + <artifactId>tycho-maven-plugin</artifactId> + <version>${tycho-version}</version> + <extensions>true</extensions> + </plugin> + </plugins> + </build> + + <repositories> + <!-- configure p2 repository to resolve against --> + <repository> + <id>indigo</id> + <layout>p2</layout> + <url>http://download.eclipse.org/releases/indigo/</url> + </repository> + </repositories> + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.editor.nls/.project b/org.eclipse.babel.editor.nls/.project index ca73d326..194dcc2a 100644 --- a/org.eclipse.babel.editor.nls/.project +++ b/org.eclipse.babel.editor.nls/.project @@ -1,22 +1,29 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.editor.nls</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <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> - </natures> -</projectDescription> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.editor.nls</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.PluginNature</nature> + </natures> +</projectDescription> + diff --git a/org.eclipse.babel.editor.nls/pom.xml b/org.eclipse.babel.editor.nls/pom.xml new file mode 100644 index 00000000..f0e9d789 --- /dev/null +++ b/org.eclipse.babel.editor.nls/pom.xml @@ -0,0 +1,13 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipse.babel.editor</groupId> + <artifactId>org.eclipse.babel.editor.nls</artifactId> + <version>0.8.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.editor.rcp.compat/.project b/org.eclipse.babel.editor.rcp.compat/.project index d7075fed..c3f353bc 100644 --- a/org.eclipse.babel.editor.rcp.compat/.project +++ b/org.eclipse.babel.editor.rcp.compat/.project @@ -20,8 +20,14 @@ <arguments> </arguments> </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.pde.PluginNature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> diff --git a/org.eclipse.babel.editor.rcp.compat/pom.xml b/org.eclipse.babel.editor.rcp.compat/pom.xml new file mode 100644 index 00000000..7153ff37 --- /dev/null +++ b/org.eclipse.babel.editor.rcp.compat/pom.xml @@ -0,0 +1,13 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipse.babel.editor</groupId> + <artifactId>org.eclipse.babel.editor.rcp.compat</artifactId> + <version>0.8.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.editor/.classpath b/org.eclipse.babel.editor/.classpath index a2115fe7..3a95b200 100644 --- a/org.eclipse.babel.editor/.classpath +++ b/org.eclipse.babel.editor/.classpath @@ -1,8 +1,8 @@ -<?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/J2SE-1.5"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="src" path="tests"/> - <classpathentry kind="output" path="bin"/> -</classpath> +<?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.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src/"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> + diff --git a/org.eclipse.babel.editor/.project b/org.eclipse.babel.editor/.project index d2bb2d67..1edb7667 100644 --- a/org.eclipse.babel.editor/.project +++ b/org.eclipse.babel.editor/.project @@ -1,34 +1,40 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.editor</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> - <buildCommand> - <name>org.eclipse.babel.editor.rbeBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.PluginNature</nature> - <nature>org.eclipse.jdt.core.javanature</nature> - <nature>org.eclipse.babel.editor.rbeNature</nature> - </natures> -</projectDescription> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.editor</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> + <buildCommand> + <name>org.eclipse.babel.editor.rbeBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + <nature>org.eclipse.babel.editor.rbeNature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.editor/build.properties b/org.eclipse.babel.editor/build.properties index 0cedbb06..71809ed6 100644 --- a/org.eclipse.babel.editor/build.properties +++ b/org.eclipse.babel.editor/build.properties @@ -4,10 +4,9 @@ bin.includes = META-INF/,\ .,\ plugin.xml,\ icons/,\ - bin/,\ plugin.properties,\ messages.properties -src.includes = bin/,\ - icons/,\ - messages.properties - +src.includes = icons/,\ + messages.properties,\ + plugin.properties,\ + plugin.xml \ No newline at end of file diff --git a/org.eclipse.babel.editor/pom.xml b/org.eclipse.babel.editor/pom.xml new file mode 100644 index 00000000..5c1cf20c --- /dev/null +++ b/org.eclipse.babel.editor/pom.xml @@ -0,0 +1,14 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipse.babel.editor</groupId> + <artifactId>org.eclipse.babel.editor</artifactId> + <version>0.8.0-SNAPSHOT</version> + <packaging>eclipse-plugin</packaging> + + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java index 63048fff..f9c65a57 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/i18n/I18NPage.java @@ -133,19 +133,19 @@ public void onModify() { public void onResourceChanged(IMessagesBundle bundle) { // [RAP] only update tree, which belongs to this UIThread - if (!keysComposite.isDisposed()) { - Display display = keysComposite.getTreeViewer().getTree() - .getDisplay(); - if (display.equals(Display.getCurrent())) { - AbstractI18NEntry i18nEntry = entryComposites.get(bundle - .getLocale()); - if (i18nEntry != null && !getSelection().isEmpty()) { - i18nEntry.updateKey(String - .valueOf(((IStructuredSelection) getSelection()) - .getFirstElement())); - } - } - } + if (!keysComposite.isDisposed()) { + Display display = keysComposite.getTreeViewer().getTree() + .getDisplay(); + if (display.equals(Display.getCurrent())) { + AbstractI18NEntry i18nEntry = entryComposites.get(bundle + .getLocale()); + if (i18nEntry != null && !getSelection().isEmpty()) { + i18nEntry.updateKey(String + .valueOf(((IStructuredSelection) getSelection()) + .getFirstElement())); + } + } + } } }); diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java index 207e635f..678639c1 100755 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/internal/AbstractMessagesEditor.java @@ -8,7 +8,7 @@ * Contributors: * Pascal Essiembre - initial API and implementation * Alexej Strelzow - TapJI integration, bug fixes & enhancements - * - issue 35, 36, 48, 73 + * - issue 35, 36, 48, 73 ******************************************************************************/ package org.eclipse.babel.editor.internal; @@ -205,8 +205,8 @@ protected void createMessagesBundlePage(MessagesBundle messagesBundle) { * and a new entry in the i18n page for the given locale and messages bundle. */ protected void addMessagesBundle(MessagesBundle messagesBundle) { - createMessagesBundlePage(messagesBundle); - i18nPage.addI18NEntry(messagesBundle.getLocale()); + createMessagesBundlePage(messagesBundle); + i18nPage.addI18NEntry(messagesBundle.getLocale()); } /** diff --git a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java index 726f9574..5ba54ca4 100644 --- a/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java +++ b/org.eclipse.babel.editor/src/org/eclipse/babel/editor/tree/internal/KeyTreeContributor.java @@ -254,9 +254,9 @@ private void contributeModelChanges(final TreeViewer treeViewer) { public void nodeAdded(KeyTreeNode node) { Display.getDefault().asyncExec(new Runnable() { public void run() { - if (!editor.getI18NPage().isDisposed()) { - treeViewer.refresh(true); - } + if (!editor.getI18NPage().isDisposed()) { + treeViewer.refresh(true); + } } }); }; @@ -267,9 +267,9 @@ public void run() { public void nodeRemoved(KeyTreeNode node) { Display.getDefault().asyncExec(new Runnable() { public void run() { - if (!editor.getI18NPage().isDisposed()) { - treeViewer.refresh(true); - } + if (!editor.getI18NPage().isDisposed()) { + treeViewer.refresh(true); + } } }); }; diff --git a/org.eclipse.babel.tapiji.tools.core.ui/.classpath b/org.eclipse.babel.tapiji.tools.core.ui/.classpath index 8a8f1668..0b1bcf94 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/.classpath +++ b/org.eclipse.babel.tapiji.tools.core.ui/.classpath @@ -1,7 +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.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> +<?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.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src/"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/org.eclipse.babel.tapiji.tools.core.ui/.project b/org.eclipse.babel.tapiji.tools.core.ui/.project index 8dce816c..b8195d4e 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/.project +++ b/org.eclipse.babel.tapiji.tools.core.ui/.project @@ -1,28 +1,34 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.core.ui</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> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.core.ui</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> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.core.ui/build.properties b/org.eclipse.babel.tapiji.tools.core.ui/build.properties index f48d8dca..05b10a6c 100644 --- a/org.eclipse.babel.tapiji.tools.core.ui/build.properties +++ b/org.eclipse.babel.tapiji.tools.core.ui/build.properties @@ -1,11 +1,9 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ plugin.xml,\ icons/,\ about.html,\ - bin/,\ epl-v10.html src.includes = icons/,\ epl-v10.html,\ diff --git a/org.eclipse.babel.tapiji.tools.core.ui/pom.xml b/org.eclipse.babel.tapiji.tools.core.ui/pom.xml new file mode 100644 index 00000000..e616cef3 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.core.ui/pom.xml @@ -0,0 +1,12 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.core.ui</artifactId> + <packaging>eclipse-plugin</packaging> + + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.core/.classpath b/org.eclipse.babel.tapiji.tools.core/.classpath index 8a8f1668..c89ae12c 100644 --- a/org.eclipse.babel.tapiji.tools.core/.classpath +++ b/org.eclipse.babel.tapiji.tools.core/.classpath @@ -1,7 +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.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" path="src"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/org.eclipse.babel.tapiji.tools.core/.project b/org.eclipse.babel.tapiji.tools.core/.project index 6d850ba3..f1bd151e 100644 --- a/org.eclipse.babel.tapiji.tools.core/.project +++ b/org.eclipse.babel.tapiji.tools.core/.project @@ -1,28 +1,34 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.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> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.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> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF index 8b016220..dcd7fe89 100644 --- a/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF +++ b/org.eclipse.babel.tapiji.tools.core/META-INF/MANIFEST.MF @@ -18,8 +18,7 @@ Import-Package: org.eclipse.jdt.core.dom, org.eclipse.jface.text, org.eclipse.jface.text.contentassist, - org.eclipse.ui.ide, - org.eclipse.ui.texteditor + org.eclipse.ui.ide Export-Package: org.eclipse.babel.tapiji.tools.core, org.eclipse.babel.tapiji.tools.core.extensions, org.eclipse.babel.tapiji.tools.core.model, diff --git a/org.eclipse.babel.tapiji.tools.core/build.properties b/org.eclipse.babel.tapiji.tools.core/build.properties index 14cdf892..62a5dd41 100644 --- a/org.eclipse.babel.tapiji.tools.core/build.properties +++ b/org.eclipse.babel.tapiji.tools.core/build.properties @@ -1,10 +1,11 @@ +source.. = src/ +output.. = bin/ bin.includes = plugin.xml,\ META-INF/,\ .,\ schema/,\ about.html,\ - epl-v10.html,\ - bin/ + epl-v10.html src.includes = schema/,\ about.html,\ epl-v10.html diff --git a/org.eclipse.babel.tapiji.tools.core/pom.xml b/org.eclipse.babel.tapiji.tools.core/pom.xml new file mode 100644 index 00000000..4b216b50 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.core/pom.xml @@ -0,0 +1,12 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.core</artifactId> + <packaging>eclipse-plugin</packaging> + + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.feature/.project b/org.eclipse.babel.tapiji.tools.feature/.project index 2f00ea08..c3a11a11 100644 --- a/org.eclipse.babel.tapiji.tools.feature/.project +++ b/org.eclipse.babel.tapiji.tools.feature/.project @@ -1,17 +1,30 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipselabs.tapiji.tools.feature</name> - <comment></comment> - <projects> - </projects> - <buildSpec> - <buildCommand> - <name>org.eclipse.pde.FeatureBuilder</name> - <arguments> - </arguments> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.pde.FeatureNature</nature> - </natures> -</projectDescription> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.java.feature</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.wst.common.project.facet.core.builder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.FeatureBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.FeatureNature</nature> + <nature>org.eclipse.wst.common.project.facet.core.nature</nature> + </natures> +</projectDescription> + diff --git a/org.eclipse.babel.tapiji.tools.java.feature/.project b/org.eclipse.babel.tapiji.tools.java.feature/.project new file mode 100644 index 00000000..79c04ebb --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java.feature/.project @@ -0,0 +1,29 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.java.feature</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.wst.common.project.facet.core.builder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.FeatureBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.FeatureNature</nature> + <nature>org.eclipse.wst.common.project.facet.core.nature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.java.feature/build.properties b/org.eclipse.babel.tapiji.tools.java.feature/build.properties new file mode 100644 index 00000000..cc2efe00 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java.feature/build.properties @@ -0,0 +1,2 @@ +bin.includes = feature.xml +src.includes = feature.xml diff --git a/org.eclipse.babel.tapiji.tools.java.feature/feature.xml b/org.eclipse.babel.tapiji.tools.java.feature/feature.xml new file mode 100644 index 00000000..3ff85c71 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java.feature/feature.xml @@ -0,0 +1,75 @@ +<?xml version="1.0" encoding="UTF-8"?> +<feature + id="org.eclipse.babel.tapiji.tools.java.feature" + label="Feature" + version="0.0.2.qualifier"> + + <description url="http://www.example.com/description"> + [Enter Feature Description here.] + </description> + + <copyright url="http://www.example.com/copyright"> + [Enter Copyright Description here.] + </copyright> + + <license url="http://www.example.com/license"> + [Enter License Description here.] + </license> + + <plugin + id="org.eclipse.babel.core" + download-size="0" + install-size="0" + version="0.8.0.qualifier" + unpack="false"/> + + <plugin + id="org.eclipse.babel.editor" + download-size="0" + install-size="0" + version="0.8.0.qualifier" + unpack="false"/> + + <plugin + id="org.eclipse.babel.editor.nls" + download-size="0" + install-size="0" + version="0.8.0.qualifier" + fragment="true"/> + + <plugin + id="org.eclipse.babel.tapiji.tools.core" + download-size="0" + install-size="0" + version="0.0.2.qualifier" + unpack="false"/> + + <plugin + id="org.eclipse.babel.tapiji.tools.core.ui" + download-size="0" + install-size="0" + version="0.0.2.qualifier" + unpack="false"/> + + <plugin + id="org.eclipse.babel.tapiji.tools.java" + download-size="0" + install-size="0" + version="0.0.2.qualifier" + unpack="false"/> + + <plugin + id="org.eclipse.babel.tapiji.tools.java.ui" + download-size="0" + install-size="0" + version="0.0.2.qualifier" + unpack="false"/> + + <plugin + id="org.eclipse.babel.tapiji.tools.rbmanager" + download-size="0" + install-size="0" + version="0.0.2.qualifier" + unpack="false"/> + +</feature> diff --git a/org.eclipse.babel.tapiji.tools.java.feature/pom.xml b/org.eclipse.babel.tapiji.tools.java.feature/pom.xml new file mode 100644 index 00000000..7c358b84 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java.feature/pom.xml @@ -0,0 +1,11 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.java.feature</artifactId> + <packaging>eclipse-feature</packaging> + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java.ui/.classpath b/org.eclipse.babel.tapiji.tools.java.ui/.classpath index 8a8f1668..0b1bcf94 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/.classpath +++ b/org.eclipse.babel.tapiji.tools.java.ui/.classpath @@ -1,7 +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.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> +<?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.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src/"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/org.eclipse.babel.tapiji.tools.java.ui/.project b/org.eclipse.babel.tapiji.tools.java.ui/.project index fc555eb9..23e072de 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/.project +++ b/org.eclipse.babel.tapiji.tools.java.ui/.project @@ -20,8 +20,14 @@ <arguments> </arguments> </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.pde.PluginNature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> diff --git a/org.eclipse.babel.tapiji.tools.java.ui/build.properties b/org.eclipse.babel.tapiji.tools.java.ui/build.properties index f28f57e2..23b68b71 100644 --- a/org.eclipse.babel.tapiji.tools.java.ui/build.properties +++ b/org.eclipse.babel.tapiji.tools.java.ui/build.properties @@ -1,10 +1,8 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ plugin.xml,\ epl-v10.html,\ - about.html,\ - bin/ + about.html src.includes = epl-v10.html,\ about.html diff --git a/org.eclipse.babel.tapiji.tools.java.ui/pom.xml b/org.eclipse.babel.tapiji.tools.java.ui/pom.xml new file mode 100644 index 00000000..ee96979e --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java.ui/pom.xml @@ -0,0 +1,12 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.java.ui</artifactId> + <packaging>eclipse-plugin</packaging> + + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.java/.classpath b/org.eclipse.babel.tapiji.tools.java/.classpath index ad32c83a..0b1bcf94 100644 --- a/org.eclipse.babel.tapiji.tools.java/.classpath +++ b/org.eclipse.babel.tapiji.tools.java/.classpath @@ -2,6 +2,6 @@ <classpath> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> + <classpathentry kind="src" path="src/"/> + <classpathentry kind="output" path="target/classes"/> </classpath> diff --git a/org.eclipse.babel.tapiji.tools.java/.project b/org.eclipse.babel.tapiji.tools.java/.project index 72635d93..32af1709 100644 --- a/org.eclipse.babel.tapiji.tools.java/.project +++ b/org.eclipse.babel.tapiji.tools.java/.project @@ -20,8 +20,14 @@ <arguments> </arguments> </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> </buildSpec> <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> <nature>org.eclipse.pde.PluginNature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> diff --git a/org.eclipse.babel.tapiji.tools.java/build.properties b/org.eclipse.babel.tapiji.tools.java/build.properties index 8971f49e..302de5ff 100644 --- a/org.eclipse.babel.tapiji.tools.java/build.properties +++ b/org.eclipse.babel.tapiji.tools.java/build.properties @@ -1,9 +1,7 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ epl-v10.html,\ - about.html,\ - bin/ + about.html src.includes = epl-v10.html,\ about.html diff --git a/org.eclipse.babel.tapiji.tools.java/pom.xml b/org.eclipse.babel.tapiji.tools.java/pom.xml new file mode 100644 index 00000000..d6d9d996 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.java/pom.xml @@ -0,0 +1,12 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.java</artifactId> + <packaging>eclipse-plugin</packaging> + + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.parent/.classpath b/org.eclipse.babel.tapiji.tools.parent/.classpath new file mode 100644 index 00000000..b6fb50ec --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.parent/.classpath @@ -0,0 +1,6 @@ +<?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/J2SE-1.5"/> + <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/org.eclipse.babel.tapiji.tools.parent/.project b/org.eclipse.babel.tapiji.tools.parent/.project new file mode 100644 index 00000000..4d4e7268 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.parent/.project @@ -0,0 +1,23 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.parent</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.parent/pom.xml b/org.eclipse.babel.tapiji.tools.parent/pom.xml new file mode 100644 index 00000000..da968d44 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.parent/pom.xml @@ -0,0 +1,96 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <packaging>pom</packaging> + + <!-- tycho requires maven >= 3.0 --> + <prerequisites> + <maven>3.0</maven> + </prerequisites> + + <properties> + <tycho-version>0.16.0</tycho-version> + </properties> + <repositories> + <!-- configure p2 repository to resolve against --> + <repository> + <id>indigo</id> + <layout>p2</layout> + <url>http://download.eclipse.org/releases/indigo</url> + </repository> + </repositories> + + <build> + <plugins> + <plugin> + <!-- enable tycho build extension --> + <groupId>org.eclipse.tycho</groupId> + <artifactId>tycho-maven-plugin</artifactId> + <version>${tycho-version}</version> + <extensions>true</extensions> + </plugin> + + <!-- enable source bundle generation --> + <plugin> + <groupId>org.eclipse.tycho</groupId> + <artifactId>tycho-source-plugin</artifactId> + <version>${tycho-version}</version> + <executions> + <execution> + <id>plugin-source</id> + <goals> + <goal>plugin-source</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.eclipse.tycho</groupId> + <artifactId>target-platform-configuration</artifactId> + <version>${tycho-version}</version> + <configuration> + <target> + <artifact> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.target</artifactId> + <version>0.0.2-SNAPSHOT</version> + </artifact> + </target> + <!-- configure the p2 target environments for multi-platform build --> + <environments> + <environment> + <os>linux</os> + <ws>gtk</ws> + <arch>x86_64</arch> + </environment> + <environment> + <os>win32</os> + <ws>win32</ws> + <arch>x86_64</arch> + </environment> + </environments> + </configuration> + </plugin> + </plugins> + </build> + <modules> + <module>../org.eclipse.babel.core</module> + <module>../org.eclipse.babel.editor</module> + <module>../org.eclipse.babel.tapiji.tools.core</module> + <module>../org.eclipse.babel.tapiji.tools.core.ui</module> + <module>../org.eclipse.babel.tapiji.tools.java</module> + <module>../org.eclipse.babel.tapiji.tools.java.feature</module> + <module>../org.eclipse.babel.tapiji.tools.java.ui</module> + <module>../org.eclipse.babel.tapiji.tools.rbmanager</module> + <module>../org.eclipse.babel.editor.nls</module> + <module>../org.eclipse.babel.tapiji.tools.target</module> + <module>../org.eclipse.babel.core.pdeutils</module> + <module>../org.eclipse.babel.editor.rcp.compat</module> + </modules> +</project> diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/.classpath b/org.eclipse.babel.tapiji.tools.rbmanager/.classpath index 8a8f1668..0b1bcf94 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/.classpath +++ b/org.eclipse.babel.tapiji.tools.rbmanager/.classpath @@ -1,7 +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.6"/> - <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> - <classpathentry kind="src" path="src"/> - <classpathentry kind="output" path="bin"/> -</classpath> +<?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.6"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src/"/> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/.project b/org.eclipse.babel.tapiji.tools.rbmanager/.project index c01fd6c1..96471afa 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/.project +++ b/org.eclipse.babel.tapiji.tools.rbmanager/.project @@ -1,28 +1,34 @@ -<?xml version="1.0" encoding="UTF-8"?> -<projectDescription> - <name>org.eclipse.babel.tapiji.tools.rbmanager</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> +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.rbmanager</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> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties index 030c8540..8584b90f 100644 --- a/org.eclipse.babel.tapiji.tools.rbmanager/build.properties +++ b/org.eclipse.babel.tapiji.tools.rbmanager/build.properties @@ -2,13 +2,10 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ .,\ - bin/,\ icons/,\ epl-v10.html,\ about.html,\ plugin.xml src.includes = icons/,\ - bin/,\ epl-v10.html,\ about.html - diff --git a/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml b/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml new file mode 100644 index 00000000..c1247ec9 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.rbmanager/pom.xml @@ -0,0 +1,12 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.rbmanager</artifactId> + <packaging>eclipse-plugin</packaging> + + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file diff --git a/org.eclipse.babel.tapiji.tools.target/.project b/org.eclipse.babel.tapiji.tools.target/.project new file mode 100644 index 00000000..84c8bf8e --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.target/.project @@ -0,0 +1,17 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.eclipse.babel.tapiji.tools.target</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.m2e.core.maven2Builder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.m2e.core.maven2Nature</nature> + </natures> +</projectDescription> diff --git a/org.eclipse.babel.tapiji.tools.target/org.eclipse.babel.tapiji.tools.target.target b/org.eclipse.babel.tapiji.tools.target/org.eclipse.babel.tapiji.tools.target.target new file mode 100644 index 00000000..03d9c1ef --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.target/org.eclipse.babel.tapiji.tools.target.target @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<?pde version="3.6"?> + +<target name="org.eclipse.babel.tapiji.tools.target" sequenceNumber="0"> +<locations> +<location includeAllPlatforms="false" includeMode="planner" includeSource="true" type="InstallableUnit"> +<unit id="epp.package.java" version="1.4.2.20120213-0813"/> +<repository location="http://download.eclipse.org/releases/indigo"/> +</location> +</locations> +</target> diff --git a/org.eclipse.babel.tapiji.tools.target/pom.xml b/org.eclipse.babel.tapiji.tools.target/pom.xml new file mode 100644 index 00000000..c5115dc0 --- /dev/null +++ b/org.eclipse.babel.tapiji.tools.target/pom.xml @@ -0,0 +1,11 @@ +<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <artifactId>org.eclipse.babel.tapiji.tools.target</artifactId> + <packaging>eclipse-target-definition </packaging> + <parent> + <groupId>org.eclipse.babel.tapiji.tools</groupId> + <artifactId>org.eclipse.babel.tapiji.tools.parent</artifactId> + <version>0.0.2-SNAPSHOT</version> + <relativePath>../org.eclipse.babel.tapiji.tools.parent</relativePath> + </parent> +</project> \ No newline at end of file
89c5498bdfd50a213b8d8e46324266883f6209ea
camel
Added another test--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@921999 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/test/java/org/apache/camel/util/CaseInsensitiveMapTest.java b/camel-core/src/test/java/org/apache/camel/util/CaseInsensitiveMapTest.java index 45e7a5eb2b788..dedc37c2a296d 100644 --- a/camel-core/src/test/java/org/apache/camel/util/CaseInsensitiveMapTest.java +++ b/camel-core/src/test/java/org/apache/camel/util/CaseInsensitiveMapTest.java @@ -279,7 +279,7 @@ public void testRomeksUsingRegularHashMap() { assertEquals("cake", map.get("FOO")); } - public void testRomeksTransferedToHashMapAfterwards() { + public void testRomeksTransferredToHashMapAfterwards() { Map<String, Object> map = new CaseInsensitiveMap(); map.put("Foo", "cheese"); map.put("FOO", "cake"); @@ -349,4 +349,21 @@ public void testCopyToAnotherMapPreserveKeyCasePutAll() { assertEquals(2, other.size()); } + public void testCopyToAnotherMapPreserveKeyCaseCtr() { + Map<String, Object> map = new CaseInsensitiveMap(); + map.put("Foo", "cheese"); + map.put("BAR", "cake"); + assertEquals(2, map.size()); + assertEquals(true, map.containsKey("foo")); + assertEquals(true, map.containsKey("bar")); + + Map<String, Object> other = new HashMap<String, Object>(map); + + assertEquals(false, other.containsKey("foo")); + assertEquals(true, other.containsKey("Foo")); + assertEquals(false, other.containsKey("bar")); + assertEquals(true, other.containsKey("BAR")); + assertEquals(2, other.size()); + } + } \ No newline at end of file
cc1d8448ed6de75c22eb4af46d21580211517d5e
kotlin
Prevent lazy types to be accidentally computed in- debug--
c
https://github.com/JetBrains/kotlin
diff --git a/core/descriptor.loader.java/src/org/jetbrains/jet/lang/resolve/java/lazy/types/LazyType.kt b/core/descriptor.loader.java/src/org/jetbrains/jet/lang/resolve/java/lazy/types/LazyType.kt index c92e2e21c2be9..25bf6ca60ff39 100644 --- a/core/descriptor.loader.java/src/org/jetbrains/jet/lang/resolve/java/lazy/types/LazyType.kt +++ b/core/descriptor.loader.java/src/org/jetbrains/jet/lang/resolve/java/lazy/types/LazyType.kt @@ -47,4 +47,14 @@ abstract class LazyType(storageManager: StorageManager) : AbstractJetType() { override fun isError()= getConstructor().getDeclarationDescriptor().inn({ d -> ErrorUtils.isError(d)}, false) override fun getAnnotations(): List<AnnotationDescriptor> = listOf() + + override fun toString(): String? { + if (!_typeConstructor.isComputed()) { + return "Type constructor is not computed" + } + if (!_arguments.isComputed()) { + return "" + getConstructor() + "<arguments are not computed>" + } + return super<AbstractJetType>.toString() + } } diff --git a/core/descriptors/src/org/jetbrains/jet/lang/types/AbstractJetType.java b/core/descriptors/src/org/jetbrains/jet/lang/types/AbstractJetType.java index 1d7f57878c10b..d5ddee2fd7428 100644 --- a/core/descriptors/src/org/jetbrains/jet/lang/types/AbstractJetType.java +++ b/core/descriptors/src/org/jetbrains/jet/lang/types/AbstractJetType.java @@ -41,7 +41,7 @@ public final boolean equals(Object obj) { } @Override - public final String toString() { + public String toString() { List<TypeProjection> arguments = getArguments(); return getConstructor() + (arguments.isEmpty() ? "" : "<" + argumentsToString(arguments) + ">") + (isNullable() ? "?" : ""); }
46349a89d9d332e1f7c9f976f65efc79ea46cd29
hbase
HBASE-6667 TestCatalogJanitor occasionally fails;- PATCH THAT ADDS DEBUG AROUND FAILING TEST--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1379682 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/CatalogJanitor.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/CatalogJanitor.java index 9b076f315528..8c0f05084e62 100644 --- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/CatalogJanitor.java +++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/CatalogJanitor.java @@ -245,6 +245,7 @@ boolean cleanParent(final HRegionInfo parent, Result rowContent) this.services.getAssignmentManager().regionOffline(parent); } FileSystem fs = this.services.getMasterFileSystem().getFileSystem(); + LOG.debug("Archiving parent region:" + parent); HFileArchiver.archiveRegion(fs, parent); MetaEditor.deleteRegion(this.server.getCatalogTracker(), parent); result = true; diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java index 39ba8c75318c..377ef7363434 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestCatalogJanitor.java @@ -32,6 +32,8 @@ import java.util.SortedMap; import java.util.TreeMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; @@ -76,6 +78,8 @@ @Category(SmallTests.class) public class TestCatalogJanitor { + private static final Log LOG = LogFactory.getLog(TestCatalogJanitor.class); + /** * Pseudo server for below tests. * Be sure to call stop on the way out else could leave some mess around. @@ -529,6 +533,10 @@ public void testScanDoesNotCleanRegionsWithExistingParents() throws Exception { janitor.join(); } + /** + * Test that we correctly archive all the storefiles when a region is deleted + * @throws Exception + */ @Test public void testArchiveOldRegion() throws Exception { String table = "table"; @@ -546,10 +554,10 @@ public void testArchiveOldRegion() throws Exception { HRegionInfo parent = new HRegionInfo(htd.getName(), Bytes.toBytes("aaa"), Bytes.toBytes("eee")); HRegionInfo splita = new HRegionInfo(htd.getName(), Bytes.toBytes("aaa"), Bytes.toBytes("ccc")); HRegionInfo splitb = new HRegionInfo(htd.getName(), Bytes.toBytes("ccc"), Bytes.toBytes("eee")); + // Test that when both daughter regions are in place, that we do not // remove the parent. - Result r = createResult(parent, splita, splitb); - + Result parentMetaRow = createResult(parent, splita, splitb); FileSystem fs = FileSystem.get(htu.getConfiguration()); Path rootdir = services.getMasterFileSystem().getRootDir(); // have to set the root directory since we use it in HFileDisposer to figure out to get to the @@ -559,32 +567,53 @@ public void testArchiveOldRegion() throws Exception { Path tabledir = HTableDescriptor.getTableDir(rootdir, htd.getName()); Path storedir = HStore.getStoreHomedir(tabledir, parent.getEncodedName(), htd.getColumnFamilies()[0].getName()); - - // delete the file and ensure that the files have been archived Path storeArchive = HFileArchiveUtil.getStoreArchivePath(services.getConfiguration(), parent, tabledir, htd.getColumnFamilies()[0].getName()); + LOG.debug("Table dir:" + tabledir); + LOG.debug("Store dir:" + storedir); + LOG.debug("Store archive dir:" + storeArchive); - // enable archiving, make sure that files get archived - addMockStoreFiles(2, services, storedir); + // add a couple of store files that we can check for + FileStatus[] mockFiles = addMockStoreFiles(2, services, storedir); // get the current store files for comparison FileStatus[] storeFiles = fs.listStatus(storedir); + int index = 0; for (FileStatus file : storeFiles) { - System.out.println("Have store file:" + file.getPath()); + LOG.debug("Have store file:" + file.getPath()); + assertEquals("Got unexpected store file", mockFiles[index].getPath(), + storeFiles[index].getPath()); + index++; } // do the cleaning of the parent - assertTrue(janitor.cleanParent(parent, r)); + assertTrue(janitor.cleanParent(parent, parentMetaRow)); + LOG.debug("Finished cleanup of parent region"); // and now check to make sure that the files have actually been archived FileStatus[] archivedStoreFiles = fs.listStatus(storeArchive); + logFiles("archived files", storeFiles); + logFiles("archived files", archivedStoreFiles); + assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs); // cleanup + FSUtils.delete(fs, rootdir, true); services.stop("Test finished"); - server.stop("shutdown"); + server.stop("Test finished"); janitor.join(); } + /** + * @param description description of the files for logging + * @param storeFiles the status of the files to log + */ + private void logFiles(String description, FileStatus[] storeFiles) { + LOG.debug("Current " + description + ": "); + for (FileStatus file : storeFiles) { + LOG.debug(file.getPath()); + } + } + /** * Test that if a store file with the same name is present as those already backed up cause the * already archived files to be timestamped backup @@ -657,7 +686,7 @@ public void testDuplicateHFileResolution() throws Exception { janitor.join(); } - private void addMockStoreFiles(int count, MasterServices services, Path storedir) + private FileStatus[] addMockStoreFiles(int count, MasterServices services, Path storedir) throws IOException { // get the existing store files FileSystem fs = services.getMasterFileSystem().getFileSystem(); @@ -669,9 +698,11 @@ private void addMockStoreFiles(int count, MasterServices services, Path storedir dos.writeBytes("Some data: " + i); dos.close(); } + LOG.debug("Adding " + count + " store files to the storedir:" + storedir); // make sure the mock store files are there FileStatus[] storeFiles = fs.listStatus(storedir); - assertEquals(count, storeFiles.length); + assertEquals("Didn't have expected store files", count, storeFiles.length); + return storeFiles; } private String setRootDirAndCleanIt(final HBaseTestingUtility htu, diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/HFileArchiveTestingUtil.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/HFileArchiveTestingUtil.java index 1b48cb7db92c..fa6c44b84f2d 100644 --- a/hbase-server/src/test/java/org/apache/hadoop/hbase/util/HFileArchiveTestingUtil.java +++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/util/HFileArchiveTestingUtil.java @@ -85,29 +85,29 @@ public static boolean compareArchiveToOriginal(FileStatus[] previous, FileStatus /** * Compare the archived files to the files in the original directory - * @param previous original files that should have been archived - * @param archived files that were archived + * @param expected original files that should have been archived + * @param actual files that were archived * @param fs filessystem on which the archiving took place * @throws IOException */ - public static void assertArchiveEqualToOriginal(FileStatus[] previous, FileStatus[] archived, + public static void assertArchiveEqualToOriginal(FileStatus[] expected, FileStatus[] actual, FileSystem fs) throws IOException { - assertArchiveEqualToOriginal(previous, archived, fs, false); + assertArchiveEqualToOriginal(expected, actual, fs, false); } /** * Compare the archived files to the files in the original directory - * @param previous original files that should have been archived - * @param archived files that were archived + * @param expected original files that should have been archived + * @param actual files that were archived * @param fs {@link FileSystem} on which the archiving took place * @param hasTimedBackup <tt>true</tt> if we expect to find an archive backup directory with a * copy of the files in the archive directory (and the original files). * @throws IOException */ - public static void assertArchiveEqualToOriginal(FileStatus[] previous, FileStatus[] archived, + public static void assertArchiveEqualToOriginal(FileStatus[] expected, FileStatus[] actual, FileSystem fs, boolean hasTimedBackup) throws IOException { - List<List<String>> lists = getFileLists(previous, archived); + List<List<String>> lists = getFileLists(expected, actual); List<String> original = lists.get(0); Collections.sort(original);
b370969690e5463374c4f47e6f8543c07c5ae4d9
spring-framework
added public "validateDatabaseSchema" method to- Hibernate LocalSessionFactoryBean (SPR-
a
https://github.com/spring-projects/spring-framework
diff --git a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java index 07ede778ab49..5bc2c55ec2b5 100644 --- a/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java +++ b/org.springframework.orm/src/main/java/org/springframework/orm/hibernate3/LocalSessionFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2010 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. @@ -875,21 +875,7 @@ public final Configuration getConfiguration() { @Override protected void afterSessionFactoryCreation() throws Exception { if (this.schemaUpdate) { - DataSource dataSource = getDataSource(); - if (dataSource != null) { - // Make given DataSource available for the schema update, - // which unfortunately reinstantiates a ConnectionProvider. - configTimeDataSourceHolder.set(dataSource); - } - try { - updateDatabaseSchema(); - } - finally { - if (dataSource != null) { - // Reset DataSource holder. - configTimeDataSourceHolder.set(null); - } - } + updateDatabaseSchema(); } } @@ -916,6 +902,93 @@ public void destroy() throws HibernateException { } + /** + * Execute schema update script, determined by the Configuration object + * used for creating the SessionFactory. A replacement for Hibernate's + * SchemaUpdate class, for automatically executing schema update scripts + * on application startup. Can also be invoked manually. + * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed + * SessionFactory to be able to invoke this method, e.g. via + * <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>. + * <p>Uses the SessionFactory that this bean generates for accessing a + * JDBC connection to perform the script. + * @throws DataAccessException in case of script execution errors + * @see #setSchemaUpdate + * @see org.hibernate.cfg.Configuration#generateSchemaUpdateScript + * @see org.hibernate.tool.hbm2ddl.SchemaUpdate + */ + public void updateDatabaseSchema() throws DataAccessException { + logger.info("Updating database schema for Hibernate SessionFactory"); + DataSource dataSource = getDataSource(); + if (dataSource != null) { + // Make given DataSource available for the schema update. + configTimeDataSourceHolder.set(dataSource); + } + try { + HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory()); + hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); + hibernateTemplate.execute( + new HibernateCallback<Object>() { + public Object doInHibernate(Session session) throws HibernateException, SQLException { + Connection con = session.connection(); + Dialect dialect = Dialect.getDialect(getConfiguration().getProperties()); + DatabaseMetadata metadata = new DatabaseMetadata(con, dialect); + String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata); + executeSchemaScript(con, sql); + return null; + } + } + ); + } + finally { + if (dataSource != null) { + configTimeDataSourceHolder.set(null); + } + } + } + + /** + * Execute schema creation script, determined by the Configuration object + * used for creating the SessionFactory. A replacement for Hibernate's + * SchemaValidator class, to be invoked after application startup. + * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed + * SessionFactory to be able to invoke this method, e.g. via + * <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>. + * <p>Uses the SessionFactory that this bean generates for accessing a + * JDBC connection to perform the script. + * @throws DataAccessException in case of script execution errors + * @see org.hibernate.cfg.Configuration#validateSchema + * @see org.hibernate.tool.hbm2ddl.SchemaValidator + */ + public void validateDatabaseSchema() throws DataAccessException { + logger.info("Validating database schema for Hibernate SessionFactory"); + DataSource dataSource = getDataSource(); + if (dataSource != null) { + // Make given DataSource available for the schema update. + configTimeDataSourceHolder.set(dataSource); + } + try { + HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory()); + hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); + hibernateTemplate.execute( + new HibernateCallback<Object>() { + public Object doInHibernate(Session session) throws HibernateException, SQLException { + Connection con = session.connection(); + Dialect dialect = Dialect.getDialect(getConfiguration().getProperties()); + DatabaseMetadata metadata = new DatabaseMetadata(con, dialect, false); + getConfiguration().validateSchema(dialect, metadata); + return null; + } + } + ); + } + finally { + if (dataSource != null) { + configTimeDataSourceHolder.set(null); + } + } + } + /** * Execute schema drop script, determined by the Configuration object * used for creating the SessionFactory. A replacement for Hibernate's @@ -923,8 +996,8 @@ public void destroy() throws HibernateException { * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>. - * <p>Uses the SessionFactory that this bean generates for accessing a JDBC - * connection to perform the script. + * <p>Uses the SessionFactory that this bean generates for accessing a + * JDBC connection to perform the script. * @throws org.springframework.dao.DataAccessException in case of script execution errors * @see org.hibernate.cfg.Configuration#generateDropSchemaScript * @see org.hibernate.tool.hbm2ddl.SchemaExport#drop @@ -952,59 +1025,38 @@ public Object doInHibernate(Session session) throws HibernateException, SQLExcep * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed * SessionFactory to be able to invoke this method, e.g. via * <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>. - * <p>Uses the SessionFactory that this bean generates for accessing a JDBC - * connection to perform the script. + * <p>Uses the SessionFactory that this bean generates for accessing a + * JDBC connection to perform the script. * @throws DataAccessException in case of script execution errors * @see org.hibernate.cfg.Configuration#generateSchemaCreationScript * @see org.hibernate.tool.hbm2ddl.SchemaExport#create */ public void createDatabaseSchema() throws DataAccessException { logger.info("Creating database schema for Hibernate SessionFactory"); - HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory()); - hibernateTemplate.execute( - new HibernateCallback<Object>() { - public Object doInHibernate(Session session) throws HibernateException, SQLException { - Connection con = session.connection(); - Dialect dialect = Dialect.getDialect(getConfiguration().getProperties()); - String[] sql = getConfiguration().generateSchemaCreationScript(dialect); - executeSchemaScript(con, sql); - return null; - } - } - ); - } - - /** - * Execute schema update script, determined by the Configuration object - * used for creating the SessionFactory. A replacement for Hibernate's - * SchemaUpdate class, for automatically executing schema update scripts - * on application startup. Can also be invoked manually. - * <p>Fetch the LocalSessionFactoryBean itself rather than the exposed - * SessionFactory to be able to invoke this method, e.g. via - * <code>LocalSessionFactoryBean lsfb = (LocalSessionFactoryBean) ctx.getBean("&mySessionFactory");</code>. - * <p>Uses the SessionFactory that this bean generates for accessing a JDBC - * connection to perform the script. - * @throws DataAccessException in case of script execution errors - * @see #setSchemaUpdate - * @see org.hibernate.cfg.Configuration#generateSchemaUpdateScript - * @see org.hibernate.tool.hbm2ddl.SchemaUpdate - */ - public void updateDatabaseSchema() throws DataAccessException { - logger.info("Updating database schema for Hibernate SessionFactory"); - HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory()); - hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); - hibernateTemplate.execute( - new HibernateCallback<Object>() { - public Object doInHibernate(Session session) throws HibernateException, SQLException { - Connection con = session.connection(); - Dialect dialect = Dialect.getDialect(getConfiguration().getProperties()); - DatabaseMetadata metadata = new DatabaseMetadata(con, dialect); - String[] sql = getConfiguration().generateSchemaUpdateScript(dialect, metadata); - executeSchemaScript(con, sql); - return null; + DataSource dataSource = getDataSource(); + if (dataSource != null) { + // Make given DataSource available for the schema update. + configTimeDataSourceHolder.set(dataSource); + } + try { + HibernateTemplate hibernateTemplate = new HibernateTemplate(getSessionFactory()); + hibernateTemplate.execute( + new HibernateCallback<Object>() { + public Object doInHibernate(Session session) throws HibernateException, SQLException { + Connection con = session.connection(); + Dialect dialect = Dialect.getDialect(getConfiguration().getProperties()); + String[] sql = getConfiguration().generateSchemaCreationScript(dialect); + executeSchemaScript(con, sql); + return null; + } } + ); + } + finally { + if (dataSource != null) { + configTimeDataSourceHolder.set(null); } - ); + } } /**
0f964dada0a88faeac1b93bde703a75662aaebef
intellij-community
aware of not sourcemap file--
p
https://github.com/JetBrains/intellij-community
diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMapDecoder.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMapDecoder.java index a0f475741b46b..431a1156ae891 100644 --- a/platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMapDecoder.java +++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMapDecoder.java @@ -67,10 +67,10 @@ public static SourceMap decode(@NotNull CharSequence in, @NotNull Function<List< @Nullable private static SourceMap parseMap(JsonReaderEx reader, - int line, - int column, - List<MappingEntry> mappings, - @NotNull Function<List<String>, SourceResolver> sourceResolverFactory) throws IOException { + int line, + int column, + List<MappingEntry> mappings, + @NotNull Function<List<String>, SourceResolver> sourceResolverFactory) throws IOException { reader.beginObject(); String sourceRoot = null; JsonReaderEx sourcesReader = null; @@ -120,6 +120,12 @@ else if (propertyName.equals("file")) { } reader.close(); + // check it before other checks, probably it is not sourcemap file + if (StringUtil.isEmpty(encodedMappings)) { + // empty map + return null; + } + if (version != 3) { throw new IOException("Unsupported sourcemap version: " + version); } @@ -128,11 +134,6 @@ else if (propertyName.equals("file")) { throw new IOException("sources is not specified"); } - if (StringUtil.isEmpty(encodedMappings)) { - // empty map - return null; - } - List<String> sources = readSources(sourcesReader, sourceRoot); @SuppressWarnings("unchecked")
c2c9352c0ca7e07fc8150f32295f93f667723b8c
restlet-framework-java
- Fixed bug in XstreamRepresentation- failing to use the DOM XML driver. Reported by Florian Georg.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt index 9e6d8e6478..ddbeabe918 100644 --- a/build/tmpl/text/changes.txt +++ b/build/tmpl/text/changes.txt @@ -46,6 +46,8 @@ Changes log Reported by Nicolas Janicaud. - Fixed potential NPE in ComponentHelper#checkVirtualHost. Reported by Matt J. Watson. + - Fixed bug in XstreamRepresentation failing to use the DOM + XML driver. Reported by Florian Georg. - Enhancements - Upgraded Jetty library to version 6.1.18. - SpringServerServlet nows gets its component fully configured, diff --git a/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java b/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java index 40e765e06a..56b9183259 100644 --- a/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java +++ b/modules/org.restlet.ext.xstream/src/org/restlet/ext/xstream/XstreamRepresentation.java @@ -118,7 +118,7 @@ protected XStream createXstream(MediaType mediaType) { result = new XStream(getJsonDriverClass().newInstance()); result.setMode(XStream.NO_REFERENCES); } else { - result = new XStream(getJsonDriverClass().newInstance()); + result = new XStream(getXmlDriverClass().newInstance()); } } catch (Exception e) { Context.getCurrentLogger().log(Level.WARNING,
c6c48e6c78a1a5f1c7cdae1db5f63f1869c67549
Search_api
Issue #1310970 by drunken monkey: Added improved UI help for determining which fields are available for sorting.
a
https://github.com/lucidworks/drupal_search_api
diff --git a/CHANGELOG.txt b/CHANGELOG.txt index bbde5ab9..42abb27f 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,5 +1,7 @@ Search API 1.x, dev (xx/xx/xxxx): --------------------------------- +- #1310970 by drunken monkey: Added improved UI help for determining which + fields are available for sorting. - #1886738 by chx, Jelle_S, drunken monkey: Added Role filter data alteration. - #1837782 by drunken monkey: Fixed enabling of indexes through the Status tab. - #1382170 by orakili, lliss, drunken monkey: Added OR filtering for Views diff --git a/search_api.admin.inc b/search_api.admin.inc index 7e848d7d..48e0aeb6 100644 --- a/search_api.admin.inc +++ b/search_api.admin.inc @@ -1491,7 +1491,7 @@ function search_api_admin_index_fields(array $form, array &$form_state, SearchAp $form['description'] = array( '#type' => 'item', '#title' => t('Select fields to index'), - '#description' => t('<p>The datatype of a field determines how it can be used for searching and filtering. ' . + '#description' => t('<p>The datatype of a field determines how it can be used for searching and filtering. Fields indexed with type "Fulltext" and multi-valued fields (marked with <sup>1</sup>) cannot be used for sorting. ' . 'The boost is used to give additional weight to certain fields, e.g. titles or tags. It only takes effect for fulltext fields.</p>' . '<p>Whether detailed field types are supported depends on the type of server this index resides on. ' . 'In any case, fields of type "Fulltext" will always be fulltext-searchable.</p>'), @@ -1502,6 +1502,10 @@ function search_api_admin_index_fields(array $form, array &$form_state, SearchAp } foreach ($fields as $key => $info) { $form['fields'][$key]['title']['#markup'] = check_plain($info['name']); + if (search_api_is_list_type($info['type'])) { + $form['fields'][$key]['title']['#markup'] .= ' <sup><a href="#note-multi-valued" class="note-ref">1</a></sup>'; + $multi_valued_field_present = TRUE; + } $form['fields'][$key]['machine_name']['#markup'] = check_plain($key); if (isset($info['description'])) { $form['fields'][$key]['description'] = array( @@ -1591,6 +1595,10 @@ function search_api_admin_index_fields(array $form, array &$form_state, SearchAp } } + if (!empty($multi_valued_field_present)) { + $form['note']['#markup'] = '<div id="note-multi-valued"><small><sup>1</sup> ' . t('Multi-valued field') . '</small></div>'; + } + $form['submit'] = array( '#type' => 'submit', '#value' => t('Save changes'), @@ -1770,11 +1778,13 @@ function theme_search_api_admin_fields_table($variables) { } } + $note = isset($form['note']) ? $form['note'] : ''; $submit = $form['submit']; $additional = isset($form['additional']) ? $form['additional'] : FALSE; - unset($form['submit'], $form['additional']); + unset($form['note'], $form['submit'], $form['additional']); $output = drupal_render_children($form); $output .= theme('table', array('header' => $header, 'rows' => $rows)); + $output .= render($note); $output .= render($submit); if ($additional) { $output .= render($additional);
cda87c7020bebd44018c627d3a5f01ebc856b38a
Vala
girparser: Use the same code for parsing callbacks as methods Fixes part of bug 621834.
c
https://github.com/GNOME/vala/
diff --git a/vala/valagirparser.vala b/vala/valagirparser.vala index 90cdf83823..7b63728f50 100644 --- a/vala/valagirparser.vala +++ b/vala/valagirparser.vala @@ -811,27 +811,7 @@ public class Vala.GirParser : CodeVisitor { } Delegate parse_callback () { - start_element ("callback"); - string name = reader.get_attribute ("name"); - next (); - DataType return_type; - if (current_token == MarkupTokenType.START_ELEMENT && reader.name == "return-value") { - return_type = parse_return_value (); - } else { - return_type = new VoidType (); - } - var d = new Delegate (name, return_type, get_current_src ()); - d.access = SymbolAccessibility.PUBLIC; - if (current_token == MarkupTokenType.START_ELEMENT && reader.name == "parameters") { - start_element ("parameters"); - next (); - while (current_token == MarkupTokenType.START_ELEMENT) { - d.add_parameter (parse_parameter ()); - } - end_element ("parameters"); - } - end_element ("callback"); - return d; + return this.parse_function ("callback") as Delegate; } Method parse_constructor (string? parent_ctype = null) { @@ -888,7 +868,7 @@ public class Vala.GirParser : CodeVisitor { public bool keep; } - Method parse_method (string element_name) { + Symbol parse_function (string element_name) { start_element (element_name); string name = reader.get_attribute ("name"); string cname = reader.get_attribute ("c:identifier"); @@ -901,19 +881,34 @@ public class Vala.GirParser : CodeVisitor { } else { return_type = new VoidType (); } - var m = new Method (name, return_type, get_current_src ()); - m.access = SymbolAccessibility.PUBLIC; + + Symbol s; + + if (element_name == "callback") { + s = new Delegate (name, return_type, get_current_src ()); + } else { + s = new Method (name, return_type, get_current_src ()); + } + + s.access = SymbolAccessibility.PUBLIC; if (cname != null) { - m.set_cname (cname); + if (s is Method) { + ((Method) s).set_cname (cname); + } else { + ((Delegate) s).set_cname (cname); + } } if (element_name == "virtual-method" || element_name == "callback") { - m.is_virtual = true; + if (s is Method) { + ((Method) s).is_virtual = true; + } + if (invoker != null){ - m.name = invoker; + s.name = invoker; } } else if (element_name == "function") { - m.binding = MemberBinding.STATIC; + ((Method) s).binding = MemberBinding.STATIC; } var parameters = new ArrayList<MethodInfo> (); @@ -943,8 +938,8 @@ public class Vala.GirParser : CodeVisitor { if (element_name != "callback" || !first) { var info = new MethodInfo(param, array_length_idx, closure_idx, destroy_idx); - if (scope == "async") { - m.coroutine = true; + if (s is Method && scope == "async") { + ((Method) s).coroutine = true; info.keep = false; } @@ -992,7 +987,11 @@ public class Vala.GirParser : CodeVisitor { /* add_parameter sets carray_length_parameter_position and cdelegate_target_parameter_position so do it first*/ - m.add_parameter (info.param); + if (s is Method) { + ((Method) s).add_parameter (info.param); + } else { + ((Delegate) s).add_parameter (info.param); + } if (info.array_length_idx != -1) { if ((info.array_length_idx) - add >= parameters.size) { @@ -1025,12 +1024,16 @@ public class Vala.GirParser : CodeVisitor { } if (throws_string == "1") { - m.add_error_type (new ErrorType (null, null)); + s.add_error_type (new ErrorType (null, null)); } end_element (element_name); - return m; + return s; } + Method parse_method (string element_name) { + return this.parse_function (element_name) as Method; + } + Signal parse_signal () { start_element ("glib:signal"); string name = string.joinv ("_", reader.get_attribute ("name").split ("-"));
c32ece3060175565124ba73b8b54fea091803eec
Delta Spike
fix JavaDoc - still did refer to old name of the class
p
https://github.com/apache/deltaspike
diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/metadata/AnnotationInstanceProvider.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/metadata/AnnotationInstanceProvider.java index 22398afd2..d5238f23d 100644 --- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/metadata/AnnotationInstanceProvider.java +++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/metadata/AnnotationInstanceProvider.java @@ -42,7 +42,7 @@ * String annotationClassName = ...; * Class<? extends annotation> annotationClass = * (Class<? extends Annotation>) ClassUtils.getClassLoader(null).loadClass(annotationClassName); - * Annotation a = DefaultAnnotation.of(annotationClass) + * Annotation a = AnnotationInstanceProvider.of(annotationClass) * </pre> */ public class AnnotationInstanceProvider implements Annotation, InvocationHandler, Serializable
da957f9a45b98add085443da67593c01c0c63639
Vala
gstreamer-cdda,dataprotocol-0.10: fix some invalid enum values
c
https://github.com/GNOME/vala/
diff --git a/vapi/gstreamer-cdda-0.10.vapi b/vapi/gstreamer-cdda-0.10.vapi index 3e5b57c70b..a0621dcddc 100644 --- a/vapi/gstreamer-cdda-0.10.vapi +++ b/vapi/gstreamer-cdda-0.10.vapi @@ -48,10 +48,10 @@ namespace Gst { public uint start; public weak Gst.TagList tags; } - [CCode (cprefix = "", cheader_filename = "gst/cdda/gstcddabasesrc.h")] + [CCode (cprefix = "GST_CDDA_BASE_SRC_MODE_", cheader_filename = "gst/cdda/gstcddabasesrc.h")] public enum CddaBaseSrcMode { - Stream consists of a single track, - Stream consists of the whole disc + NORMAL, + CONTINUOUS } [CCode (cheader_filename = "gst/cdda/gstcddabasesrc.h")] public const string TAG_CDDA_TRACK_TAGS; diff --git a/vapi/gstreamer-dataprotocol-0.10.vapi b/vapi/gstreamer-dataprotocol-0.10.vapi index f62b5b882c..6af1e0bf3e 100644 --- a/vapi/gstreamer-dataprotocol-0.10.vapi +++ b/vapi/gstreamer-dataprotocol-0.10.vapi @@ -26,10 +26,10 @@ namespace Gst { CAPS, EVENT_NONE } - [CCode (cprefix = "", cheader_filename = "gst/dataprotocol/dataprotocol.h")] + [CCode (cprefix = "GST_DP_VERSION_", cheader_filename = "gst/dataprotocol/dataprotocol.h")] public enum DPVersion { - GDP Version 0.2, - GDP Version 1.0 + @0_2, + @1_0 } [CCode (cheader_filename = "gst/dataprotocol/dataprotocol.h", has_target = false)] public delegate bool DPHeaderFromBufferFunction (Gst.Buffer buffer, Gst.DPHeaderFlag flags, uint length, uchar header); diff --git a/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10-custom.vala b/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10-custom.vala new file mode 100644 index 0000000000..d8a25085cb --- /dev/null +++ b/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10-custom.vala @@ -0,0 +1,7 @@ +namespace Gst { + [CCode (cprefix = "GST_CDDA_BASE_SRC_MODE_", cheader_filename = "gst/cdda/gstcddabasesrc.h")] + public enum CddaBaseSrcMode { + NORMAL, + CONTINUOUS + } +} diff --git a/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10.metadata b/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10.metadata index 56e03b7b32..172efd3e4b 100644 --- a/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10.metadata +++ b/vapi/packages/gstreamer-cdda-0.10/gstreamer-cdda-0.10.metadata @@ -1 +1,2 @@ Gst cprefix="Gst" lower_case_cprefix="gst_" cheader_filename="gst/cdda/gstcddabasesrc.h" +GstCddaBaseSrcMode hidden="1" diff --git a/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10-custom.vala b/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10-custom.vala new file mode 100644 index 0000000000..aa73d23daa --- /dev/null +++ b/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10-custom.vala @@ -0,0 +1,7 @@ +namespace Gst { + [CCode (cprefix = "GST_DP_VERSION_", cheader_filename = "gst/dataprotocol/dataprotocol.h")] + public enum DPVersion { + @0_2, + @1_0 + } +} diff --git a/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10.metadata b/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10.metadata index b69d6f35f5..4f7e680e6d 100644 --- a/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10.metadata +++ b/vapi/packages/gstreamer-dataprotocol-0.10/gstreamer-dataprotocol-0.10.metadata @@ -1,2 +1,2 @@ Gst cprefix="Gst" lower_case_cprefix="gst_" cheader_filename="gst/dataprotocol/dataprotocol.h" - +GstDPVersion hidden="1"
20cb52c5ac94dc2fc1a36930f341938e91025706
Vala
girwriter: Write accessor methods for interface properties Fixes bug 733115
a
https://github.com/GNOME/vala/
diff --git a/codegen/valagirwriter.vala b/codegen/valagirwriter.vala index 3aff8c6324..e855e1e71f 100644 --- a/codegen/valagirwriter.vala +++ b/codegen/valagirwriter.vala @@ -578,6 +578,32 @@ public class Vala.GIRWriter : CodeVisitor { } } + foreach (var prop in iface.get_properties ()) { + if (prop.is_abstract || prop.is_virtual) { + if (prop.get_accessor != null) { + var m = prop.get_accessor.get_method (); + write_indent (); + buffer.append_printf("<field name=\"%s\">\n", m.name); + indent++; + do_write_signature (m, "callback", true, m.name, CCodeBaseModule.get_ccode_name (m), m.get_parameters (), m.return_type, m.tree_can_fail, false); + indent--; + write_indent (); + buffer.append_printf ("</field>\n"); + } + + if (prop.set_accessor != null) { + var m = prop.set_accessor.get_method (); + write_indent (); + buffer.append_printf("<field name=\"%s\">\n", m.name); + indent++; + do_write_signature (m, "callback", true, m.name, CCodeBaseModule.get_ccode_name (m), m.get_parameters (), m.return_type, m.tree_can_fail, false); + indent--; + write_indent (); + buffer.append_printf ("</field>\n"); + } + } + } + indent--; write_indent (); buffer.append_printf ("</record>\n"); @@ -1128,6 +1154,20 @@ public class Vala.GIRWriter : CodeVisitor { indent--; write_indent (); buffer.append_printf ("</property>\n"); + + if (prop.get_accessor != null) { + var m = prop.get_accessor.get_method (); + if (m != null) { + visit_method (m); + } + } + + if (prop.set_accessor != null) { + var m = prop.set_accessor.get_method (); + if (m != null) { + visit_method (m); + } + } } public override void visit_signal (Signal sig) { diff --git a/vala/valapropertyaccessor.vala b/vala/valapropertyaccessor.vala index 466fe6c181..057e442079 100644 --- a/vala/valapropertyaccessor.vala +++ b/vala/valapropertyaccessor.vala @@ -114,6 +114,30 @@ public class Vala.PropertyAccessor : Subroutine { } } + /** + * Get the method representing this property accessor + * @return null if the accessor is neither readable nor writable + */ + public Method? get_method () { + Method? m = null; + if (readable) { + m = new Method ("get_"+prop.name, value_type, source_reference, comment); + } else if (writable) { + m = new Method ("set_"+prop.name, new VoidType(), source_reference, comment); + m.add_parameter (value_parameter.copy ()); + } + + if (m != null) { + m.owner = prop.owner; + m.access = access; + m.binding = prop.binding; + m.is_abstract = prop.is_abstract; + m.is_virtual = prop.is_virtual; + } + + return m; + } + public override bool check (CodeContext context) { if (checked) { return !error; @@ -130,6 +154,10 @@ public class Vala.PropertyAccessor : Subroutine { context.analyzer.current_symbol = this; + if (writable || construction) { + value_parameter = new Parameter ("value", value_type, source_reference); + } + if (prop.source_type == SourceFileType.SOURCE) { if (body == null && !prop.interface_only && !prop.is_abstract) { /* no accessor body specified, insert default body */ @@ -157,7 +185,6 @@ public class Vala.PropertyAccessor : Subroutine { if (body != null) { if (writable || construction) { - value_parameter = new Parameter ("value", value_type, source_reference); body.scope.add (value_parameter.name, value_parameter); }
4713ae66eda8b146b13970dbbd3e5ab5b92ed6da
bendisposto$prob
added support for simple theory mapping files
a
https://github.com/hhu-stups/prob-rodinplugin
diff --git a/de.prob.core/src/de/prob/eventb/translator/Theories.java b/de.prob.core/src/de/prob/eventb/translator/Theories.java index 53e916cf..6b598b55 100644 --- a/de.prob.core/src/de/prob/eventb/translator/Theories.java +++ b/de.prob.core/src/de/prob/eventb/translator/Theories.java @@ -1,9 +1,16 @@ package de.prob.eventb.translator; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Collection; +import java.util.Collections; import java.util.LinkedList; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; +import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eventb.core.IEventBProject; @@ -41,6 +48,9 @@ import de.prob.prolog.output.IPrologTermOutput; import de.prob.prolog.output.StructuredPrologOutput; import de.prob.prolog.term.PrologTerm; +import de.prob.tmparser.OperatorMapping; +import de.prob.tmparser.TheoryMappingException; +import de.prob.tmparser.TheoryMappingParser; public class Theories { private static final String PROB_THEORY_MAPPING_SUFFIX = "ptm"; @@ -74,9 +84,12 @@ public static void translate(IEventBProject project, IPrologTermOutput pout) * the translation is currently very unstable and erroneous. Writing in a * Prolog object makes sure that the output stream to the Prolog process * will not be corrupted. + * + * @throws TranslationFailedException */ private static void savePrintTranslation(IDeployedTheoryRoot theory, - IPrologTermOutput opto) throws RodinDBException { + IPrologTermOutput opto) throws RodinDBException, + TranslationFailedException { final StructuredPrologOutput pto = new StructuredPrologOutput(); printTranslation(theory, pto); @@ -86,7 +99,8 @@ private static void savePrintTranslation(IDeployedTheoryRoot theory, } private static void printTranslation(IDeployedTheoryRoot theory, - StructuredPrologOutput pto) throws RodinDBException { + StructuredPrologOutput pto) throws RodinDBException, + TranslationFailedException { pto.openTerm("theory"); printIdentifiers(theory.getSCTypeParameters(), pto); printDataTypes(theory, pto); @@ -97,23 +111,51 @@ private static void printTranslation(IDeployedTheoryRoot theory, } private static void findProBMappingFile(IDeployedTheoryRoot theory, - IPrologTermOutput pto) { + IPrologTermOutput pto) throws TranslationFailedException { final String theoryName = theory.getComponentName(); final IPath path = new Path(theoryName + "." + PROB_THEORY_MAPPING_SUFFIX); final IProject project = theory.getRodinProject().getProject(); + final Collection<OperatorMapping> mappings; if (project.exists(path)) { final IFile file = project.getFile(path); - readAndPrintMapping(file, theory, pto); + mappings = readMappingFile(file, theory); } else { - pto.printAtom("none"); + mappings = Collections.emptyList(); } + printMappings(mappings, pto); } - private static void readAndPrintMapping(IFile file, - IDeployedTheoryRoot theory, IPrologTermOutput pto) { - // TODO Auto-generated method stub + private static Collection<OperatorMapping> readMappingFile(IFile file, + IDeployedTheoryRoot theory) throws TranslationFailedException { + try { + final InputStream input = file.getContents(); + final String name = theory.getComponentName(); + final Reader reader = new InputStreamReader(input); + return TheoryMappingParser.parseTheoryMapping(name, reader); + } catch (CoreException e) { + throw new TranslationFailedException(e); + } catch (TheoryMappingException e) { + throw new TranslationFailedException(e); + } catch (IOException e) { + throw new TranslationFailedException(e); + } + } + private static void printMappings(Collection<OperatorMapping> mappings, + IPrologTermOutput pto) { + pto.openList(); + // Currently, we support only one kind of operator mapping, just tagging + // an operator to indicate that an optimized ProB implementation should + // be used. We do not invest any effort in preparing future kinds of + // other operator mappings. + for (OperatorMapping mapping : mappings) { + pto.openTerm("tag"); + pto.printAtom(mapping.getOperatorName()); + pto.printAtom(mapping.getSpec()); + pto.closeTerm(); + } + pto.closeList(); } private static void printIdentifiers(ISCIdentifierElement[] identifiers, @@ -250,7 +292,8 @@ private static void printTypedIdentifier(final String functor, final IPrologTermOutput pto) throws RodinDBException { pto.openTerm(functor); pto.printAtom(id.getIdentifierString()); - printType(id.getType(ff), ff, pto); + Type type = id.getType(ff); + printType(type, ff, pto); pto.closeTerm(); }
c7b8537c6d600a1ae25131a8c7a226e4cb9b3d24
Vala
glib-2.0: use g_strcmp0 instead of strcmp
a
https://github.com/GNOME/vala/
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi index 54d27c445a..11eff0af02 100644 --- a/vapi/glib-2.0.vapi +++ b/vapi/glib-2.0.vapi @@ -3366,10 +3366,10 @@ namespace GLib { public delegate int CompareFunc (void* a, void* b); public delegate int CompareDataFunc (void* a, void* b); - - [CCode (cname = "strcmp")] + + [CCode (cname = "g_strcmp0")] public static GLib.CompareFunc strcmp; - + /* Double-ended Queues */ [Compact]
5d8fac86d749c9ea98eb7eda58655fe5fa3616d0
spring-framework
Add timeout async request handling to OSIV- components--This change adds async web request timeout handling to OSIV filters-and interceptors to ensure the session or entity manager is released.--Issue: SPR-10874-
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/AsyncRequestInterceptor.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/AsyncRequestInterceptor.java new file mode 100644 index 000000000000..38879158544a --- /dev/null +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/AsyncRequestInterceptor.java @@ -0,0 +1,109 @@ +/* + * Copyright 2002-2013 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 + * + * http://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.springframework.orm.hibernate4.support; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.SessionFactory; +import org.springframework.orm.hibernate4.SessionFactoryUtils; +import org.springframework.orm.hibernate4.SessionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; + +import java.util.concurrent.Callable; + +/** + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and + * OpenSessionInViewInterceptor. + * + * Ensures the following: + * 1) The session is bound/unbound when "callable processing" is started + * 2) The session is closed if an async request times out + * + * @author Rossen Stoyanchev + * @since 3.2.5 + */ +public class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { + + private static Log logger = LogFactory.getLog(AsyncRequestInterceptor.class); + + private final SessionFactory sessionFactory; + + private final SessionHolder sessionHolder; + + private volatile boolean timeoutInProgress; + + public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { + this.sessionFactory = sessionFactory; + this.sessionHolder = sessionHolder; + } + + @Override + public <T> void preProcess(NativeWebRequest request, Callable<T> task) { + bindSession(); + } + + public void bindSession() { + this.timeoutInProgress = false; + TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); + } + + @Override + public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.sessionFactory); + } + + @Override + public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) { + this.timeoutInProgress = true; + return RESULT_NONE; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception { + closeAfterTimeout(); + } + + private void closeAfterTimeout() { + if (this.timeoutInProgress) { + logger.debug("Closing Hibernate Session after async request timeout"); + SessionFactoryUtils.closeSession(sessionHolder.getSession()); + } + } + + // Implementation of DeferredResultProcessingInterceptor methods + + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object result) { } + + @Override + public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) { + this.timeoutInProgress = true; + return true; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) { + closeAfterTimeout(); + } +} diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java index 0045a5d3f873..6ab5668293c2 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java @@ -16,14 +16,6 @@ package org.springframework.orm.hibernate4.support; -import java.io.IOException; -import java.util.concurrent.Callable; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Session; @@ -33,13 +25,17 @@ import org.springframework.orm.hibernate4.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + /** * Servlet 2.3 Filter that binds a Hibernate Session to the thread for the entire * processing of the request. Intended for the "Open Session in View" pattern, @@ -143,8 +139,9 @@ protected void doFilterInternal( SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - asyncManager.registerCallableInterceptor(key, - new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(sessionFactory, sessionHolder); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } } @@ -216,37 +213,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private static class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionFactory sessionFactory; - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { - this.sessionFactory = sessionFactory; - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(this.sessionFactory); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); - } - } } diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java index 4d82160eb7c5..c1c46bc24865 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java @@ -33,9 +33,7 @@ import org.springframework.web.context.request.AsyncWebRequestInterceptor; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; /** * Spring web request interceptor that binds a Hibernate {@code Session} to the @@ -119,8 +117,10 @@ public void preHandle(WebRequest request) throws DataAccessException { SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, - new SessionBindingCallableInterceptor(sessionHolder)); + AsyncRequestInterceptor asyncRequestInterceptor = + new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); + asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); + asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); } } @@ -200,35 +200,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(getSessionFactory()); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); - } - } - } diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/AsyncRequestInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/AsyncRequestInterceptor.java new file mode 100644 index 000000000000..4e161d87df7b --- /dev/null +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/AsyncRequestInterceptor.java @@ -0,0 +1,110 @@ +/* + * Copyright 2002-2013 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 + * + * http://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.springframework.orm.hibernate3.support; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.SessionFactory; +import org.springframework.orm.hibernate3.SessionFactoryUtils; +import org.springframework.orm.hibernate3.SessionHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; + +import java.util.concurrent.Callable; + +/** + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and + * OpenSessionInViewInterceptor. + * + * Ensures the following: + * 1) The session is bound/unbound when "callable processing" is started + * 2) The session is closed if an async request times out + * + * @author Rossen Stoyanchev + * @since 3.2.5 + */ +class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { + + private static final Log logger = LogFactory.getLog(AsyncRequestInterceptor.class); + + private final SessionFactory sessionFactory; + + private final SessionHolder sessionHolder; + + private volatile boolean timeoutInProgress; + + + public AsyncRequestInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { + this.sessionFactory = sessionFactory; + this.sessionHolder = sessionHolder; + } + + @Override + public <T> void preProcess(NativeWebRequest request, Callable<T> task) { + bindSession(); + } + + public void bindSession() { + this.timeoutInProgress = false; + TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); + } + + @Override + public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.sessionFactory); + } + + @Override + public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) { + this.timeoutInProgress = true; + return RESULT_NONE; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception { + closeAfterTimeout(); + } + + private void closeAfterTimeout() { + if (this.timeoutInProgress) { + logger.debug("Closing Hibernate Session after async request timeout"); + SessionFactoryUtils.closeSession(sessionHolder.getSession()); + } + } + + // Implementation of DeferredResultProcessingInterceptor methods + + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) {} + public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) {} + public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object result) {} + + @Override + public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) { + this.timeoutInProgress = true; + return true; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) { + closeAfterTimeout(); + } + +} diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java index 7aab7c89100a..ced44d6f5e27 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java @@ -17,7 +17,6 @@ package org.springframework.orm.hibernate3.support; import java.io.IOException; -import java.util.concurrent.Callable; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -33,10 +32,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -212,8 +208,9 @@ protected void doFilterInternal( SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - asyncManager.registerCallableInterceptor(key, - new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(sessionFactory, sessionHolder); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } } } @@ -319,38 +316,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private static class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionFactory sessionFactory; - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { - this.sessionFactory = sessionFactory; - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(this.sessionFactory); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); - } - } - } diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java index 9daf211d5034..d42ce03c129d 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java @@ -29,9 +29,7 @@ import org.springframework.web.context.request.AsyncWebRequestInterceptor; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; /** * Spring web request interceptor that binds a Hibernate {@code Session} to the @@ -173,8 +171,10 @@ public void preHandle(WebRequest request) throws DataAccessException { SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, - new SessionBindingCallableInterceptor(sessionHolder)); + AsyncRequestInterceptor asyncRequestInterceptor = + new AsyncRequestInterceptor(getSessionFactory(), sessionHolder); + asyncManager.registerCallableInterceptor(participateAttributeName, asyncRequestInterceptor); + asyncManager.registerDeferredResultInterceptor(participateAttributeName, asyncRequestInterceptor); } else { // deferred close mode @@ -272,34 +272,8 @@ private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, Str if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private class SessionBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final SessionHolder sessionHolder; - - public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { - this.sessionHolder = sessionHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(getSessionFactory()); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); - } - } } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/AsyncRequestInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/AsyncRequestInterceptor.java new file mode 100644 index 000000000000..046bd8f65014 --- /dev/null +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/AsyncRequestInterceptor.java @@ -0,0 +1,111 @@ +/* + * Copyright 2002-2013 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 + * + * http://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.springframework.orm.jpa.support; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.orm.jpa.EntityManagerFactoryUtils; +import org.springframework.orm.jpa.EntityManagerHolder; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; +import org.springframework.web.context.request.async.DeferredResult; +import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; + +import javax.persistence.EntityManagerFactory; +import java.util.concurrent.Callable; + +/** + * An interceptor with asynchronous web requests used in OpenSessionInViewFilter and + * OpenSessionInViewInterceptor. + * + * Ensures the following: + * 1) The session is bound/unbound when "callable processing" is started + * 2) The session is closed if an async request times out + * + * @author Rossen Stoyanchev + * @since 3.2.5 + */ +public class AsyncRequestInterceptor extends CallableProcessingInterceptorAdapter + implements DeferredResultProcessingInterceptor { + + private static Log logger = LogFactory.getLog(AsyncRequestInterceptor.class); + + private final EntityManagerFactory emFactory; + + private final EntityManagerHolder emHolder; + + private volatile boolean timeoutInProgress; + + + public AsyncRequestInterceptor(EntityManagerFactory emFactory, EntityManagerHolder emHolder) { + this.emFactory = emFactory; + this.emHolder = emHolder; + } + + @Override + public <T> void preProcess(NativeWebRequest request, Callable<T> task) { + bindSession(); + } + + public void bindSession() { + this.timeoutInProgress = false; + TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder); + } + + @Override + public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.emFactory); + } + + @Override + public <T> Object handleTimeout(NativeWebRequest request, Callable<T> task) { + this.timeoutInProgress = true; + return RESULT_NONE; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, Callable<T> task) throws Exception { + closeAfterTimeout(); + } + + private void closeAfterTimeout() { + if (this.timeoutInProgress) { + logger.debug("Closing JPA EntityManager after async request timeout"); + EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager()); + } + } + + // Implementation of DeferredResultProcessingInterceptor methods + + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void preProcess(NativeWebRequest request, DeferredResult<T> deferredResult) { } + public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferredResult, Object result) { } + + @Override + public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) { + this.timeoutInProgress = true; + return true; // give other interceptors a chance to handle the timeout + } + + @Override + public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) { + closeAfterTimeout(); + } +} + diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java index 24febab2514a..b518fe262d22 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java @@ -34,9 +34,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; -import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.*; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -166,7 +164,9 @@ protected void doFilterInternal( EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(emf, emHolder); - asyncManager.registerCallableInterceptor(key, new EntityManagerBindingCallableInterceptor(emf, emHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder); + asyncManager.registerCallableInterceptor(key, interceptor); + asyncManager.registerDeferredResultInterceptor(key, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); @@ -242,38 +242,8 @@ private boolean applyEntityManagerBindingInterceptor(WebAsyncManager asyncManage if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - /** - * Bind and unbind the {@code EntityManager} to the current thread. - */ - private static class EntityManagerBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final EntityManagerFactory emFactory; - - private final EntityManagerHolder emHolder; - - - public EntityManagerBindingCallableInterceptor(EntityManagerFactory emFactory, EntityManagerHolder emHolder) { - this.emFactory = emFactory; - this.emHolder = emHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(this.emFactory); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder); - } - } - } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java index fdebb8c8c867..dbc88b73e381 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java @@ -93,8 +93,9 @@ public void preHandle(WebRequest request) throws DataAccessException { EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); - asyncManager.registerCallableInterceptor(participateAttributeName, - new EntityManagerBindingCallableInterceptor(emHolder)); + AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(getEntityManagerFactory(), emHolder); + asyncManager.registerCallableInterceptor(participateAttributeName, interceptor); + asyncManager.registerDeferredResultInterceptor(participateAttributeName, interceptor); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); @@ -154,36 +155,8 @@ private boolean applyCallableInterceptor(WebAsyncManager asyncManager, String ke if (asyncManager.getCallableInterceptor(key) == null) { return false; } - ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + ((AsyncRequestInterceptor) asyncManager.getCallableInterceptor(key)).bindSession(); return true; } - - /** - * Bind and unbind the Hibernate {@code Session} to the current thread. - */ - private class EntityManagerBindingCallableInterceptor extends CallableProcessingInterceptorAdapter { - - private final EntityManagerHolder emHolder; - - - public EntityManagerBindingCallableInterceptor(EntityManagerHolder emHolder) { - this.emHolder = emHolder; - } - - @Override - public <T> void preProcess(NativeWebRequest request, Callable<T> task) { - initializeThread(); - } - - @Override - public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object concurrentResult) { - TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); - } - - private void initializeThread() { - TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), this.emHolder); - } - } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java index 0777c3ae11c2..c57dbcfc1e4f 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java @@ -18,13 +18,11 @@ import java.io.IOException; import java.sql.Connection; +import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.transaction.TransactionManager; import org.hibernate.FlushMode; @@ -35,11 +33,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.mock.web.test.MockFilterConfig; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.mock.web.test.PassThroughFilterChain; +import org.springframework.mock.web.test.*; import org.springframework.orm.hibernate3.HibernateAccessor; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.orm.hibernate3.SessionFactoryUtils; @@ -50,9 +44,11 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; +import org.springframework.web.context.request.async.StandardServletAsyncWebRequest; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; +import org.springframework.web.util.NestedServletException; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; @@ -79,6 +75,7 @@ public class OpenSessionInViewTests { public void setup() { this.sc = new MockServletContext(); this.request = new MockHttpServletRequest(sc); + this.request.setAsyncSupported(true); this.response = new MockHttpServletResponse(); this.webRequest = new ServletWebRequest(this.request); } @@ -142,12 +139,10 @@ public void testOpenSessionInViewInterceptorAsyncScenario() throws Exception { interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); - + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); - asyncManager.startCallableProcessing(new Callable<String>() { @Override public String call() throws Exception { @@ -166,13 +161,58 @@ public String call() throws Exception { interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(sf)); + verify(session, never()).close(); + interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(sf)); verify(session).setFlushMode(FlushMode.MANUAL); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); - verify(asyncWebRequest).startAsync(); + verify(session).close(); + } + + @Test + public void testOpenSessionInViewInterceptorAsyncTimeoutScenario() throws Exception { + + // Initial request thread + + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + + OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); + interceptor.setSessionFactory(sf); + + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + + interceptor.preHandle(this.webRequest); + assertTrue(TransactionSynchronizationManager.hasResource(sf)); + + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); + asyncManager.setAsyncWebRequest(asyncWebRequest); + asyncManager.startCallableProcessing(new Callable<String>() { + @Override + public String call() throws Exception { + return "anything"; + } + }); + + interceptor.afterConcurrentHandlingStarted(this.webRequest); + assertFalse(TransactionSynchronizationManager.hasResource(sf)); + verify(session, never()).close(); + + // Async request timeout + + MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onTimeout(new AsyncEvent(asyncContext)); + } + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onComplete(new AsyncEvent(asyncContext)); + } + + verify(session).close(); } @Test @@ -376,9 +416,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo } }; - AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); - given(asyncWebRequest.isAsyncStarted()).willReturn(true); - + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); @@ -393,19 +431,89 @@ public String call() throws Exception { filter.doFilter(this.request, this.response, filterChain); assertFalse(TransactionSynchronizationManager.hasResource(sf)); assertEquals(1, count.get()); - + verify(session, never()).close(); // Async dispatch after concurrent handling produces result ... + this.request.setAsyncStarted(false); assertFalse(TransactionSynchronizationManager.hasResource(sf)); filter.doFilter(this.request, this.response, filterChain); assertFalse(TransactionSynchronizationManager.hasResource(sf)); assertEquals(2, count.get()); verify(session).setFlushMode(FlushMode.MANUAL); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); - verify(asyncWebRequest).startAsync(); + verify(session).close(); + + wac.close(); + } + + @Test + public void testOpenSessionInViewFilterAsyncTimeoutScenario() throws Exception { + + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + + // Initial request during which concurrent handling starts.. + + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + + StaticWebApplicationContext wac = new StaticWebApplicationContext(); + wac.setServletContext(sc); + wac.getDefaultListableBeanFactory().registerSingleton("sessionFactory", sf); + wac.refresh(); + sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); + + MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); + final OpenSessionInViewFilter filter = new OpenSessionInViewFilter(); + filter.init(filterConfig); + + final AtomicInteger count = new AtomicInteger(0); + final AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + final MockHttpServletRequest request = this.request; + + final FilterChain filterChain = new FilterChain() { + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) + throws NestedServletException { + + assertTrue(TransactionSynchronizationManager.hasResource(sf)); + count.incrementAndGet(); + + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); + asyncManager.setAsyncWebRequest(asyncWebRequest); + try { + asyncManager.startCallableProcessing(new Callable<String>() { + @Override + public String call() throws Exception { + return "anything"; + } + }); + } + catch (Exception e) { + throw new NestedServletException("", e); + } + } + }; + + assertFalse(TransactionSynchronizationManager.hasResource(sf)); + filter.doFilter(this.request, this.response, filterChain); + assertFalse(TransactionSynchronizationManager.hasResource(sf)); + assertEquals(1, count.get()); + verify(session, never()).close(); + + // Async request timeout ... + + MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onTimeout(new AsyncEvent(asyncContext)); + } + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onComplete(new AsyncEvent(asyncContext)); + } + + verify(session).close(); wac.close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java index 901448e0a6d2..5ad164e9dc36 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java @@ -21,25 +21,19 @@ import java.util.concurrent.atomic.AtomicInteger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.mock.web.test.MockFilterConfig; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.mock.web.test.PassThroughFilterChain; +import org.springframework.mock.web.test.*; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.async.AsyncWebRequest; +import org.springframework.web.context.request.async.StandardServletAsyncWebRequest; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; @@ -59,6 +53,12 @@ public class OpenEntityManagerInViewTests { private EntityManagerFactory factory; + private MockHttpServletRequest request; + + private MockHttpServletResponse response; + + private ServletWebRequest webRequest; + @Before public void setUp() throws Exception { @@ -66,6 +66,11 @@ public void setUp() throws Exception { manager = mock(EntityManager.class); given(factory.createEntityManager()).willReturn(manager); + + this.request = new MockHttpServletRequest(); + this.request.setAsyncSupported(true); + this.response = new MockHttpServletResponse(); + this.webRequest = new ServletWebRequest(this.request); } @After @@ -79,13 +84,13 @@ public void tearDown() throws Exception { @Test public void testOpenEntityManagerInViewInterceptor() throws Exception { OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); - interceptor.setEntityManagerFactory(factory); + interceptor.setEntityManagerFactory(this.factory); MockServletContext sc = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(sc); interceptor.preHandle(new ServletWebRequest(request)); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); + assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); // check that further invocations simply participate interceptor.preHandle(new ServletWebRequest(request)); @@ -120,16 +125,13 @@ public void testOpenEntityManagerInViewInterceptorAsyncScenario() throws Excepti OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); interceptor.setEntityManagerFactory(factory); - MockServletContext sc = new MockServletContext(); - MockHttpServletRequest request = new MockHttpServletRequest(sc); - ServletWebRequest webRequest = new ServletWebRequest(request); + given(factory.createEntityManager()).willReturn(this.manager); - interceptor.preHandle(webRequest); + interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); - - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(webRequest); + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.webRequest); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { @@ -139,17 +141,12 @@ public String call() throws Exception { } }); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); - verify(asyncWebRequest).startAsync(); - - interceptor.afterConcurrentHandlingStarted(webRequest); + interceptor.afterConcurrentHandlingStarted(this.webRequest); assertFalse(TransactionSynchronizationManager.hasResource(factory)); // Async dispatch thread - interceptor.preHandle(webRequest); + interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(factory)); asyncManager.clearConcurrentResult(); @@ -168,15 +165,57 @@ public String call() throws Exception { interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); - interceptor.postHandle(webRequest, null); + interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - given(manager.isOpen()).willReturn(true); + given(this.manager.isOpen()).willReturn(true); - interceptor.afterCompletion(webRequest, null); + interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(factory)); - verify(manager).close(); + verify(this.manager).close(); + } + + @Test + public void testOpenEntityManagerInViewInterceptorAsyncTimeoutScenario() throws Exception { + + // Initial request thread + + OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); + interceptor.setEntityManagerFactory(factory); + + given(this.factory.createEntityManager()).willReturn(this.manager); + + interceptor.preHandle(this.webRequest); + assertTrue(TransactionSynchronizationManager.hasResource(this.factory)); + + AsyncWebRequest asyncWebRequest = new StandardServletAsyncWebRequest(this.request, this.response); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); + asyncManager.setAsyncWebRequest(asyncWebRequest); + asyncManager.startCallableProcessing(new Callable<String>() { + @Override + public String call() throws Exception { + return "anything"; + } + }); + + interceptor.afterConcurrentHandlingStarted(this.webRequest); + assertFalse(TransactionSynchronizationManager.hasResource(this.factory)); + + // Async request timeout + + given(this.manager.isOpen()).willReturn(true); + + MockAsyncContext asyncContext = (MockAsyncContext) this.request.getAsyncContext(); + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onTimeout(new AsyncEvent(asyncContext)); + } + for (AsyncListener listener : asyncContext.getListeners()) { + listener.onComplete(new AsyncEvent(asyncContext)); + } + + verify(this.manager).close(); } @Test @@ -257,8 +296,6 @@ public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception { wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); - MockHttpServletRequest request = new MockHttpServletRequest(sc); - MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2"); @@ -297,7 +334,7 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); given(asyncWebRequest.isAsyncStarted()).willReturn(true); - WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { @@ -309,13 +346,12 @@ public String call() throws Exception { assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - filter2.doFilter(request, response, filterChain3); + filter2.doFilter(this.request, this.response, filterChain3); assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); assertEquals(1, count.get()); assertEquals(1, count2.get()); assertNotNull(request.getAttribute("invoked")); - verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); @@ -328,13 +364,13 @@ public String call() throws Exception { assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); - filter.doFilter(request, response, filterChain3); + filter.doFilter(this.request, this.response, filterChain3); assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); assertEquals(2, count.get()); assertEquals(2, count2.get()); - verify(manager).close(); + verify(this.manager).close(); verify(manager2).close(); wac.close(); diff --git a/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java index 42409c6fe2fa..0298f7db4fe4 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java @@ -31,7 +31,8 @@ public abstract class DeferredResultProcessingInterceptorAdapter implements Defe * This implementation is empty. */ @Override - public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception { + public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) + throws Exception { } /** @@ -50,7 +51,8 @@ public <T> void postProcess(NativeWebRequest request, DeferredResult<T> deferred } /** - * This implementation returns {@code true} by default. + * This implementation returns {@code true} by default allowing other interceptors + * to be given a chance to handle the timeout. */ @Override public <T> boolean handleTimeout(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception {
3c4d64750b9fba05c95bb6cc359fe2e6fac9127f
brandonborkholder$glg2d
Brand new functionality that repaints only child components, not the entire scene.
p
https://github.com/brandonborkholder/glg2d
diff --git a/src/main/java/glg2d/G2DGLCanvas.java b/src/main/java/glg2d/G2DGLCanvas.java index 5c74a7d7..5da5cfac 100644 --- a/src/main/java/glg2d/G2DGLCanvas.java +++ b/src/main/java/glg2d/G2DGLCanvas.java @@ -21,14 +21,15 @@ import java.awt.Dimension; import java.awt.Graphics; import java.awt.LayoutManager2; +import java.awt.Rectangle; import java.io.Serializable; +import java.util.Map; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLContext; import javax.media.opengl.GLDrawableFactory; -import javax.media.opengl.GLEventListener; import javax.media.opengl.GLJPanel; import javax.media.opengl.GLPbuffer; import javax.media.opengl.Threading; @@ -41,17 +42,19 @@ public class G2DGLCanvas extends JComponent { protected GLAutoDrawable canvas; - protected boolean drawGL = true; + protected boolean drawGL; /** * @see #removeNotify() */ protected GLPbuffer sideContext; - protected GLEventListener g2dglListener; + protected G2DGLEventListener g2dglListener; protected JComponent drawableComponent; + GLGraphics2D g2d; + public static GLCapabilities getDefaultCapabalities() { GLCapabilities caps = new GLCapabilities(); caps.setRedBits(8); @@ -78,6 +81,7 @@ public G2DGLCanvas(GLCapabilities capabilities) { add((Component) canvas); RepaintManager.setCurrentManager(GLAwareRepaintManager.INSTANCE); + setGLDrawing(true); } public G2DGLCanvas(JComponent drawableComponent) { @@ -120,6 +124,7 @@ public boolean isGLDrawing() { public void setGLDrawing(boolean drawGL) { this.drawGL = drawGL; ((Component) canvas).setVisible(drawGL); + setOpaque(drawGL); repaint(); } @@ -130,6 +135,9 @@ public void setDrawableComponent(JComponent component) { if (g2dglListener != null) { canvas.removeGLEventListener(g2dglListener); + if (sideContext != null) { + sideContext.removeGLEventListener(g2dglListener); + } } if (drawableComponent != null) { @@ -140,6 +148,10 @@ public void setDrawableComponent(JComponent component) { if (drawableComponent != null) { g2dglListener = createG2DListener(drawableComponent); canvas.addGLEventListener(g2dglListener); + if (sideContext != null) { + sideContext.addGLEventListener(g2dglListener); + } + add(drawableComponent); forceViewportToNativeDraw(drawableComponent); @@ -150,7 +162,7 @@ public void setDrawableComponent(JComponent component) { * Creates the GLEventListener that will draw the given component to the * canvas. */ - protected GLEventListener createG2DListener(JComponent drawingComponent) { + protected G2DGLEventListener createG2DListener(JComponent drawingComponent) { return new G2DGLEventListener(drawingComponent); } @@ -213,8 +225,12 @@ public void run() { @Override public void paint(Graphics g) { - if (drawGL && drawableComponent != null) { - canvas.display(); + if (drawGL && drawableComponent != null && canvas != null) { + if (g2d == null) { + canvas.display(); + } else { + drawableComponent.paint(g2d); + } } else { super.paint(g); } @@ -257,6 +273,17 @@ protected void forceViewportToNativeDraw(Container parent) { } } + @Override + public Graphics getGraphics() { + return g2d == null ? super.getGraphics() : g2d.create(); + } + + public void paintGLImmediately(Map<JComponent, Rectangle> r) { + g2dglListener.canvas = this; + g2dglListener.repaints = r; + canvas.display(); + } + /** * Implements a simple layout where all the components are the same size as * the parent. diff --git a/src/main/java/glg2d/G2DGLEventListener.java b/src/main/java/glg2d/G2DGLEventListener.java index a65247f6..cf64d05d 100644 --- a/src/main/java/glg2d/G2DGLEventListener.java +++ b/src/main/java/glg2d/G2DGLEventListener.java @@ -17,11 +17,15 @@ package glg2d; import java.awt.Component; +import java.awt.Rectangle; +import java.util.Map; +import java.util.Map.Entry; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLContext; import javax.media.opengl.GLEventListener; +import javax.swing.JComponent; import javax.swing.RepaintManager; /** @@ -32,6 +36,10 @@ public class G2DGLEventListener implements GLEventListener { protected Component baseComponent; + Map<JComponent, Rectangle> repaints; + + G2DGLCanvas canvas; + /** * Creates a new listener that will paint using the {@code GLGraphics2D} * object on each call to {@link #display(GLAutoDrawable)}. The provided @@ -130,10 +138,30 @@ protected void paintGL(GLGraphics2D g2d) { RepaintManager mgr = RepaintManager.currentManager(baseComponent); boolean doubleBuffer = mgr.isDoubleBufferingEnabled(); mgr.setDoubleBufferingEnabled(false); - baseComponent.paint(g2d); + + if (isPaintingDirtyRects()) { + paintDirtyRects(); + } else { + baseComponent.paint(g2d); + } + mgr.setDoubleBufferingEnabled(doubleBuffer); } + protected boolean isPaintingDirtyRects() { + return repaints != null; + } + + protected void paintDirtyRects() { + canvas.g2d = g2d; + for (Entry<JComponent, Rectangle> entry : repaints.entrySet()) { + entry.getKey().paintImmediately(entry.getValue()); + } + + repaints = null; + canvas.g2d = null; + } + @Override public void init(GLAutoDrawable drawable) { reshape(drawable, 0, 0, drawable.getWidth(), drawable.getWidth()); diff --git a/src/main/java/glg2d/GLAwareRepaintManager.java b/src/main/java/glg2d/GLAwareRepaintManager.java index 9251b7b4..1151bc59 100644 --- a/src/main/java/glg2d/GLAwareRepaintManager.java +++ b/src/main/java/glg2d/GLAwareRepaintManager.java @@ -17,25 +17,78 @@ package glg2d; import java.awt.Container; +import java.awt.Rectangle; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.Map; +import javax.media.opengl.GLAutoDrawable; import javax.swing.JComponent; import javax.swing.RepaintManager; +import javax.swing.SwingUtilities; public class GLAwareRepaintManager extends RepaintManager { public static RepaintManager INSTANCE = new GLAwareRepaintManager(); + private Map<JComponent, Rectangle> rects = new IdentityHashMap<JComponent, Rectangle>(); + + private volatile boolean queued = false; + @Override public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { - G2DGLCanvas glDrawable = getGLParent(c); - if (glDrawable != null) { - super.addDirtyRegion(glDrawable, 0, 0, glDrawable.getWidth(), glDrawable.getHeight()); - } else { + G2DGLCanvas canvas = getGLParent(c); + if (canvas == null || c instanceof GLAutoDrawable) { super.addDirtyRegion(c, x, y, w, h); + } else { + synchronized (rects) { + if (!rects.containsKey(c)) { + rects.put(c, new Rectangle(0, 0, c.getWidth(), c.getHeight())); + } + + if (!queued && rects.size() > 0) { + queued = true; + queue(); + } + } + } + } + + private void queue() { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + Map<JComponent, Rectangle> r; + synchronized (rects) { + r = new IdentityHashMap<JComponent, Rectangle>(rects); + queued = false; + + rects.clear(); + } + + r = filter(r); + G2DGLCanvas canvas = getGLParent(r.keySet().iterator().next()); + canvas.paintGLImmediately(r); + } + }); + } + + private Map<JComponent, Rectangle> filter(Map<JComponent, Rectangle> rects) { + Iterator<JComponent> itr = rects.keySet().iterator(); + while (itr.hasNext()) { + JComponent desc = itr.next(); + for (JComponent key : rects.keySet()) { + if (desc != key && SwingUtilities.isDescendingFrom(desc, key)) { + itr.remove(); + break; + } + } } + + return rects; } protected G2DGLCanvas getGLParent(JComponent component) { - Container c = component; + Container c = component.getParent(); while (true) { if (c == null) { return null; diff --git a/src/main/java/glg2d/GLGraphics2D.java b/src/main/java/glg2d/GLGraphics2D.java index afb517bc..eb8bb001 100644 --- a/src/main/java/glg2d/GLGraphics2D.java +++ b/src/main/java/glg2d/GLGraphics2D.java @@ -139,8 +139,6 @@ protected void setCanvas(GLAutoDrawable drawable) { protected void prePaint(GLAutoDrawable drawable, Component component) { setCanvas(drawable); setupState(component); - - gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); } protected void setupState(Component component) { diff --git a/src/test/java/glg2d/examples/shaders/CellShaderExample.java b/src/test/java/glg2d/examples/shaders/CellShaderExample.java index 4cf8c5ba..2adb01b4 100644 --- a/src/test/java/glg2d/examples/shaders/CellShaderExample.java +++ b/src/test/java/glg2d/examples/shaders/CellShaderExample.java @@ -13,7 +13,6 @@ import java.awt.Dimension; import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLEventListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.UIManager; @@ -26,7 +25,7 @@ public static void main(String[] args) throws Exception { JFrame frame = new JFrame("Cell Shader Example"); frame.setContentPane(new G2DGLCanvas(new UIDemo()) { @Override - protected GLEventListener createG2DListener(JComponent drawingComponent) { + protected G2DGLEventListener createG2DListener(JComponent drawingComponent) { return new G2DGLEventListener(drawingComponent) { @Override protected GLGraphics2D createGraphics2D(GLAutoDrawable drawable) { diff --git a/src/test/java/glg2d/examples/shaders/DepthSimExample.java b/src/test/java/glg2d/examples/shaders/DepthSimExample.java index 2428cbd2..db66ad4f 100644 --- a/src/test/java/glg2d/examples/shaders/DepthSimExample.java +++ b/src/test/java/glg2d/examples/shaders/DepthSimExample.java @@ -11,7 +11,6 @@ import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; -import javax.media.opengl.GLEventListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.Timer; @@ -25,7 +24,7 @@ public static void main(String[] args) throws Exception { final JFrame frame = new JFrame("Depth Shaker Example"); frame.setContentPane(new G2DGLCanvas(new UIDemo()) { @Override - protected GLEventListener createG2DListener(JComponent drawingComponent) { + protected G2DGLEventListener createG2DListener(JComponent drawingComponent) { return new G2DGLEventListener(drawingComponent) { @Override protected GLGraphics2D createGraphics2D(GLAutoDrawable drawable) { diff --git a/src/test/java/glg2d/examples/shaders/UIDemo.java b/src/test/java/glg2d/examples/shaders/UIDemo.java index 54f750fd..a0ef02cd 100644 --- a/src/test/java/glg2d/examples/shaders/UIDemo.java +++ b/src/test/java/glg2d/examples/shaders/UIDemo.java @@ -66,7 +66,7 @@ public UIDemo() { JPanel rightSubPanel = new JPanel(new BorderLayout()); rightPanel.add(rightSubPanel, BorderLayout.CENTER); - rightSubPanel.add(createProgressComponent(), BorderLayout.NORTH); +// rightSubPanel.add(createProgressComponent(), BorderLayout.NORTH); JSplitPane rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); rightSplit.setDividerSize(10); @@ -214,6 +214,11 @@ JComponent createListComponent() { model.addElement("golf"); model.addElement("hotel"); model.addElement("india"); + model.addElement("juliet"); + model.addElement("kilo"); + model.addElement("limo"); + model.addElement("mike"); + model.addElement("november"); return new JList(model); } @@ -286,6 +291,7 @@ public static void main(String[] args) throws Exception { // frame.setContentPane(new UIDemo()); frame.setContentPane(new G2DGLCanvas(new UIDemo())); +// frame.setContentPane(new UIDemo().createTabComponent()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(1024, 768)); frame.pack();
6f1932ab677b4e544fa964a6aacc7e888613ff2f
elasticsearch
support yaml detection on char sequence--
a
https://github.com/elastic/elasticsearch
diff --git a/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java b/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java index c01709db88b6f..50565dbba88d3 100644 --- a/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java +++ b/src/main/java/org/elasticsearch/common/xcontent/XContentFactory.java @@ -115,6 +115,21 @@ public static XContent xContent(XContentType type) { */ public static XContentType xContentType(CharSequence content) { int length = content.length() < GUESS_HEADER_LENGTH ? content.length() : GUESS_HEADER_LENGTH; + if (length == 0) { + return null; + } + char first = content.charAt(0); + if (first == '{') { + return XContentType.JSON; + } + // Should we throw a failure here? Smile idea is to use it in bytes.... + if (length > 2 && first == SmileConstants.HEADER_BYTE_1 && content.charAt(1) == SmileConstants.HEADER_BYTE_2 && content.charAt(2) == SmileConstants.HEADER_BYTE_3) { + return XContentType.SMILE; + } + if (length > 2 && first == '-' && content.charAt(1) == '-' && content.charAt(2) == '-') { + return XContentType.YAML; + } + for (int i = 0; i < length; i++) { char c = content.charAt(i); if (c == '{') {
063b8da4cfd78758f2eef5244008dc65f0557a4b
orientdb
Patch by Luca Molino about the management of JSON- with document type not only as first attribute--
a
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java index 7ad53982e4b..1fa83610f70 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java +++ b/core/src/main/java/com/orientechnologies/orient/core/serialization/serializer/record/string/ORecordSerializerJSON.java @@ -217,7 +217,7 @@ private Object getValue(final ODocument iRecord, String iFieldName, String iFiel // EMPTY, RETURN an EMPTY HASHMAP return new HashMap<String, Object>(); - if (fields[0].equals("\"@type\"")) + if (hasTypeField(fields)) // OBJECT return fromString(iRecord.getDatabase(), iFieldValue, null); else { @@ -335,6 +335,8 @@ else if (iFieldValueAsString.startsWith("{") && iFieldValueAsString.endsWith("}" return fromString(iRecord.getDatabase(), iFieldValueAsString); case DATE: + if (iFieldValueAsString == null || iFieldValueAsString.equals("")) + return null; try { // TRY TO PARSE AS LONG return Long.parseLong(iFieldValueAsString); @@ -703,6 +705,15 @@ private Integer getDepthLevel(final ORecordSchemaAware<?> record, final Map<Stri return depthLevel; } + private boolean hasTypeField(String[] fields) { + for (int i = 0; i < fields.length; i = i + 2) { + if (fields[i].equals("\"@type\"")) { + return true; + } + } + return false; + } + @Override public String toString() { return NAME;
13aba44f713378272aa92ad033c7016609802661
Valadoc
libvaladoc: register child structs
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/api/childsymbolregistrar.vala b/src/libvaladoc/api/childsymbolregistrar.vala index c3288e0130..e044327b03 100644 --- a/src/libvaladoc/api/childsymbolregistrar.vala +++ b/src/libvaladoc/api/childsymbolregistrar.vala @@ -82,6 +82,10 @@ public class Valadoc.Api.ChildSymbolRegistrar : Visitor { * {@inheritDoc} */ public override void visit_struct (Struct item) { + if (item.base_type != null) { + ((Struct) item.base_type.data_type).register_child_struct (item); + } + item.accept_all_children (this, false); } diff --git a/src/libvaladoc/api/struct.vala b/src/libvaladoc/api/struct.vala index 52bcb6b3d9..302494857c 100644 --- a/src/libvaladoc/api/struct.vala +++ b/src/libvaladoc/api/struct.vala @@ -95,6 +95,24 @@ public class Valadoc.Api.Struct : TypeSymbol { } + private Set<Struct> _known_child_structs = new TreeSet<Struct> (); + + /** + * Returns a list of all known structs based on this struct + */ + public Collection<Struct> get_known_child_structs () { + return _known_child_structs.read_only_view; + } + + public void register_child_struct (Struct stru) { + if (this.base_type != null) { + ((Struct) this.base_type.data_type).register_child_struct (stru); + } + + _known_child_structs.add (stru); + } + + /** * {@inheritDoc} */
03ef46a1cfe87d411243e5189a4906d0fce38237
orientdb
DbDeleteTest is made more stable.--
c
https://github.com/orientechnologies/orientdb
diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/eh/OExtendibleHashingTable.java b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/eh/OExtendibleHashingTable.java index 081583af4df..163d7c2a099 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/eh/OExtendibleHashingTable.java +++ b/core/src/main/java/com/orientechnologies/orient/core/storage/impl/memory/eh/OExtendibleHashingTable.java @@ -58,27 +58,27 @@ public OExtendibleHashingTable() { } public boolean put(OPhysicalPosition value) { - NodeInfo nodeInfo = getBucket(value.clusterPosition); - long[] node = hashTree[nodeInfo.nodeIndex]; + NodePath nodePath = getBucket(value.clusterPosition); + long[] node = hashTree[nodePath.nodeIndex]; - long filePosition = node[nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + long filePosition = node[nodePath.itemIndex + nodePath.hashMapOffset]; final OExtendibleHashingBucket bucket; long newFilePosition; if (filePosition == 0) { - bucket = new OExtendibleHashingBucket(nodeInfo.nodeGlobalDepth); + bucket = new OExtendibleHashingBucket(nodePath.nodeGlobalDepth); - final long nextBucketPos = nextBucket(new NodeInfo(nodeInfo.parent, nodeInfo.hashMapOffset, nodeInfo.itemIndex + 1, - nodeInfo.nodeIndex, nodeInfo.nodeGlobalDepth)); + final long nextBucketPos = nextBucket(new NodePath(nodePath.parent, nodePath.hashMapOffset, nodePath.itemIndex + 1, + nodePath.nodeIndex, nodePath.nodeGlobalDepth)); bucket.setNextBucket(nextBucketPos); - final long prevBucketPos = prevBucket(new NodeInfo(nodeInfo.parent, nodeInfo.hashMapOffset, nodeInfo.itemIndex - 1, - nodeInfo.nodeIndex, nodeInfo.nodeGlobalDepth)); + final long prevBucketPos = prevBucket(new NodePath(nodePath.parent, nodePath.hashMapOffset, nodePath.itemIndex - 1, + nodePath.nodeIndex, nodePath.nodeGlobalDepth)); bucket.setPrevBucket(prevBucketPos); file.add(bucket); newFilePosition = file.size(); - node[nodeInfo.itemIndex + nodeInfo.hashMapOffset] = newFilePosition; + node[nodePath.itemIndex + nodePath.hashMapOffset] = newFilePosition; if (nextBucketPos > 0) { final OExtendibleHashingBucket nextBucket = file.get((int) nextBucketPos - 1); @@ -112,7 +112,7 @@ public boolean put(OPhysicalPosition value) { newFilePosition = file.size(); - if (((nodeInfo.itemIndex >>> (64 - bucketDepth + 1)) & 1) == 0) { + if (((nodePath.itemIndex >>> (64 - bucketDepth + 1)) & 1) == 0) { final long oldNextBucketPosition = bucket.getNextBucket(); bucket.setNextBucket(newFilePosition); @@ -142,13 +142,13 @@ public boolean put(OPhysicalPosition value) { assert checkFileOrder(); - if (bucketDepth <= nodeInfo.nodeGlobalDepth) { - updateNodeAfterSplit(nodeInfo, bucketDepth, newFilePosition); + if (bucketDepth <= nodePath.nodeGlobalDepth) { + updateNodeAfterSplit(nodePath, bucketDepth, newFilePosition); } else { - if (nodeLocalDepths[nodeInfo.nodeIndex] < MAX_LEVEL_DEPTH) { - final long[] newNode = splitNode(nodeInfo, node); + if (nodeLocalDepths[nodePath.nodeIndex] < MAX_LEVEL_DEPTH) { + final long[] newNode = splitNode(nodePath, node); - final int nodeLocalDepth = nodeLocalDepths[nodeInfo.nodeIndex]; + final int nodeLocalDepth = nodeLocalDepths[nodePath.nodeIndex]; final int hashMapSize = 1 << nodeLocalDepth; boolean allHashMapsEquals = checkAllMapsContainSameBucket(newNode, hashMapSize); @@ -158,27 +158,27 @@ public boolean put(OPhysicalPosition value) { newNodeIndex = addNewNode(newNode, nodeLocalDepth); } - updateNodesAfterSplit(nodeInfo, newNode, nodeLocalDepth, hashMapSize, allHashMapsEquals, newNodeIndex); + updateNodesAfterSplit(nodePath, newNode, nodeLocalDepth, hashMapSize, allHashMapsEquals, newNodeIndex); - final int newIndex = nodeInfo.itemIndex << 1; - final int newOffset = nodeInfo.hashMapOffset << 1; - final int newGlobalDepth = nodeInfo.nodeGlobalDepth + 1; + final int newIndex = nodePath.itemIndex << 1; + final int newOffset = nodePath.hashMapOffset << 1; + final int newGlobalDepth = nodePath.nodeGlobalDepth + 1; if (newOffset < MAX_LEVEL_SIZE) { - final NodeInfo updatedNodeInfo = new NodeInfo(nodeInfo.parent, newOffset, newIndex, nodeInfo.nodeIndex, newGlobalDepth); - updateNodeAfterSplit(updatedNodeInfo, bucketDepth, newFilePosition); + final NodePath updatedNodePath = new NodePath(nodePath.parent, newOffset, newIndex, nodePath.nodeIndex, newGlobalDepth); + updateNodeAfterSplit(updatedNodePath, bucketDepth, newFilePosition); } else { - final NodeInfo newNodeInfo; + final NodePath newNodePath; if (!allHashMapsEquals) { - newNodeInfo = new NodeInfo(nodeInfo.parent, newOffset - MAX_LEVEL_SIZE, newIndex, newNodeIndex, newGlobalDepth); + newNodePath = new NodePath(nodePath.parent, newOffset - MAX_LEVEL_SIZE, newIndex, newNodeIndex, newGlobalDepth); } else { - newNodeInfo = nodeInfo.parent; + newNodePath = nodePath.parent; } - updateNodeAfterSplit(newNodeInfo, bucketDepth, newFilePosition); + updateNodeAfterSplit(newNodePath, bucketDepth, newFilePosition); } } else { - addNewLevelNode(nodeInfo, node, newFilePosition); + addNewLevelNode(nodePath, node, newFilePosition); } } @@ -186,8 +186,8 @@ public boolean put(OPhysicalPosition value) { } public boolean contains(OClusterPosition clusterPosition) { - NodeInfo nodeInfo = getBucket(clusterPosition); - long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + NodePath nodePath = getBucket(clusterPosition); + long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; if (position == 0) return false; @@ -197,8 +197,8 @@ public boolean contains(OClusterPosition clusterPosition) { } public OPhysicalPosition delete(OClusterPosition clusterPosition) { - final NodeInfo nodeInfo = getBucket(clusterPosition); - final long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + final NodePath nodePath = getBucket(clusterPosition); + final long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; final OExtendibleHashingBucket bucket = file.get((int) position - 1); final int positionIndex = bucket.getPosition(clusterPosition); if (positionIndex < 0) @@ -208,38 +208,38 @@ public OPhysicalPosition delete(OClusterPosition clusterPosition) { if (bucket.size() > 0) return removedPosition; - mergeNodesAfterDeletion(nodeInfo, bucket, position); + mergeNodesAfterDeletion(nodePath, bucket, position); assert checkFileOrder(); - if (nodeInfo.parent != null) { - final int hashMapSize = 1 << nodeLocalDepths[nodeInfo.nodeIndex]; + if (nodePath.parent != null) { + final int hashMapSize = 1 << nodeLocalDepths[nodePath.nodeIndex]; - final long[] node = hashTree[nodeInfo.nodeIndex]; + final long[] node = hashTree[nodePath.nodeIndex]; final boolean allMapsContainSameBucket = checkAllMapsContainSameBucket(node, hashMapSize); if (allMapsContainSameBucket) - mergeNodeToParent(node, nodeInfo); + mergeNodeToParent(node, nodePath); } return removedPosition; } - private void mergeNodeToParent(long[] node, NodeInfo nodeInfo) { - final long[] parentNode = hashTree[nodeInfo.parent.nodeIndex]; + private void mergeNodeToParent(long[] node, NodePath nodePath) { + final long[] parentNode = hashTree[nodePath.parent.nodeIndex]; int startIndex = -1; for (int i = 0; i < parentNode.length; i++) - if (parentNode[i] < 0 && (parentNode[i] & Long.MAX_VALUE) >>> 8 == nodeInfo.nodeIndex) { + if (parentNode[i] < 0 && (parentNode[i] & Long.MAX_VALUE) >>> 8 == nodePath.nodeIndex) { startIndex = i; break; } - final int hashMapSize = 1 << nodeLocalDepths[nodeInfo.nodeIndex]; + final int hashMapSize = 1 << nodeLocalDepths[nodePath.nodeIndex]; for (int i = 0, k = startIndex; i < node.length; i += hashMapSize, k++) { parentNode[k] = node[i]; } - deleteNode(nodeInfo.nodeIndex); + deleteNode(nodePath.nodeIndex); } private void deleteNode(int nodeIndex) { @@ -259,15 +259,15 @@ private void deleteNode(int nodeIndex) { } } - private void mergeNodesAfterDeletion(NodeInfo nodeInfo, OExtendibleHashingBucket bucket, long filePosition) { + private void mergeNodesAfterDeletion(NodePath nodePath, OExtendibleHashingBucket bucket, long filePosition) { final int bucketDepth = bucket.getDepth(); - int offset = nodeInfo.nodeGlobalDepth - (bucketDepth - 1); - NodeInfo currentNode = nodeInfo; - int nodeLocalDepth = nodeLocalDepths[nodeInfo.nodeIndex]; + int offset = nodePath.nodeGlobalDepth - (bucketDepth - 1); + NodePath currentNode = nodePath; + int nodeLocalDepth = nodeLocalDepths[nodePath.nodeIndex]; while (offset > 0) { offset -= nodeLocalDepth; if (offset > 0) { - currentNode = nodeInfo.parent; + currentNode = nodePath.parent; nodeLocalDepth = nodeLocalDepths[currentNode.nodeIndex]; } } @@ -354,10 +354,10 @@ private void mergeNodesAfterDeletion(NodeInfo nodeInfo, OExtendibleHashingBucket assert checkBucketDepth(buddyBucket); } - private long nextBucket(NodeInfo nodeInfo) { - nextBucketLoop: while (nodeInfo != null) { - final long[] node = hashTree[nodeInfo.nodeIndex]; - final int startIndex = nodeInfo.itemIndex + nodeInfo.hashMapOffset; + private long nextBucket(NodePath nodePath) { + nextBucketLoop: while (nodePath != null) { + final long[] node = hashTree[nodePath.nodeIndex]; + final int startIndex = nodePath.itemIndex + nodePath.hashMapOffset; final int endIndex = MAX_LEVEL_SIZE; for (int i = startIndex; i < endIndex; i++) { @@ -369,44 +369,44 @@ private long nextBucket(NodeInfo nodeInfo) { final int childNodeIndex = (int) ((position & Long.MAX_VALUE) >> 8); final int childItemOffset = (int) position & 0xFF; - final NodeInfo parent = new NodeInfo(nodeInfo.parent, 0, i, nodeInfo.nodeIndex, -1); - nodeInfo = new NodeInfo(parent, childItemOffset, 0, childNodeIndex, -1); + final NodePath parent = new NodePath(nodePath.parent, 0, i, nodePath.nodeIndex, -1); + nodePath = new NodePath(parent, childItemOffset, 0, childNodeIndex, -1); continue nextBucketLoop; } } - nodeInfo = nextLevelUp(nodeInfo); + nodePath = nextLevelUp(nodePath); } return 0; } - private NodeInfo nextLevelUp(NodeInfo nodeInfo) { - if (nodeInfo.parent == null) + private NodePath nextLevelUp(NodePath nodePath) { + if (nodePath.parent == null) return null; - final int nodeLocalDepth = nodeLocalDepths[nodeInfo.nodeIndex]; + final int nodeLocalDepth = nodeLocalDepths[nodePath.nodeIndex]; final int pointersSize = 1 << (MAX_LEVEL_DEPTH - nodeLocalDepth); - final NodeInfo parent = nodeInfo.parent; + final NodePath parent = nodePath.parent; if (parent.itemIndex < MAX_LEVEL_SIZE / 2) { final int nextParentIndex = (parent.itemIndex / pointersSize + 1) * pointersSize; - return new NodeInfo(parent.parent, 0, nextParentIndex, parent.nodeIndex, parent.nodeGlobalDepth); + return new NodePath(parent.parent, 0, nextParentIndex, parent.nodeIndex, parent.nodeGlobalDepth); } - final int nextParentIndex = ((nodeInfo.parent.itemIndex - MAX_LEVEL_SIZE / 2) / pointersSize + 1) * pointersSize; + final int nextParentIndex = ((nodePath.parent.itemIndex - MAX_LEVEL_SIZE / 2) / pointersSize + 1) * pointersSize; if (nextParentIndex < MAX_LEVEL_SIZE) - return new NodeInfo(parent.parent, 0, nextParentIndex, parent.nodeIndex, parent.nodeGlobalDepth); + return new NodePath(parent.parent, 0, nextParentIndex, parent.nodeIndex, parent.nodeGlobalDepth); - return nextLevelUp(new NodeInfo(parent.parent, 0, MAX_LEVEL_SIZE - 1, parent.nodeIndex, parent.nodeGlobalDepth)); + return nextLevelUp(new NodePath(parent.parent, 0, MAX_LEVEL_SIZE - 1, parent.nodeIndex, parent.nodeGlobalDepth)); } - private long prevBucket(NodeInfo nodeInfo) { - prevBucketLoop: while (nodeInfo != null) { - final long[] node = hashTree[nodeInfo.nodeIndex]; + private long prevBucket(NodePath nodePath) { + prevBucketLoop: while (nodePath != null) { + final long[] node = hashTree[nodePath.nodeIndex]; final int startIndex = 0; - final int endIndex = nodeInfo.itemIndex + nodeInfo.hashMapOffset; + final int endIndex = nodePath.itemIndex + nodePath.hashMapOffset; for (int i = endIndex; i >= startIndex; i--) { final long position = node[i]; @@ -419,37 +419,37 @@ private long prevBucket(NodeInfo nodeInfo) { final int localDepth = nodeLocalDepths[childNodeIndex]; final int endChildIndex = 1 << localDepth - 1; - final NodeInfo parent = new NodeInfo(nodeInfo.parent, 0, i, nodeInfo.nodeIndex, -1); - nodeInfo = new NodeInfo(parent, childItemOffset, endChildIndex, childNodeIndex, -1); + final NodePath parent = new NodePath(nodePath.parent, 0, i, nodePath.nodeIndex, -1); + nodePath = new NodePath(parent, childItemOffset, endChildIndex, childNodeIndex, -1); continue prevBucketLoop; } } - nodeInfo = prevLevelUp(nodeInfo); + nodePath = prevLevelUp(nodePath); } return 0; } - private NodeInfo prevLevelUp(NodeInfo nodeInfo) { - if (nodeInfo.parent == null) + private NodePath prevLevelUp(NodePath nodePath) { + if (nodePath.parent == null) return null; - final int nodeLocalDepth = nodeLocalDepths[nodeInfo.nodeIndex]; + final int nodeLocalDepth = nodeLocalDepths[nodePath.nodeIndex]; final int pointersSize = 1 << (MAX_LEVEL_DEPTH - nodeLocalDepth); - final NodeInfo parent = nodeInfo.parent; + final NodePath parent = nodePath.parent; if (parent.itemIndex > MAX_LEVEL_SIZE / 2) { - final int prevParentIndex = ((nodeInfo.parent.itemIndex - MAX_LEVEL_SIZE / 2) / pointersSize) * pointersSize - 1; - return new NodeInfo(parent.parent, 0, prevParentIndex, parent.nodeIndex, -1); + final int prevParentIndex = ((nodePath.parent.itemIndex - MAX_LEVEL_SIZE / 2) / pointersSize) * pointersSize - 1; + return new NodePath(parent.parent, 0, prevParentIndex, parent.nodeIndex, -1); } final int prevParentIndex = (parent.itemIndex / pointersSize) * pointersSize - 1; if (prevParentIndex >= 0) - return new NodeInfo(parent.parent, 0, prevParentIndex, parent.nodeIndex, -1); + return new NodePath(parent.parent, 0, prevParentIndex, parent.nodeIndex, -1); - return prevLevelUp(new NodeInfo(parent.parent, 0, 0, parent.nodeIndex, -1)); + return prevLevelUp(new NodePath(parent.parent, 0, 0, parent.nodeIndex, -1)); } public void clear() { @@ -474,8 +474,8 @@ public long size() { } public OPhysicalPosition get(OClusterPosition clusterPosition) { - NodeInfo nodeInfo = getBucket(clusterPosition); - long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + NodePath nodePath = getBucket(clusterPosition); + long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; if (position == 0) return null; @@ -485,10 +485,10 @@ public OPhysicalPosition get(OClusterPosition clusterPosition) { } public Entry[] higherEntries(OClusterPosition key) { - final NodeInfo nodeInfo = getBucket(key); - long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + final NodePath nodePath = getBucket(key); + long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; if (position == 0) - position = nextBucket(nodeInfo); + position = nextBucket(nodePath); if (position == 0) return new Entry[0]; @@ -518,10 +518,10 @@ public Entry[] higherEntries(OClusterPosition key) { } public Entry[] ceilingEntries(OClusterPosition key) { - final NodeInfo nodeInfo = getBucket(key); - long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + final NodePath nodePath = getBucket(key); + long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; if (position == 0) - position = nextBucket(nodeInfo); + position = nextBucket(nodePath); if (position == 0) return new Entry[0]; @@ -551,10 +551,10 @@ public Entry[] ceilingEntries(OClusterPosition key) { } public Entry[] lowerEntries(OClusterPosition key) { - final NodeInfo nodeInfo = getBucket(key); - long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + final NodePath nodePath = getBucket(key); + long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; if (position == 0) - position = prevBucket(nodeInfo); + position = prevBucket(nodePath); if (position == 0) return new Entry[0]; @@ -585,10 +585,10 @@ public Entry[] lowerEntries(OClusterPosition key) { } public Entry[] floorEntries(OClusterPosition key) { - final NodeInfo nodeInfo = getBucket(key); - long position = hashTree[nodeInfo.nodeIndex][nodeInfo.itemIndex + nodeInfo.hashMapOffset]; + final NodePath nodePath = getBucket(key); + long position = hashTree[nodePath.nodeIndex][nodePath.itemIndex + nodePath.hashMapOffset]; if (position == 0) - position = prevBucket(nodeInfo); + position = prevBucket(nodePath); if (position == 0) return new Entry[0]; @@ -644,14 +644,14 @@ private Entry[] convertBucketToEntries(final OExtendibleHashingBucket bucket, in return entries; } - private void addNewLevelNode(NodeInfo nodeInfo, long[] node, long newFilePosition) { + private void addNewLevelNode(NodePath nodePath, long[] node, long newFilePosition) { final long[] newNode = new long[MAX_LEVEL_SIZE]; final int newNodeDepth; final int newNodeStartIndex; final int mapInterval; - if (nodeInfo.itemIndex < node.length / 2) { + if (nodePath.itemIndex < node.length / 2) { final int maxDepth = getMaxLevelDepth(node, 0, node.length / 2); if (maxDepth > 0) newNodeDepth = maxDepth; @@ -659,7 +659,7 @@ private void addNewLevelNode(NodeInfo nodeInfo, long[] node, long newFilePositio newNodeDepth = 1; mapInterval = 1 << (MAX_LEVEL_DEPTH - newNodeDepth); - newNodeStartIndex = (nodeInfo.itemIndex / mapInterval) * mapInterval; + newNodeStartIndex = (nodePath.itemIndex / mapInterval) * mapInterval; } else { final int maxDepth = getMaxLevelDepth(node, node.length / 2, node.length); if (maxDepth > 0) @@ -668,7 +668,7 @@ private void addNewLevelNode(NodeInfo nodeInfo, long[] node, long newFilePositio newNodeDepth = 1; mapInterval = 1 << (MAX_LEVEL_DEPTH - newNodeDepth); - newNodeStartIndex = ((nodeInfo.itemIndex - node.length / 2) / mapInterval) * mapInterval + node.length / 2; + newNodeStartIndex = ((nodePath.itemIndex - node.length / 2) / mapInterval) * mapInterval + node.length / 2; } final int newNodeIndex = addNewNode(newNode, newNodeDepth); @@ -676,7 +676,7 @@ private void addNewLevelNode(NodeInfo nodeInfo, long[] node, long newFilePositio for (int i = 0; i < mapInterval; i++) { final int nodeOffset = i + newNodeStartIndex; final long position = node[nodeOffset]; - if (nodeOffset != nodeInfo.itemIndex) { + if (nodeOffset != nodePath.itemIndex) { for (int n = i << newNodeDepth; n < (i + 1) << newNodeDepth; n++) newNode[n] = position; } else { @@ -712,19 +712,19 @@ private int getMaxLevelDepth(long node[], int start, int end) { return maxDepth; } - private void updateNodesAfterSplit(NodeInfo nodeInfo, long[] newNode, int nodeLocalDepth, int hashMapSize, + private void updateNodesAfterSplit(NodePath nodePath, long[] newNode, int nodeLocalDepth, int hashMapSize, boolean allHashMapsEquals, int newNodeIndex) { - final long[] parentNode = hashTree[nodeInfo.parent.nodeIndex]; + final long[] parentNode = hashTree[nodePath.parent.nodeIndex]; int startIndex = -1; for (int i = 0; i < parentNode.length; i++) - if (parentNode[i] < 0 && (parentNode[i] & Long.MAX_VALUE) >>> 8 == nodeInfo.nodeIndex) { + if (parentNode[i] < 0 && (parentNode[i] & Long.MAX_VALUE) >>> 8 == nodePath.nodeIndex) { startIndex = i; break; } final int pointersSize = 1 << (MAX_LEVEL_DEPTH - nodeLocalDepth); for (int i = 0; i < pointersSize; i++) { - parentNode[startIndex + i] = (nodeInfo.nodeIndex << 8) | (i * hashMapSize) | Long.MIN_VALUE; + parentNode[startIndex + i] = (nodePath.nodeIndex << 8) | (i * hashMapSize) | Long.MIN_VALUE; } if (allHashMapsEquals) { @@ -777,7 +777,7 @@ private boolean assertAllNodesAreFilePointers(boolean allHashMapsEquals, long[] return true; } - private long[] splitNode(NodeInfo nodeInfo, long[] node) { + private long[] splitNode(NodePath nodePath, long[] node) { final long[] newNode = new long[MAX_LEVEL_SIZE]; for (int i = MAX_LEVEL_SIZE / 2; i < MAX_LEVEL_SIZE; i++) { @@ -795,8 +795,8 @@ private long[] splitNode(NodeInfo nodeInfo, long[] node) { updatedNode[2 * i + 1] = position; } - nodeLocalDepths[nodeInfo.nodeIndex]++; - hashTree[nodeInfo.nodeIndex] = updatedNode; + nodeLocalDepths[nodePath.nodeIndex]++; + hashTree[nodePath.nodeIndex] = updatedNode; return newNode; } @@ -835,9 +835,9 @@ private int addNewNode(long[] newNode, int nodeLocalDepth) { return hashTreeSize - 1; } - private void updateNodeAfterSplit(NodeInfo info, int bucketDepth, long newFilePosition) { + private void updateNodeAfterSplit(NodePath info, int bucketDepth, long newFilePosition) { int offset = info.nodeGlobalDepth - (bucketDepth - 1); - NodeInfo currentNode = info; + NodePath currentNode = info; int nodeLocalDepth = nodeLocalDepths[info.nodeIndex]; while (offset > 0) { offset -= nodeLocalDepth; @@ -877,16 +877,16 @@ private void updateBucket(int nodeIndex, int itemIndex, int offset, long newFile } } - private NodeInfo getBucket(final OClusterPosition key) { + private NodePath getBucket(final OClusterPosition key) { return getBucket(key, null); } - private NodeInfo getBucket(final OClusterPosition key, NodeInfo startNode) { + private NodePath getBucket(final OClusterPosition key, NodePath startNode) { final long hash = key.longValueHigh(); int nodeDepth; int localNodeDepth; - NodeInfo parentNode; + NodePath parentNode; int nodeIndex; int offset; @@ -905,7 +905,7 @@ private NodeInfo getBucket(final OClusterPosition key, NodeInfo startNode) { } int index = (int) ((hash >>> (64 - nodeDepth)) & (LEVEL_MASK >>> (MAX_LEVEL_DEPTH - localNodeDepth))); - NodeInfo currentNode = new NodeInfo(parentNode, 0, index, 0, nodeDepth); + NodePath currentNode = new NodePath(parentNode, 0, index, 0, nodeDepth); do { final long position = hashTree[nodeIndex][index + offset]; if (position >= 0) @@ -920,7 +920,7 @@ private NodeInfo getBucket(final OClusterPosition key, NodeInfo startNode) { index = (int) ((hash >>> (64 - nodeDepth)) & (LEVEL_MASK >>> (MAX_LEVEL_DEPTH - localNodeDepth))); parentNode = currentNode; - currentNode = new NodeInfo(parentNode, offset, index, nodeIndex, nodeDepth); + currentNode = new NodePath(parentNode, offset, index, nodeIndex, nodeDepth); } while (nodeDepth <= 64); throw new IllegalStateException("Extendible hashing tree in corrupted state."); @@ -972,7 +972,7 @@ private boolean checkFileOrder() { if (size == 0) return true; - final long firstBucket = nextBucket(new NodeInfo(null, 0, 0, 0, MAX_LEVEL_DEPTH)); + final long firstBucket = nextBucket(new NodePath(null, 0, 0, 0, MAX_LEVEL_DEPTH)); OExtendibleHashingBucket bucket = file.get((int) firstBucket - 1); OClusterPosition lastPrevKey = null; @@ -997,14 +997,14 @@ private boolean checkFileOrder() { return true; } - private static final class NodeInfo { - private final NodeInfo parent; + private static final class NodePath { + private final NodePath parent; private final int hashMapOffset; private final int itemIndex; private final int nodeIndex; private final int nodeGlobalDepth; - private NodeInfo(NodeInfo parent, int hashMapOffset, int itemIndex, int nodeIndex, int nodeDepth) { + private NodePath(NodePath parent, int hashMapOffset, int itemIndex, int nodeIndex, int nodeDepth) { this.parent = parent; this.hashMapOffset = hashMapOffset; this.itemIndex = itemIndex; diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbDeleteTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbDeleteTest.java index 1b71faff274..a517943a4d0 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbDeleteTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbDeleteTest.java @@ -18,10 +18,6 @@ import java.io.File; import java.io.IOException; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.record.impl.ODocument; import org.testng.Assert; import org.testng.annotations.Parameters; import org.testng.annotations.Test; @@ -32,6 +28,9 @@ import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.exception.ODatabaseException; import com.orientechnologies.orient.core.exception.OStorageException; +import com.orientechnologies.orient.core.metadata.schema.OClass; +import com.orientechnologies.orient.core.metadata.schema.OType; +import com.orientechnologies.orient.core.record.impl.ODocument; @Test(groups = "db") public class DbDeleteTest { @@ -65,23 +64,23 @@ public void testDbDelete() throws IOException { Assert.assertFalse(new File(testPath + "/" + DbImportExportTest.NEW_DB_PATH).exists()); } - public void testDbDeleteWithIndex() { - final ODatabaseDocument db = new ODatabaseDocumentTx("local:" + testPath + "target/testDbDeleteWithIndex"); - if (db.exists()) { - db.open("admin", "admin"); - db.drop(); - } + public void testDbDeleteWithIndex() { + final ODatabaseDocument db = new ODatabaseDocumentTx("local:" + testPath + "core/target/testDbDeleteWithIndex"); + if (db.exists()) { + db.open("admin", "admin"); + db.drop(); + } - db.create(); + db.create(); - final OClass indexedClass = db.getMetadata().getSchema().createClass("IndexedClass"); - indexedClass.createProperty("value", OType.STRING); - indexedClass.createIndex("indexValue", OClass.INDEX_TYPE.UNIQUE, "value"); + final OClass indexedClass = db.getMetadata().getSchema().createClass("IndexedClass"); + indexedClass.createProperty("value", OType.STRING); + indexedClass.createIndex("indexValue", OClass.INDEX_TYPE.UNIQUE, "value"); - final ODocument document = new ODocument("IndexedClass"); - document.field("value", "value"); - document.save(); + final ODocument document = new ODocument("IndexedClass"); + document.field("value", "value"); + document.save(); - db.drop(); - } + db.drop(); + } }
c689af142aefea121ae87e32fe775f9859b7344a
kotlin
Fixed highlighting for enum and object names in- code-- -KT-8134 Fixed-
c
https://github.com/JetBrains/kotlin
diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java index 4f7f3f83e3016..249a00b8caa37 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitor.java @@ -30,7 +30,15 @@ public R visitDeclaration(@NotNull JetDeclaration dcl, D data) { } public R visitClass(@NotNull JetClass klass, D data) { - return visitNamedDeclaration(klass, data); + return visitClassOrObject(klass, data); + } + + public R visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, D data) { + return visitClassOrObject(declaration, data); + } + + public R visitClassOrObject(@NotNull JetClassOrObject classOrObject, D data) { + return visitNamedDeclaration(classOrObject, data); } public R visitSecondaryConstructor(@NotNull JetSecondaryConstructor constructor, D data) { @@ -402,10 +410,6 @@ public R visitWhenConditionWithExpression(@NotNull JetWhenConditionWithExpressio return visitJetElement(condition, data); } - public R visitObjectDeclaration(@NotNull JetObjectDeclaration declaration, D data) { - return visitNamedDeclaration(declaration, data); - } - public R visitObjectDeclarationName(@NotNull JetObjectDeclarationName declarationName, D data) { return visitExpression(declarationName, data); } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java index 78caf28882d0c..286fd42ad1f75 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java +++ b/compiler/frontend/src/org/jetbrains/kotlin/psi/JetVisitorVoid.java @@ -33,6 +33,10 @@ public void visitClass(@NotNull JetClass klass) { super.visitClass(klass, null); } + public void visitClassOrObject(@NotNull JetClassOrObject classOrObject) { + super.visitClassOrObject(classOrObject, null); + } + public void visitSecondaryConstructor(@NotNull JetSecondaryConstructor constructor) { super.visitSecondaryConstructor(constructor, null); } @@ -448,6 +452,12 @@ public final Void visitClass(@NotNull JetClass klass, Void data) { return null; } + @Override + public final Void visitClassOrObject(@NotNull JetClassOrObject classOrObject, Void data) { + visitClassOrObject(classOrObject); + return null; + } + @Override public final Void visitSecondaryConstructor(@NotNull JetSecondaryConstructor constructor, Void data) { visitSecondaryConstructor(constructor); diff --git a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt index 31ddc27f0a6cc..58abc341513df 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/resolve/LazyTopDownAnalyzer.kt @@ -154,7 +154,7 @@ public class LazyTopDownAnalyzer { fileScope.forceResolveImport(importDirective) } - private fun visitClassOrObject(classOrObject: JetClassOrObject) { + override fun visitClassOrObject(classOrObject: JetClassOrObject) { val descriptor = lazyDeclarationResolver!!.getClassDescriptor(classOrObject) as ClassDescriptorWithResolutionScopes c.getDeclaredClasses().put(classOrObject, descriptor) diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties index 099b79fce1473..c57187ff1aaa4 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/JetBundle.properties @@ -133,6 +133,7 @@ options.kotlin.attribute.descriptor.kdoc.comment=KDoc comment options.kotlin.attribute.descriptor.kdoc.tag=KDoc tag options.kotlin.attribute.descriptor.kdoc.value=Link in KDoc tag options.kotlin.attribute.descriptor.object=Object +options.kotlin.attribute.descriptor.enumEntry=Enum entry options.kotlin.attribute.descriptor.annotation=Annotation options.kotlin.attribute.descriptor.var=Var (mutable variable, parameter or property) options.kotlin.attribute.descriptor.local.variable=Local variable or value diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java index 62b237cf779a2..60f81964a740f 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/JetHighlightingColors.java @@ -55,6 +55,7 @@ public class JetHighlightingColors { public static final TextAttributesKey TRAIT = createTextAttributesKey("KOTLIN_TRAIT", CodeInsightColors.INTERFACE_NAME_ATTRIBUTES); public static final TextAttributesKey ANNOTATION = createTextAttributesKey("KOTLIN_ANNOTATION"); public static final TextAttributesKey OBJECT = createTextAttributesKey("KOTLIN_OBJECT", CLASS); + public static final TextAttributesKey ENUM_ENTRY = createTextAttributesKey("KOTLIN_ENUM_ENTRY", CodeInsightColors.INSTANCE_FIELD_ATTRIBUTES); // variable kinds public static final TextAttributesKey MUTABLE_VARIABLE = createTextAttributesKey("KOTLIN_MUTABLE_VARIABLE"); diff --git a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java index db9b10016969b..a4267bd75fa46 100644 --- a/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java +++ b/idea/idea-analysis/src/org/jetbrains/kotlin/idea/highlighter/TypeKindHighlightingVisitor.java @@ -62,14 +62,6 @@ private void highlightAnnotation(@NotNull JetSimpleNameExpression expression) { JetPsiChecker.highlightName(holder, toHighlight, JetHighlightingColors.ANNOTATION); } - @Override - public void visitObjectDeclarationName(@NotNull JetObjectDeclarationName declaration) { - PsiElement nameIdentifier = declaration.getNameIdentifier(); - if (nameIdentifier != null) { - highlightName(nameIdentifier, JetHighlightingColors.CLASS); - } - } - @Override public void visitTypeParameter(@NotNull JetTypeParameter parameter) { PsiElement identifier = parameter.getNameIdentifier(); @@ -80,18 +72,13 @@ public void visitTypeParameter(@NotNull JetTypeParameter parameter) { } @Override - public void visitEnumEntry(@NotNull JetEnumEntry enumEntry) { - // Do nothing, the name was already highlighted in visitObjectDeclarationName - } - - @Override - public void visitClass(@NotNull JetClass klass) { - PsiElement identifier = klass.getNameIdentifier(); - ClassDescriptor classDescriptor = bindingContext.get(BindingContext.CLASS, klass); + public void visitClassOrObject(@NotNull JetClassOrObject classOrObject) { + PsiElement identifier = classOrObject.getNameIdentifier(); + ClassDescriptor classDescriptor = bindingContext.get(BindingContext.CLASS, classOrObject); if (identifier != null && classDescriptor != null) { highlightName(identifier, textAttributesKeyForClass(classDescriptor)); } - super.visitClass(klass); + super.visitClassOrObject(classOrObject); } @Override @@ -113,7 +100,7 @@ private static TextAttributesKey textAttributesKeyForClass(@NotNull ClassDescrip case OBJECT: return JetHighlightingColors.OBJECT; case ENUM_ENTRY: - return JetHighlightingColors.INSTANCE_PROPERTY; + return JetHighlightingColors.ENUM_ENTRY; default: return descriptor.getModality() == Modality.ABSTRACT ? JetHighlightingColors.ABSTRACT_CLASS diff --git a/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java b/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java index 0969b6e4983aa..9973ee9244129 100644 --- a/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java +++ b/idea/src/org/jetbrains/kotlin/idea/highlighter/JetColorSettingsPage.java @@ -82,6 +82,10 @@ public String getDemoText() { "\n" + "<KEYWORD>public</KEYWORD> <KEYWORD>abstract</KEYWORD> class <ABSTRACT_CLASS>Abstract</ABSTRACT_CLASS> {\n" + "}\n" + + "\n" + + "<KEYWORD>object</KEYWORD> <OBJECT>Obj</OBJECT>\n" + + "\n" + + "<KEYWORD>enum</KEYWORD> <KEYWORD>class</KEYWORD> <CLASS>E</CLASS> { <ENUM_ENTRY>A</ENUM_ENTRY> }\n" + " Bad character: \\n\n"; } @@ -137,6 +141,7 @@ public AttributesDescriptor[] getAttributeDescriptors() { new AttributesDescriptor("Interface", JetHighlightingColors.TRAIT), new AttributesDescriptor(JetBundle.message("options.kotlin.attribute.descriptor.annotation"), JetHighlightingColors.ANNOTATION), new AttributesDescriptor(JetBundle.message("options.kotlin.attribute.descriptor.object"), JetHighlightingColors.OBJECT), + new AttributesDescriptor(JetBundle.message("options.kotlin.attribute.descriptor.enumEntry"), JetHighlightingColors.ENUM_ENTRY), new AttributesDescriptor(JetBundle.message("options.kotlin.attribute.descriptor.var"), JetHighlightingColors.MUTABLE_VARIABLE), diff --git a/idea/testData/highlighter/Enums.kt b/idea/testData/highlighter/Enums.kt index 835f6f1cffaac..4c194cc839292 100644 --- a/idea/testData/highlighter/Enums.kt +++ b/idea/testData/highlighter/Enums.kt @@ -1,11 +1,11 @@ package testing <info textAttributesKey="KOTLIN_BUILTIN_ANNOTATION">enum</info> class <info textAttributesKey="KOTLIN_CLASS">Test</info> { - <info textAttributesKey="KOTLIN_CLASS">FIRST</info>, - <info textAttributesKey="KOTLIN_CLASS">SECOND</info> + <info textAttributesKey="KOTLIN_ENUM_ENTRY">FIRST</info>, + <info textAttributesKey="KOTLIN_ENUM_ENTRY">SECOND</info> } fun <info textAttributesKey="KOTLIN_FUNCTION_DECLARATION">testing</info>(<info textAttributesKey="KOTLIN_PARAMETER">t1</info>: <info textAttributesKey="KOTLIN_CLASS">Test</info>, <info textAttributesKey="KOTLIN_PARAMETER">t2</info>: <info textAttributesKey="KOTLIN_CLASS">Test</info>): <info textAttributesKey="KOTLIN_CLASS">Test</info> { - if (<info textAttributesKey="KOTLIN_PARAMETER">t1</info> != <info textAttributesKey="KOTLIN_PARAMETER">t2</info>) return <info textAttributesKey="KOTLIN_CLASS">Test</info>.<info textAttributesKey="KOTLIN_INSTANCE_PROPERTY">FIRST</info> - return <info textAttributesKey="KOTLIN_PACKAGE_FUNCTION_CALL"><info textAttributesKey="KOTLIN_FUNCTION_CALL">testing</info></info>(<info textAttributesKey="KOTLIN_CLASS">Test</info>.<info textAttributesKey="KOTLIN_INSTANCE_PROPERTY">FIRST</info>, <info textAttributesKey="KOTLIN_CLASS">Test</info>.<info textAttributesKey="KOTLIN_INSTANCE_PROPERTY">SECOND</info>) + if (<info textAttributesKey="KOTLIN_PARAMETER">t1</info> != <info textAttributesKey="KOTLIN_PARAMETER">t2</info>) return <info textAttributesKey="KOTLIN_CLASS">Test</info>.<info textAttributesKey="KOTLIN_ENUM_ENTRY">FIRST</info> + return <info textAttributesKey="KOTLIN_PACKAGE_FUNCTION_CALL"><info textAttributesKey="KOTLIN_FUNCTION_CALL">testing</info></info>(<info textAttributesKey="KOTLIN_CLASS">Test</info>.<info textAttributesKey="KOTLIN_ENUM_ENTRY">FIRST</info>, <info textAttributesKey="KOTLIN_CLASS">Test</info>.<info textAttributesKey="KOTLIN_ENUM_ENTRY">SECOND</info>) } \ No newline at end of file diff --git a/idea/testData/highlighter/Object.kt b/idea/testData/highlighter/Object.kt index 1533b54340fd6..1e25e85a838f3 100644 --- a/idea/testData/highlighter/Object.kt +++ b/idea/testData/highlighter/Object.kt @@ -1,6 +1,6 @@ package testing -object <info textAttributesKey="KOTLIN_CLASS">O</info> { +object <info textAttributesKey="KOTLIN_OBJECT">O</info> { fun <info textAttributesKey="KOTLIN_FUNCTION_DECLARATION">foo</info>() = 42 }
f2fb6938e2c7d45eaeb0eefd6c9f9ebc3c1606f8
echo3$echo3
Moved common selection functionality of TablePeer and AbstractListComponentPeer to new ListSelectionUtil class. Cleanups and docs.
p
https://github.com/echo3/echo3
diff --git a/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/AbstractListComponentPeer.java b/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/AbstractListComponentPeer.java index 93fe855a..77421ea0 100644 --- a/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/AbstractListComponentPeer.java +++ b/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/AbstractListComponentPeer.java @@ -32,7 +32,6 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Set; -import java.util.StringTokenizer; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -42,7 +41,6 @@ import nextapp.echo.app.list.AbstractListComponent; import nextapp.echo.app.list.ListCellRenderer; import nextapp.echo.app.list.ListModel; -import nextapp.echo.app.list.ListSelectionModel; import nextapp.echo.app.list.StyledListCell; import nextapp.echo.app.serial.PropertyPeerFactory; import nextapp.echo.app.serial.SerialContext; @@ -59,13 +57,15 @@ import nextapp.echo.webcontainer.service.JavaScriptService; import nextapp.echo.webcontainer.util.MultiIterator; +/** + * Abstract base synchronization peer for <code>AbstractListComponent</code>s. + */ public abstract class AbstractListComponentPeer extends AbstractComponentSynchronizePeer { - public Class getComponentClass() { - // TODO Auto-generated method stub - return null; - } - + /** + * Property object describing rendered list data, + * i.e., the <code>ListModel</code> and </code>ListCellRenderer</code>. + */ private class ListData { private ListModel model; @@ -109,6 +109,9 @@ public int hashCode() { } } + /** + * Server-to-client serialization peer for <code>ListData</code> objects. + */ public static class ListDataPeer implements SerialPropertyPeer { @@ -164,28 +167,6 @@ public void toXml(Context context, Class objectClass, Element propertyElement, O } } - private static final String getSelectionString(ListSelectionModel selectionModel) { - int min = selectionModel.getMinSelectedIndex(); - int max = selectionModel.getMaxSelectedIndex(); - if (min == max || selectionModel.getSelectionMode() != ListSelectionModel.MULTIPLE_SELECTION) { - return Integer.toString(min); - } else { - StringBuffer out = new StringBuffer(); - boolean commaRequired = false; - for (int i = min; i <= max; ++i) { - if (selectionModel.isSelectedIndex(i)) { - if (commaRequired) { - out.append(","); - } else { - commaRequired = true; - } - out.append(i); - } - } - return out.toString(); - } - } - /** * Service for <code>ListSelectionModel</code>. */ @@ -196,15 +177,19 @@ private static final String getSelectionString(ListSelectionModel selectionModel new String[] { "/nextapp/echo/webcontainer/resource/js/Render.List.js", "/nextapp/echo/webcontainer/resource/js/RemoteClient.List.js" }); + private static final String PROPERTY_DATA = "data"; + + private static final String PROPERTY_SELECTION = "selection"; + private static final String PROPERTY_SELECTION_MODE = "selectionMode"; static { WebContainerServlet.getServiceRegistry().add(LIST_COMPONENT_SERVICE); WebContainerServlet.getServiceRegistry().add(LIST_SELECTION_MODEL_SERVICE); } - - private static final String PROPERTY_DATA = "data"; - private static final String PROPERTY_SELECTION = "selection"; - private static final String PROPERTY_SELECTION_MODE = "selectionMode"; + /** + * Default constructor. + * Installs additional output properties. + */ public AbstractListComponentPeer() { super(); addOutputProperty(PROPERTY_DATA); @@ -214,14 +199,14 @@ public AbstractListComponentPeer() { } /** - * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getOutputPropertyMethodName( - * nextapp.echo.app.util.Context, nextapp.echo.app.Component, java.lang.String) + * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getInputPropertyClass(java.lang.String) */ - public String getOutputPropertyMethodName(Context context, Component component, String propertyName) { - if (PROPERTY_DATA.equals(propertyName)) { - return "updateListData"; + public Class getInputPropertyClass(String propertyName) { + if (PROPERTY_SELECTION.equals(propertyName)) { + return String.class; + } else { + return null; } - return super.getOutputPropertyMethodName(context, component, propertyName); } /** @@ -232,7 +217,8 @@ public Object getOutputProperty(Context context, Component component, String pro if (PROPERTY_DATA.equals(propertyName)) { return new ListData((AbstractListComponent) component); } else if (PROPERTY_SELECTION.equals(propertyName)) { - return getSelectionString(((AbstractListComponent) component).getSelectionModel()); + return ListSelectionUtil.toString(((AbstractListComponent) component).getSelectionModel(), + ((AbstractListComponent) component).getModel().size()); } else if (PROPERTY_SELECTION_MODE.equals(propertyName)) { int selectionMode = ((AbstractListComponent) component).getSelectionModel().getSelectionMode(); return new Integer(selectionMode); @@ -240,6 +226,17 @@ public Object getOutputProperty(Context context, Component component, String pro return super.getOutputProperty(context, component, propertyName, propertyIndex); } + /** + * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getOutputPropertyMethodName( + * nextapp.echo.app.util.Context, nextapp.echo.app.Component, java.lang.String) + */ + public String getOutputPropertyMethodName(Context context, Component component, String propertyName) { + if (PROPERTY_DATA.equals(propertyName)) { + return "updateListData"; + } + return super.getOutputPropertyMethodName(context, component, propertyName); + } + /** * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getUpdatedOutputPropertyNames( * nextapp.echo.app.util.Context, nextapp.echo.app.Component, nextapp.echo.app.update.ServerComponentUpdate) @@ -272,40 +269,14 @@ public void init(Context context) { } /** - * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getInputPropertyClass(java.lang.String) - */ - public Class getInputPropertyClass(String propertyName) { - if (PROPERTY_SELECTION.equals(propertyName)) { - return String.class; - } else { - return null; - } - } - - /** - * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#storeInputProperty(nextapp.echo.app.util.Context, nextapp.echo.app.Component, java.lang.String, int, java.lang.Object) + * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#storeInputProperty( + * nextapp.echo.app.util.Context, nextapp.echo.app.Component, java.lang.String, int, java.lang.Object) */ public void storeInputProperty(Context context, Component component, String propertyName, int index, Object newValue) { - int[] selection; - - String selectionString = (String) newValue; - int selectionStringLength = selectionString.length(); - if (selectionStringLength == 0) { - selection = new int[0]; - } else { - int itemCount = 1; - for (int i = 1; i < selectionStringLength - 1; ++i) { - if (selectionString.charAt(i) == ',') { - ++itemCount; - } - } - selection = new int[itemCount]; - } - StringTokenizer st = new StringTokenizer(selectionString, ","); - for (int i = 0; i < selection.length; ++i) { - selection[i] = Integer.parseInt(st.nextToken()); + if (PROPERTY_SELECTION.equals(propertyName)) { + int[] selection = ListSelectionUtil.toIntArray((String) newValue); + ClientUpdateManager clientUpdateManager = (ClientUpdateManager) context.get(ClientUpdateManager.class); + clientUpdateManager.setComponentProperty(component, AbstractListComponent.SELECTION_CHANGED_PROPERTY, selection); } - ClientUpdateManager clientUpdateManager = (ClientUpdateManager) context.get(ClientUpdateManager.class); - clientUpdateManager.setComponentProperty(component, AbstractListComponent.SELECTION_CHANGED_PROPERTY, selection); } } diff --git a/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/ListSelectionUtil.java b/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/ListSelectionUtil.java new file mode 100644 index 00000000..94f68a28 --- /dev/null +++ b/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/ListSelectionUtil.java @@ -0,0 +1,111 @@ +/* + * This file is part of the Echo Web Application Framework (hereinafter "Echo"). + * Copyright (C) 2002-2007 NextApp, Inc. + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + */ + +package nextapp.echo.webcontainer.sync.component; + +import java.util.StringTokenizer; + +import nextapp.echo.app.list.ListSelectionModel; + +/** + * Utilities for serializing <code>ListSelectionModel</code> state between client and server. + */ +class ListSelectionUtil { + + /** + * Creates a selection string representation of a <code>ListSelectionModel</code>. + * + * @param selectionModel the <code>ListSelectionModel</code> + * @param modelSize the size of the <strong>data</strong> model of which items are selected + * @return a selection string, e.g., "1,2,3,4", "5", or "" + */ + static String toString(ListSelectionModel selectionModel, int size) { + int minimumIndex = selectionModel.getMinSelectedIndex(); + + if (minimumIndex == -1) { + // Nothing selected: return empty String. + return ""; + } + int maximumIndex = selectionModel.getMaxSelectedIndex(); + + if (minimumIndex == maximumIndex || selectionModel.getSelectionMode() != ListSelectionModel.MULTIPLE_SELECTION) { + // Single selection mode or only one index selected: return it directly. + return Integer.toString(minimumIndex); + } + + if (maximumIndex > size - 1) { + maximumIndex = size - 1; + } + StringBuffer out = new StringBuffer(); + boolean commaRequired = false; + for (int i = minimumIndex; i <= maximumIndex; ++i) { + if (selectionModel.isSelectedIndex(i)) { + if (commaRequired) { + out.append(","); + } else { + commaRequired = true; + } + out.append(i); + } + } + return out.toString(); + } + + /** + * Converts a selection String to an int[] array. + * + * @param selectionString the selection string, e.g., "1,2,3,4", "5", or "" + * @return the integer array + */ + static int[] toIntArray(String selectionString) { + int[] selection; + + int selectionStringLength = selectionString.length(); + if (selectionStringLength == 0) { + selection = new int[0]; + } else { + int itemCount = 1; + for (int i = 1; i < selectionStringLength - 1; ++i) { + if (selectionString.charAt(i) == ',') { + ++itemCount; + } + } + selection = new int[itemCount]; + } + StringTokenizer st = new StringTokenizer(selectionString, ","); + for (int i = 0; i < selection.length; ++i) { + selection[i] = Integer.parseInt(st.nextToken()); + } + + return selection; + } + + /** Non-instantiable class. */ + private ListSelectionUtil() { } +} diff --git a/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/TablePeer.java b/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/TablePeer.java index 9ffd1380..1a64d780 100644 --- a/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/TablePeer.java +++ b/src/webcontainer/java/nextapp/echo/webcontainer/sync/component/TablePeer.java @@ -33,8 +33,6 @@ import nextapp.echo.app.Component; import nextapp.echo.app.Table; -import nextapp.echo.app.list.ListSelectionModel; -import nextapp.echo.app.table.TableModel; import nextapp.echo.app.update.ClientUpdateManager; import nextapp.echo.app.update.ServerComponentUpdate; import nextapp.echo.app.util.Context; @@ -56,26 +54,6 @@ */ public class TablePeer extends AbstractComponentSynchronizePeer { - private static String getSelectionString(ListSelectionModel selectionModel, TableModel model) { - String selection = ""; - int minimumIndex = selectionModel.getMinSelectedIndex(); - if (minimumIndex != -1) { - int maximumIndex = selectionModel.getMaxSelectedIndex(); - if (maximumIndex > model.getRowCount() - 1) { - maximumIndex = model.getRowCount() - 1; - } - for (int i = minimumIndex; i <= maximumIndex; ++i) { - if (selectionModel.isSelectedIndex(i)) { - if (selection.length() > 0) { - selection += ","; - } - selection += Integer.toString(i); - } - } - } - return selection; - } - private static final Service TABLE_SERVICE = JavaScriptService.forResource("Echo.RemoteTable", "/nextapp/echo/webcontainer/resource/js/Render.RemoteTable.js"); @@ -118,15 +96,6 @@ public Class getComponentClass() { return Table.class; } - /** - * @see nextapp.echo.webcontainer.ComponentSynchronizePeer#init(nextapp.echo.app.util.Context) - */ - public void init(Context context) { - ServerMessage serverMessage = (ServerMessage) context.get(ServerMessage.class); - serverMessage.addLibrary(AbstractListComponentPeer.LIST_SELECTION_MODEL_SERVICE.getId()); - serverMessage.addLibrary(TABLE_SERVICE.getId()); - } - /** * @see nextapp.echo.webcontainer.ComponentSynchronizePeer#getImmediateEventTypes(Context, nextapp.echo.app.Component) */ @@ -137,34 +106,6 @@ public Iterator getImmediateEventTypes(Context context, Component component) { } return super.getImmediateEventTypes(context, component); } - - /** - * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getOutputPropertyIndices(nextapp.echo.app.util.Context, - * nextapp.echo.app.Component, java.lang.String) - */ - public Iterator getOutputPropertyIndices(Context context, Component component, String propertyName) { - if (PROPERTY_COLUMN_WIDTH.equals(propertyName)) { - final Iterator columnIterator = ((Table) component).getColumnModel().getColumns(); - return new Iterator() { - private int i = 0; - - public void remove() { - throw new UnsupportedOperationException(); - } - - public Object next() { - columnIterator.next(); - return new Integer(i++); - } - - public boolean hasNext() { - return columnIterator.hasNext(); - } - }; - } else { - return super.getOutputPropertyIndices(context, component, propertyName); - } - } /** * @see ComponentSynchronizePeer#getInputPropertyClass(String) @@ -175,7 +116,7 @@ public Class getInputPropertyClass(String propertyName) { } return super.getInputPropertyClass(propertyName); } - + /** * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getOutputProperty( * nextapp.echo.app.util.Context, nextapp.echo.app.Component, java.lang.String, int) @@ -191,13 +132,41 @@ public Object getOutputProperty(Context context, Component component, String pro } else if (PROPERTY_ROW_COUNT.equals(propertyName)) { return new Integer(table.getModel().getRowCount()); } else if (PROPERTY_SELECTION.equals(propertyName)) { - return getSelectionString(table.getSelectionModel(), table.getModel()); + return ListSelectionUtil.toString(table.getSelectionModel(), table.getModel().getRowCount()); } else if (PROPERTY_SELECTION_MODE.equals(propertyName)) { return new Integer(table.getSelectionModel().getSelectionMode()); } return super.getOutputProperty(context, component, propertyName, propertyIndex); } + /** + * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getOutputPropertyIndices(nextapp.echo.app.util.Context, + * nextapp.echo.app.Component, java.lang.String) + */ + public Iterator getOutputPropertyIndices(Context context, Component component, String propertyName) { + if (PROPERTY_COLUMN_WIDTH.equals(propertyName)) { + final Iterator columnIterator = ((Table) component).getColumnModel().getColumns(); + return new Iterator() { + private int i = 0; + + public boolean hasNext() { + return columnIterator.hasNext(); + } + + public Object next() { + columnIterator.next(); + return new Integer(i++); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } else { + return super.getOutputPropertyIndices(context, component, propertyName); + } + } + /** * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#getUpdatedOutputPropertyNames( * nextapp.echo.app.util.Context, @@ -217,25 +186,12 @@ public Iterator getUpdatedOutputPropertyNames(Context context, Component compone } /** - * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#storeInputProperty(nextapp.echo.app.util.Context, - * nextapp.echo.app.Component, java.lang.String, int, java.lang.Object) + * @see nextapp.echo.webcontainer.ComponentSynchronizePeer#init(nextapp.echo.app.util.Context) */ - public void storeInputProperty(Context context, Component component, String propertyName, int index, Object newValue) { - if (PROPERTY_SELECTION.equals(propertyName)) { - int[] selectedIndices; - String tokensString = (String)newValue; - if (tokensString.length() == 0) { - selectedIndices = new int[0]; - } else { - String[] tokens = (tokensString).split(","); - selectedIndices = new int[tokens.length]; - for (int i = 0; i < tokens.length; ++i) { - selectedIndices[i] = Integer.parseInt(tokens[i]); - } - } - ClientUpdateManager clientUpdateManager = (ClientUpdateManager) context.get(ClientUpdateManager.class); - clientUpdateManager.setComponentProperty(component, Table.SELECTION_CHANGED_PROPERTY, selectedIndices); - } + public void init(Context context) { + ServerMessage serverMessage = (ServerMessage) context.get(ServerMessage.class); + serverMessage.addLibrary(AbstractListComponentPeer.LIST_SELECTION_MODEL_SERVICE.getId()); + serverMessage.addLibrary(TABLE_SERVICE.getId()); } /** @@ -247,4 +203,16 @@ public void processEvent(Context context, Component component, String eventType, clientUpdateManager.setComponentAction(component, Table.INPUT_ACTION, null); } } + + /** + * @see nextapp.echo.webcontainer.AbstractComponentSynchronizePeer#storeInputProperty(nextapp.echo.app.util.Context, + * nextapp.echo.app.Component, java.lang.String, int, java.lang.Object) + */ + public void storeInputProperty(Context context, Component component, String propertyName, int index, Object newValue) { + if (PROPERTY_SELECTION.equals(propertyName)) { + int[] selection = ListSelectionUtil.toIntArray((String) newValue); + ClientUpdateManager clientUpdateManager = (ClientUpdateManager) context.get(ClientUpdateManager.class); + clientUpdateManager.setComponentProperty(component, Table.SELECTION_CHANGED_PROPERTY, selection); + } + } } \ No newline at end of file
a4870e1f053d17b9e9cbb64d6a9b8774a8815863
restlet-framework-java
- Fixed issues in Grizzly code.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerCall.java b/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerCall.java index 43b3d1bc35..af977017db 100644 --- a/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerCall.java +++ b/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerCall.java @@ -72,6 +72,21 @@ public class GrizzlyServerCall extends HttpServerCall { public GrizzlyServerCall(Server server, ByteBuffer byteBuffer, SelectionKey key, boolean confidential) { super(server); + init(byteBuffer, key, confidential); + } + + /** + * Initialize the call. + * + * @param byteBuffer + * The NIO byte buffer. + * @param key + * The NIO selection key. + * @param confidential + * Indicates if the call is confidential. + */ + public void init(ByteBuffer byteBuffer, SelectionKey key, + boolean confidential) { setConfidential(confidential); try { diff --git a/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerHelper.java b/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerHelper.java index 80854b5da6..4f32e03191 100644 --- a/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerHelper.java +++ b/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/GrizzlyServerHelper.java @@ -56,7 +56,7 @@ public void start() throws Exception { configure(this.controller); } - getLogger().info("Starting the Grizzly HTTP server"); + getLogger().info("Starting the Grizzly " + getProtocols() + " server"); final Controller controller = this.controller; new Thread() { public void run() { @@ -84,7 +84,8 @@ public void stop() throws Exception { super.stop(); if (this.controller != null) { - getLogger().info("Stopping the Grizzly HTTP server"); + getLogger().info( + "Stopping the Grizzly " + getProtocols() + " server"); this.controller.stop(); } } diff --git a/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/HttpParserFilter.java b/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/HttpParserFilter.java index 389ca49e68..c14f44e396 100644 --- a/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/HttpParserFilter.java +++ b/modules/com.noelios.restlet.ext.grizzly_1.5/src/com/noelios/restlet/ext/grizzly/HttpParserFilter.java @@ -66,7 +66,11 @@ public boolean execute(Context context) throws IOException { if (serverCall == null) { serverCall = new GrizzlyServerCall(this.helper.getServer(), byteBuffer, key, (helper instanceof HttpsServerHelper)); + } else { + serverCall.init(byteBuffer, key, + (helper instanceof HttpsServerHelper)); } + boolean keepAlive = false; // Handle the call
7a5b4fb0d911a1e32a1dbf3a0431587836545be3
Vala
Add gdu and gdu-gtk bindings to the build system.
c
https://github.com/GNOME/vala/
diff --git a/vapi/Makefile.am b/vapi/Makefile.am index 5c33e6e205..2b6def8e84 100644 --- a/vapi/Makefile.am +++ b/vapi/Makefile.am @@ -38,6 +38,10 @@ dist_vapi_DATA = \ gdk-x11-2.0.vapi \ gdl-1.0.deps \ gdl-1.0.vapi \ + gdu.deps \ + gdu.vapi \ + gdu-gtk.deps \ + gdu-gtk.vapi \ gio-2.0.vapi \ gio-unix-2.0.deps \ gio-unix-2.0.vapi \
a97d51e05efd366c7bfc4d52c12fa757c1495a56
Mylyn Reviews
332591: hide internal api for tbr ui
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF index 1c730309..2717a899 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF @@ -4,7 +4,7 @@ Bundle-Name: Mylyn Reviews Bundle-Vendor: Eclipse Mylyn Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.ui;singleton:=true Bundle-Version: 0.7.0.qualifier -Bundle-Activator: org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin +Bundle-Activator: org.eclipse.mylyn.reviews.tasks.ui.internal.ReviewsUiPlugin Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, org.eclipse.mylyn.tasks.ui;bundle-version="3.4.0", @@ -15,5 +15,5 @@ Require-Bundle: org.eclipse.ui, org.eclipse.mylyn.reviews.tasks.core;bundle-version="0.0.1" Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Export-Package: org.eclipse.mylyn.reviews.tasks.ui, - org.eclipse.mylyn.reviews.tasks.ui.editors +Export-Package: org.eclipse.mylyn.reviews.tasks.ui.internal;x-internal:=true, + org.eclipse.mylyn.reviews.tasks.ui.internal.editors;x-internal:=true diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml b/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml index 12faedae..e9863184 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml @@ -18,7 +18,7 @@ id="org.eclipse.mylyn.reviews.ui.objectContribution1" objectClass="org.eclipse.mylyn.tasks.core.ITaskAttachment"> <action - class="org.eclipse.mylyn.reviews.tasks.ui.CreateReviewActionFromAttachment" + class="org.eclipse.mylyn.reviews.tasks.ui.internal.CreateReviewActionFromAttachment" enablesFor="*" id="org.eclipse.mylyn.reviews.tasks.ui.create_review_from_attachment" label="Create Review from Attachment" @@ -29,7 +29,7 @@ <extension point="org.eclipse.mylyn.tasks.ui.editors"> <pageFactory - class="org.eclipse.mylyn.reviews.tasks.ui.editors.ReviewTaskEditorPageFactory" + class="org.eclipse.mylyn.reviews.tasks.ui.internal.editors.ReviewTaskEditorPageFactory" id="org.eclipse.mylyn.reviews.ui.pageFactory2"> </pageFactory> </extension> diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java similarity index 98% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java index 0b5a77ff..d9265032 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/CreateReviewActionFromAttachment.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui; +package org.eclipse.mylyn.reviews.tasks.ui.internal; import java.util.ArrayList; import java.util.Iterator; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Images.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/Images.java similarity index 98% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Images.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/Images.java index f5c4c8f5..1d80a02e 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Images.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/Images.java @@ -8,7 +8,7 @@ * Contributors: * Christoph Mayerhofer (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui; +package org.eclipse.mylyn.reviews.tasks.ui.internal; import java.net.URL; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Messages.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/Messages.java similarity index 92% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Messages.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/Messages.java index eaf36f61..a6f8c6a8 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/Messages.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/Messages.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui; +package org.eclipse.mylyn.reviews.tasks.ui.internal; import org.eclipse.osgi.util.NLS; @@ -16,7 +16,7 @@ * @author Kilian Matt */ public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.tasks.ui.messages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.tasks.ui.internal.messages"; //$NON-NLS-1$ public static String CreateTask_Success; public static String CreateTask_Title; public static String CreateTask_UploadingAttachment; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewUiUtils.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewUiUtils.java similarity index 94% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewUiUtils.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewUiUtils.java index bbc4276d..ad5d43ab 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewUiUtils.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewUiUtils.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui; +package org.eclipse.mylyn.reviews.tasks.ui.internal; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewsUiPlugin.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java similarity index 97% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewsUiPlugin.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java index 8651c34c..1d0602c9 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/ReviewsUiPlugin.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui; +package org.eclipse.mylyn.reviews.tasks.ui.internal; import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper; import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewTaskMapper; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/AbstractReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/AbstractReviewTaskEditorPart.java similarity index 95% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/AbstractReviewTaskEditorPart.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/AbstractReviewTaskEditorPart.java index baa06c5f..92054398 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/AbstractReviewTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/AbstractReviewTaskEditorPart.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java similarity index 95% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java index c5400b7d..9c426928 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import org.eclipse.swt.graphics.Image; /** diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/IColumnSpec.java similarity index 93% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/IColumnSpec.java index bb87f4f7..5193a152 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/IColumnSpec.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import org.eclipse.swt.graphics.Image; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/Messages.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/Messages.java similarity index 96% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/Messages.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/Messages.java index 16b59e14..fa6121c7 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/Messages.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/Messages.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import org.eclipse.osgi.util.NLS; @@ -16,7 +16,7 @@ * @author Kilian Matt */ public class Messages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.tasks.ui.editors.messages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "org.eclipse.mylyn.reviews.tasks.ui.internal.editors.messages"; //$NON-NLS-1$ public static String CreateReviewTaskEditorPageFactory_Reviews; public static String CreateReviewTaskEditorPart_Patches; public static String CreateReviewTaskEditorPart_Create_Review; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java similarity index 97% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java index 12875b04..8a256914 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import java.util.Collection; @@ -27,8 +27,8 @@ import org.eclipse.mylyn.reviews.tasks.core.internal.ITreeNode; import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewResultNode; import org.eclipse.mylyn.reviews.tasks.core.internal.TaskNode; -import org.eclipse.mylyn.reviews.tasks.ui.Images; -import org.eclipse.mylyn.reviews.tasks.ui.ReviewUiUtils; +import org.eclipse.mylyn.reviews.tasks.ui.internal.Images; +import org.eclipse.mylyn.reviews.tasks.ui.internal.ReviewUiUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java similarity index 97% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java index 657ed0a5..a7b674ca 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPage.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import java.util.HashSet; import java.util.Set; @@ -22,7 +22,7 @@ import org.eclipse.mylyn.reviews.tasks.core.internal.ITreeNode; import org.eclipse.mylyn.reviews.tasks.core.internal.ReviewsUtil; import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties; -import org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin; +import org.eclipse.mylyn.reviews.tasks.ui.internal.ReviewsUiPlugin; import org.eclipse.mylyn.tasks.core.sync.SubmitJobEvent; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPage; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPageFactory.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java similarity index 90% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPageFactory.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java index 5e8f6fa3..c1d99ce4 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPageFactory.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPageFactory.java @@ -8,10 +8,10 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; -import org.eclipse.mylyn.reviews.tasks.ui.Images; -import org.eclipse.mylyn.reviews.tasks.ui.Messages; +import org.eclipse.mylyn.reviews.tasks.ui.internal.Images; +import org.eclipse.mylyn.reviews.tasks.ui.internal.Messages; import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory; import org.eclipse.mylyn.tasks.ui.editors.TaskEditor; import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java similarity index 98% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java index d8bf6cb5..5220bb90 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPart.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; @@ -45,8 +45,8 @@ import org.eclipse.mylyn.reviews.tasks.core.ReviewResult; import org.eclipse.mylyn.reviews.tasks.core.ReviewScope; import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties; -import org.eclipse.mylyn.reviews.tasks.ui.Images; -import org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin; +import org.eclipse.mylyn.reviews.tasks.ui.internal.Images; +import org.eclipse.mylyn.reviews.tasks.ui.internal.ReviewsUiPlugin; import org.eclipse.mylyn.tasks.core.data.TaskAttribute; import org.eclipse.mylyn.tasks.ui.TasksUi; import org.eclipse.swt.SWT; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TableLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/TableLabelProvider.java similarity index 94% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TableLabelProvider.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/TableLabelProvider.java index 7289bf28..51417174 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TableLabelProvider.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/TableLabelProvider.java @@ -8,7 +8,7 @@ * Contributors: * Christoph Mayerhofer (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/TreeHelper.java similarity index 95% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/TreeHelper.java index 7d5fb386..834a431c 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/TreeHelper.java @@ -8,7 +8,7 @@ * Contributors: * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation *******************************************************************************/ -package org.eclipse.mylyn.reviews.tasks.ui.editors; +package org.eclipse.mylyn.reviews.tasks.ui.internal.editors; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.TreeViewerColumn; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/messages.properties b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/messages.properties similarity index 100% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/messages.properties rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/messages.properties diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/messages.properties b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/messages.properties similarity index 100% rename from tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/messages.properties rename to tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/messages.properties
f84e57e1c6ae9b09dc5fab974a8b9010c04147ef
genericworkflownodes$genericknimenodes
be passed to the node generator which is then used as the directory in where to look for plugin.properties. Otherwise the current working directory is used. - The payload directory must now reside in the plugin.properties'
p
https://github.com/genericworkflownodes/genericknimenodes
diff --git a/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java index 9f560b27..58398164 100644 --- a/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java +++ b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReader.java @@ -52,492 +52,440 @@ import org.dom4j.Node; import org.dom4j.io.SAXReader; -public class CTDNodeConfigurationReader implements NodeConfigurationReader -{ - - private static Logger log = Logger.getLogger(CTDNodeConfigurationReader.class.getCanonicalName()); - +public class CTDNodeConfigurationReader implements NodeConfigurationReader { + + private static Logger log = Logger + .getLogger(CTDNodeConfigurationReader.class.getCanonicalName()); + private Document doc; private DefaultNodeConfiguration config = new DefaultNodeConfiguration(); - - public CTDNodeConfigurationReader() - { + + public CTDNodeConfigurationReader() { } - - + protected String SECTION_NODE_NAME = "NODE"; - protected String INPUTFILE_TAG = "input file"; - protected String OUTPUTFILE_TAG = "output file"; - + protected String INPUTFILE_TAG = "input file"; + protected String OUTPUTFILE_TAG = "output file"; + protected Set<String> captured_ports = new HashSet<String>(); - - private static List<Port> in_ports; - private static List<Port> out_ports; - - private void readPorts() throws Exception - { - in_ports = new ArrayList<Port>(); + + private static List<Port> in_ports; + private static List<Port> out_ports; + + private void readPorts() throws Exception { + in_ports = new ArrayList<Port>(); out_ports = new ArrayList<Port>(); - - Node node = doc.selectSingleNode("/tool/PARAMETERS"); + + Node node = this.doc.selectSingleNode("/tool/PARAMETERS"); Element root = (Element) node; - processIOPorts(root); - - config.setInports((Port[]) in_ports.toArray(new Port[in_ports.size()])); - config.setOutports((Port[]) out_ports.toArray(new Port[out_ports.size()])); + this.processIOPorts(root); + + this.config.setInports(in_ports.toArray(new Port[in_ports.size()])); + this.config.setOutports(out_ports.toArray(new Port[out_ports.size()])); } - - + @SuppressWarnings("unchecked") - public void processIOPorts(Element root) throws Exception - { - List<Node> items = root.selectNodes("//ITEM[contains(@tags,'"+OUTPUTFILE_TAG+"')]"); - for(Node n: items) - { - createPortFromNode(n, false); - } - items = root.selectNodes("//ITEM[contains(@tags,'"+INPUTFILE_TAG+"')]"); - for(Node n: items) - { - createPortFromNode(n, false); - } - items = root.selectNodes("//ITEMLIST[contains(@tags,'"+INPUTFILE_TAG+"')]"); - for(Node n: items) - { - createPortFromNode(n, true); - } - items = root.selectNodes("//ITEMLIST[contains(@tags,'"+OUTPUTFILE_TAG+"')]"); - for(Node n: items) - { - createPortFromNode(n, true); + public void processIOPorts(Element root) throws Exception { + List<Node> items = root.selectNodes("//ITEM[contains(@tags,'" + + this.OUTPUTFILE_TAG + "')]"); + for (Node n : items) { + this.createPortFromNode(n, false); + } + items = root.selectNodes("//ITEM[contains(@tags,'" + this.INPUTFILE_TAG + + "')]"); + for (Node n : items) { + this.createPortFromNode(n, false); + } + items = root.selectNodes("//ITEMLIST[contains(@tags,'" + + this.INPUTFILE_TAG + "')]"); + for (Node n : items) { + this.createPortFromNode(n, true); + } + items = root.selectNodes("//ITEMLIST[contains(@tags,'" + + this.OUTPUTFILE_TAG + "')]"); + for (Node n : items) { + this.createPortFromNode(n, true); } } - + @SuppressWarnings("unchecked") - public void readParameters() throws Exception - { - Node root = doc.selectSingleNode("/tool/PARAMETERS"); - List<Node> items = root.selectNodes("//ITEM[not(contains(@tags,'"+OUTPUTFILE_TAG+"')) and not(contains(@tags,'"+INPUTFILE_TAG+"'))]"); - for(Node n: items) - { - processItem(n); - } - items = root.selectNodes("//ITEMLIST[not(contains(@tags,'"+OUTPUTFILE_TAG+"')) and not(contains(@tags,'"+INPUTFILE_TAG+"'))]"); - for(Node n: items) - { - processMultiItem(n); + public void readParameters() throws Exception { + Node root = this.doc.selectSingleNode("/tool/PARAMETERS"); + List<Node> items = root.selectNodes("//ITEM[not(contains(@tags,'" + + this.OUTPUTFILE_TAG + "')) and not(contains(@tags,'" + + this.INPUTFILE_TAG + "'))]"); + for (Node n : items) { + this.processItem(n); + } + items = root.selectNodes("//ITEMLIST[not(contains(@tags,'" + + this.OUTPUTFILE_TAG + "')) and not(contains(@tags,'" + + this.INPUTFILE_TAG + "'))]"); + for (Node n : items) { + this.processMultiItem(n); } } - - public String getPath(Node n) - { - + + public String getPath(Node n) { + List<String> path_nodes = new ArrayList<String>(); - while(n!=null&&!n.getName().equals("PARAMETERS")) - { + while (n != null && !n.getName().equals("PARAMETERS")) { path_nodes.add(n.valueOf("@name")); n = n.getParent(); } - + Collections.reverse(path_nodes); - - + String ret = ""; int N = path_nodes.size(); - for(int i=0;i<N;i++) - { - if(i==N-1) - ret+=path_nodes.get(i); - else - ret+=path_nodes.get(i)+"."; + for (int i = 0; i < N; i++) { + if (i == N - 1) { + ret += path_nodes.get(i); + } else { + ret += path_nodes.get(i) + "."; + } } return ret; } - - private void createPortFromNode(Node node, boolean multi) throws Exception - { - + + private void createPortFromNode(Node node, boolean multi) throws Exception { + Element elem = (Element) node; - - String name = node.valueOf("@name"); - String descr = node.valueOf("@description"); - String tags = node.valueOf("@tags"); - - if(name.equals("write_ini")||name.equals("write_par")||name.equals("par")||name.equals("help")) - { + + String name = node.valueOf("@name"); + String descr = node.valueOf("@description"); + String tags = node.valueOf("@tags"); + + if (name.equals("write_ini") || name.equals("write_par") + || name.equals("par") || name.equals("help")) return; - } - - + Port port = new Port(); - - + port.setMultiFile(multi); - - if(tags.contains(INPUTFILE_TAG)||tags.contains(OUTPUTFILE_TAG)) - { - String[] file_extensions = null; - - if(elem.attributeValue("supported_formats")==null) - { - if(elem.attributeValue("restrictions")!=null) - { - String formats = node.valueOf("@restrictions"); + + if (tags.contains(this.INPUTFILE_TAG) + || tags.contains(this.OUTPUTFILE_TAG)) { + String[] file_extensions = null; + + if (elem.attributeValue("supported_formats") == null) { + if (elem.attributeValue("restrictions") != null) { + String formats = node.valueOf("@restrictions"); file_extensions = formats.split(","); - for(int i=0;i<file_extensions.length;i++) - { - file_extensions[i] = file_extensions[i].replace("*.", ""); + for (int i = 0; i < file_extensions.length; i++) { + file_extensions[i] = file_extensions[i].replace("*.", + ""); } - } - else - throw new Exception("i/o item '"+elem.attributeValue("name")+"' with missing attribute supported_formats detected"); - } - else - { - String formats = node.valueOf("@supported_formats"); + } else + throw new Exception( + "i/o item '" + + elem.attributeValue("name") + + "' with missing attribute supported_formats detected"); + } else { + String formats = node.valueOf("@supported_formats"); file_extensions = formats.split(","); - for(int i=0;i<file_extensions.length;i++) + for (int i = 0; i < file_extensions.length; i++) { file_extensions[i] = file_extensions[i].trim(); + } } - - - - - String path = getPath(node); + String path = this.getPath(node); port.setName(path); - + port.setDescription(descr); - + boolean optional = true; - if(tags.contains("mandatory")||tags.contains("required")) + if (tags.contains("mandatory") || tags.contains("required")) { optional = false; - else + } else { optional = true; + } port.setOptional(optional); - - - for(String mt : file_extensions) - { + + for (String mt : file_extensions) { port.addMimeType(new MIMEtype(mt.trim())); } - + } - if(tags.contains(OUTPUTFILE_TAG)) - { + if (tags.contains(this.OUTPUTFILE_TAG)) { out_ports.add(port); - captured_ports.add(port.getName()); - - if(multi) - { - String path = getPath(node); - FileListParameter param = new FileListParameter(name, new ArrayList<String>()); + this.captured_ports.add(port.getName()); + + if (multi) { + String path = this.getPath(node); + FileListParameter param = new FileListParameter(name, + new ArrayList<String>()); param.setPort(port); param.setDescription(descr); param.setIsOptional(false); - config.addParameter(path, param); + this.config.addParameter(path, param); } } - if(tags.contains(INPUTFILE_TAG)) - { + if (tags.contains(this.INPUTFILE_TAG)) { in_ports.add(port); - captured_ports.add(port.getName()); - } - + this.captured_ports.add(port.getName()); + } + } - - public void processItem(Node elem) throws Exception - { + + public void processItem(Node elem) throws Exception { String name = elem.valueOf("@name"); - - String path = getPath(elem); - - if(captured_ports.contains(path)) + + String path = this.getPath(elem); + + if (this.captured_ports.contains(path)) return; - - if(name.equals("write_ini")||name.equals("write_par")||name.equals("par")||name.equals("help")) - { + + if (name.equals("write_ini") || name.equals("write_par") + || name.equals("par") || name.equals("help")) return; - } - - Parameter<?> param = getParameterFromNode(elem); - config.addParameter(path, param); + + Parameter<?> param = this.getParameterFromNode(elem); + this.config.addParameter(path, param); } - - public void processMultiItem(Node elem) throws Exception - { + + public void processMultiItem(Node elem) throws Exception { String name = elem.valueOf("@name"); - - String path = getPath(elem); - - if(captured_ports.contains(path)) + + String path = this.getPath(elem); + + if (this.captured_ports.contains(path)) return; - - if(name.equals("write_ini")||name.equals("write_par")||name.equals("par")||name.equals("help")) - { + + if (name.equals("write_ini") || name.equals("write_par") + || name.equals("par") || name.equals("help")) return; - } - - Parameter<?> param = getMultiParameterFromNode(elem); - config.addParameter(path, param); + + Parameter<?> param = this.getMultiParameterFromNode(elem); + this.config.addParameter(path, param); } - - private void readDescription() throws Exception - { - Node node = doc.selectSingleNode("/tool"); - if(node==null) + + private void readDescription() throws Exception { + Node node = this.doc.selectSingleNode("/tool"); + if (node == null) throw new Exception("CTD has no root named tool"); - - String lstatus = node.valueOf("@status"); - if(lstatus!=null && lstatus.equals("")) + + String lstatus = node.valueOf("@status"); + if (lstatus != null && lstatus.equals("")) throw new Exception("CTD has no status"); - - config.setStatus(lstatus); - - node = doc.selectSingleNode("/tool/name"); - if(node==null) + + this.config.setStatus(lstatus); + + node = this.doc.selectSingleNode("/tool/name"); + if (node == null) throw new Exception("CTD has no tool name"); - String name = node.valueOf("text()"); - if(name.equals("")) + String name = node.valueOf("text()"); + if (name.equals("")) throw new Exception("CTD has no tool name"); - config.setName(name); - - - - node = doc.selectSingleNode("/tool/description"); - String sdescr = ""; - if(node!=null) - sdescr = node.valueOf("text()"); - config.setDescription(sdescr); - - node = doc.selectSingleNode("/tool/path"); - String spath = ""; - if(node!=null) - spath = node.valueOf("text()"); - - config.setCommand(spath); - - node = doc.selectSingleNode("/tool/manual"); + this.config.setName(name); + + node = this.doc.selectSingleNode("/tool/description"); + String sdescr = ""; + if (node != null) { + sdescr = node.valueOf("text()"); + } + this.config.setDescription(sdescr); + + node = this.doc.selectSingleNode("/tool/path"); + String spath = ""; + if (node != null) { + spath = node.valueOf("text()"); + } + + this.config.setCommand(spath); + + node = this.doc.selectSingleNode("/tool/manual"); String ldescr = ""; - if(node!=null) - ldescr = node.valueOf("text()"); - config.setManual(ldescr); - - node = doc.selectSingleNode("/tool/version"); + if (node != null) { + ldescr = node.valueOf("text()"); + } + this.config.setManual(ldescr); + + node = this.doc.selectSingleNode("/tool/version"); String lversion = ""; - if(node!=null) - lversion = node.valueOf("text()"); - config.setVersion(lversion); - - node = doc.selectSingleNode("/tool/docurl"); - String docurl = ""; - if(node!=null) - docurl = node.valueOf("text()"); - config.setDocUrl(docurl); - - node = doc.selectSingleNode("/tool/category"); + if (node != null) { + lversion = node.valueOf("text()"); + } + this.config.setVersion(lversion); + + node = this.doc.selectSingleNode("/tool/docurl"); + String docurl = ""; + if (node != null) { + docurl = node.valueOf("text()"); + } + this.config.setDocUrl(docurl); + + node = this.doc.selectSingleNode("/tool/category"); String cat = ""; - if(node!=null) - cat = node.valueOf("text()"); - config.setCategory(cat); + if (node != null) { + cat = node.valueOf("text()"); + } + this.config.setCategory(cat); } - - private Parameter<?> getParameterFromNode(Node node) throws Exception - { + + private Parameter<?> getParameterFromNode(Node node) throws Exception { Parameter<?> ret = null; - String type = node.valueOf("@type"); - String name = node.valueOf("@name"); - String value = node.valueOf("@value"); + String type = node.valueOf("@type"); + String name = node.valueOf("@name"); + String value = node.valueOf("@value"); String restrs = node.valueOf("@restrictions"); - String descr = node.valueOf("@description"); - String tags = node.valueOf("@tags"); - - if (type.toLowerCase().equals("double")||type.toLowerCase().equals("float")) - { - ret = processDoubleParameter(name, value, restrs, tags); - } - else - { - if(type.toLowerCase().equals("int")) - { - ret = processIntParameter(name, value, restrs, tags); - } - else - { - if(type.toLowerCase().equals("string")) - { - ret = processStringParameter(name, value, restrs, tags); + String descr = node.valueOf("@description"); + String tags = node.valueOf("@tags"); + + if (type.toLowerCase().equals("double") + || type.toLowerCase().equals("float")) { + ret = this.processDoubleParameter(name, value, restrs, tags); + } else { + if (type.toLowerCase().equals("int")) { + ret = this.processIntParameter(name, value, restrs, tags); + } else { + if (type.toLowerCase().equals("string")) { + ret = this + .processStringParameter(name, value, restrs, tags); } } } - + ret.setDescription(descr); Set<String> tagset = tokenSet(tags); - - if(tagset.contains("mandatory")||tagset.contains("required")) + + if (tagset.contains("mandatory") || tagset.contains("required")) { ret.setIsOptional(false); - - if(tagset.contains("advanced")) + } + + if (tagset.contains("advanced")) { ret.setAdvanced(true); - + } + return ret; } - - private Parameter<?> getMultiParameterFromNode(Node node) throws Exception - { - String type = node.valueOf("@type"); - String name = node.valueOf("@name"); - String value = node.valueOf("@value"); + + private Parameter<?> getMultiParameterFromNode(Node node) throws Exception { + String type = node.valueOf("@type"); + String name = node.valueOf("@name"); + String value = node.valueOf("@value"); String restrs = node.valueOf("@restrictions"); - String descr = node.valueOf("@description"); - String tags = node.valueOf("@tags"); - + String descr = node.valueOf("@description"); + String tags = node.valueOf("@tags"); + Set<String> tagset = tokenSet(tags); - + @SuppressWarnings("unchecked") - List<Node> subnodes = node.selectNodes("LISTITEM"); - - List<String> values = new ArrayList<String>(); - for(Node n: subnodes) - { + List<Node> subnodes = node.selectNodes("LISTITEM"); + + List<String> values = new ArrayList<String>(); + for (Node n : subnodes) { values.add(n.valueOf("@value")); } - + Parameter<?> param = null; - - if (type.toLowerCase().equals("double")||type.toLowerCase().equals("float")) - { - param = processDoubleListParameter(name, values, restrs, tags); - } - else - { - if(type.toLowerCase().equals("int")) - { - param = processIntListParameter(name, values, restrs, tags); - } - else - { - if(type.toLowerCase().equals("string")) - { - param = processStringListParameter(name, values, restrs, tags); + if (type.toLowerCase().equals("double") + || type.toLowerCase().equals("float")) { + param = this.processDoubleListParameter(name, values, restrs, tags); + } else { + if (type.toLowerCase().equals("int")) { + param = this + .processIntListParameter(name, values, restrs, tags); + } else { + if (type.toLowerCase().equals("string")) { + param = this.processStringListParameter(name, values, + restrs, tags); } } } - + param.setDescription(descr); - - if(tagset.contains("mandatory")||tagset.contains("required")) + + if (tagset.contains("mandatory") || tagset.contains("required")) { param.setIsOptional(false); + } - if(tagset.contains("advanced")) + if (tagset.contains("advanced")) { param.setAdvanced(true); - + } + return param; } - private Parameter<?> processStringListParameter(String name, List<String> values, String restrs, String tags) - { - return new StringListParameter(name,values); + private Parameter<?> processStringListParameter(String name, + List<String> values, String restrs, String tags) { + return new StringListParameter(name, values); } - - private Parameter<?> processIntListParameter(String name, List<String> values, String restrs, String tags) - { + private Parameter<?> processIntListParameter(String name, + List<String> values, String restrs, String tags) { List<Integer> vals = new ArrayList<Integer>(); - for(String cur_val: values) - { + for (String cur_val : values) { vals.add(Integer.parseInt(cur_val)); } - - IntegerListParameter ret = new IntegerListParameter(name,vals); - + + IntegerListParameter ret = new IntegerListParameter(name, vals); + Integer[] bounds = new Integer[2]; - getIntegerBoundsFromRestrictions( restrs, bounds); + this.getIntegerBoundsFromRestrictions(restrs, bounds); ret.setLowerBound(bounds[0]); ret.setUpperBound(bounds[1]); - + return ret; } - - private Parameter<?> processDoubleListParameter(String name, List<String> values, String restrs, String tags) - { + private Parameter<?> processDoubleListParameter(String name, + List<String> values, String restrs, String tags) { List<Double> vals = new ArrayList<Double>(); - for(String cur_val: values) - { + for (String cur_val : values) { vals.add(Double.parseDouble(cur_val)); } - - DoubleListParameter ret = new DoubleListParameter(name,vals); - + + DoubleListParameter ret = new DoubleListParameter(name, vals); + Double[] bounds = new Double[2]; - getDoubleBoundsFromRestrictions( restrs, bounds); + this.getDoubleBoundsFromRestrictions(restrs, bounds); ret.setLowerBound(bounds[0]); ret.setUpperBound(bounds[1]); - + return ret; } - - private void getDoubleBoundsFromRestrictions(String restrs, Double[] bounds) - { + private void getDoubleBoundsFromRestrictions(String restrs, Double[] bounds) { Double UB = Double.POSITIVE_INFINITY; Double LB = Double.NEGATIVE_INFINITY; - - if(restrs.equals("")) - { + + if (restrs.equals("")) { bounds[0] = LB; bounds[1] = UB; return; } - + String[] toks = restrs.split(":"); - if (toks.length != 0) - { - if (toks[0].equals("")) - { + if (toks.length != 0) { + if (toks[0].equals("")) { // upper bounded only double ub; - try - { + try { ub = Double.parseDouble(toks[1]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { throw new RuntimeException(e); } UB = ub; - } - else - { + } else { // lower and upper bounded - if (toks.length == 2) - { + if (toks.length == 2) { double lb; double ub; - try - { + try { lb = Double.parseDouble(toks[0]); ub = Double.parseDouble(toks[1]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { throw new RuntimeException(e); } LB = lb; UB = ub; - } - else - { + } else { // lower bounded only double lb; - try - { + try { lb = Double.parseDouble(toks[0]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { throw new RuntimeException(e); } LB = lb; @@ -545,87 +493,69 @@ private void getDoubleBoundsFromRestrictions(String restrs, Double[] bounds) } } bounds[0] = LB; - bounds[1] = UB; + bounds[1] = UB; } - - private Parameter<?> processDoubleParameter(String name, String value, String restrs, String tags) throws Exception - { + + private Parameter<?> processDoubleParameter(String name, String value, + String restrs, String tags) throws Exception { DoubleParameter retd = new DoubleParameter(name, value); Double[] bounds = new Double[2]; - getDoubleBoundsFromRestrictions( restrs, bounds); + this.getDoubleBoundsFromRestrictions(restrs, bounds); retd.setLowerBound(bounds[0]); retd.setUpperBound(bounds[1]); return retd; } - - private static Set<String> tokenSet(String s) - { + + private static Set<String> tokenSet(String s) { Set<String> ret = new HashSet<String>(); String[] toks = s.split(","); - for(String tok: toks) + for (String tok : toks) { ret.add(tok); + } return ret; } - private void getIntegerBoundsFromRestrictions(String restrs, Integer[] bounds) - { + private void getIntegerBoundsFromRestrictions(String restrs, + Integer[] bounds) { Integer UB = Integer.MAX_VALUE; Integer LB = Integer.MIN_VALUE; - - if(restrs.equals("")) - { + + if (restrs.equals("")) { bounds[0] = LB; bounds[1] = UB; return; } - String[] toks = restrs.split(":"); - if (toks.length != 0) - { - if (toks[0].equals("")) - { + if (toks.length != 0) { + if (toks[0].equals("")) { // upper bounded only int ub; - try - { + try { ub = Integer.parseInt(toks[1]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { throw new RuntimeException(e); } UB = ub; - } - else - { + } else { // lower and upper bounded - if (toks.length == 2) - { + if (toks.length == 2) { int lb; int ub; - try - { + try { lb = Integer.parseInt(toks[0]); ub = Integer.parseInt(toks[1]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { throw new RuntimeException(e); } LB = lb; UB = ub; - } - else - { + } else { // lower bounded only int lb; - try - { + try { lb = Integer.parseInt(toks[0]); - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { throw new RuntimeException(e); } LB = lb; @@ -635,94 +565,95 @@ private void getIntegerBoundsFromRestrictions(String restrs, Integer[] bounds) bounds[0] = LB; bounds[1] = UB; } - - private Parameter<?> processIntParameter(String name, String value, String restrs, String tags) throws Exception - { + + private Parameter<?> processIntParameter(String name, String value, + String restrs, String tags) throws Exception { IntegerParameter reti = new IntegerParameter(name, value); Integer[] bounds = new Integer[2]; - getIntegerBoundsFromRestrictions(restrs, bounds); + this.getIntegerBoundsFromRestrictions(restrs, bounds); reti.setLowerBound(bounds[0]); reti.setUpperBound(bounds[1]); return reti; } - private Parameter<?> processStringParameter(String name, String value, String restrs, String tags) throws Exception - { + private Parameter<?> processStringParameter(String name, String value, + String restrs, String tags) throws Exception { Parameter<?> rets = null; String[] toks = restrs.split(","); - - for(int i=0;i<toks.length;i++) - { + + for (int i = 0; i < toks.length; i++) { toks[i] = toks[i].trim(); } - - if(restrs.length()>0) - { - if( (toks[0].equals("true")&&toks[1].equals("false")) || (toks[0].equals("false")&&toks[1].equals("true")) ) - { + + if (restrs.length() > 0) { + if ((toks[0].equals("true") && toks[1].equals("false")) + || (toks[0].equals("false") && toks[1].equals("true"))) { rets = new BoolParameter(name, value); - } - else - { + } else { rets = new StringChoiceParameter(name, toks); ((StringChoiceParameter) rets).setValue(value); } - } - else - { + } else { rets = new StringParameter(name, value); } - + return rets; } @Override - public NodeConfiguration read(InputStream xmlstream) throws Exception - { - SAXParserFactory factory = SAXParserFactory.newInstance(); - SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); - - factory.setSchema(schemaFactory.newSchema(new Source[] {new StreamSource(SchemaProvider.class.getResourceAsStream("CTD.xsd")), new StreamSource(SchemaProvider.class.getResourceAsStream("Param_1_3.xsd"))})); - - SAXParser parser = factory.newSAXParser(); - - SAXReader reader = new SAXReader(parser.getXMLReader()); - reader.setValidation(false); - - SimpleErrorHandler errorHandler = new SimpleErrorHandler(); - - reader.setErrorHandler(errorHandler); - - doc = reader.read(xmlstream); - - if(!errorHandler.isValid()) - { - System.err.println(errorHandler.getErrorReport()); - throw new Exception("CTD file is not valid !"); - } - - readPorts(); - readParameters(); - readDescription(); - readMapping(); - config.setXml(doc.asXML()); - - return config; - } + public NodeConfiguration read(InputStream xmlstream) + throws CTDNodeConfigurationReaderException { + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + SchemaFactory schemaFactory = SchemaFactory + .newInstance("http://www.w3.org/2001/XMLSchema"); + + factory.setSchema(schemaFactory.newSchema(new Source[] { + new StreamSource(SchemaProvider.class + .getResourceAsStream("CTD.xsd")), + new StreamSource(SchemaProvider.class + .getResourceAsStream("Param_1_3.xsd")) })); + + SAXParser parser = factory.newSAXParser(); + + SAXReader reader = new SAXReader(parser.getXMLReader()); + reader.setValidation(false); + + SimpleErrorHandler errorHandler = new SimpleErrorHandler(); + reader.setErrorHandler(errorHandler); - private void readMapping() throws Exception - { - Node node = doc.selectSingleNode("/tool/mapping"); - if(node==null&&this.config.getStatus().equals("external")) - throw new Exception("CTD has no mapping tag and is an external tool"); - if(node==null) + this.doc = reader.read(xmlstream); + + if (!errorHandler.isValid()) { + System.err.println(errorHandler.getErrorReport()); + throw new Exception("CTD file is not valid !"); + } + + this.readPorts(); + this.readParameters(); + this.readDescription(); + this.readMapping(); + this.config.setXml(this.doc.asXML()); + + return this.config; + } catch (Exception e) { + throw new CTDNodeConfigurationReaderException(e); + } + } + + private void readMapping() throws Exception { + Node node = this.doc.selectSingleNode("/tool/mapping"); + if (node == null && this.config.getStatus().equals("external")) + throw new Exception( + "CTD has no mapping tag and is an external tool"); + if (node == null) return; - - String mapping = node.valueOf("text()"); - if(mapping.equals("")) + + String mapping = node.valueOf("text()"); + if (mapping.equals("")) throw new Exception("CTD has an empty mapping tag"); - config.setMapping(mapping); + this.config.setMapping(mapping); } } diff --git a/src/org/ballproject/knime/base/config/CTDNodeConfigurationReaderException.java b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReaderException.java new file mode 100644 index 00000000..565a5cb2 --- /dev/null +++ b/src/org/ballproject/knime/base/config/CTDNodeConfigurationReaderException.java @@ -0,0 +1,10 @@ +package org.ballproject.knime.base.config; + +public class CTDNodeConfigurationReaderException extends Exception { + + private static final long serialVersionUID = -4982931986389455916L; + + public CTDNodeConfigurationReaderException(Throwable throwable) { + super(throwable); + } +} diff --git a/src/org/ballproject/knime/nodegeneration/KNIMENode.java b/src/org/ballproject/knime/nodegeneration/KNIMENode.java new file mode 100644 index 00000000..b530564f --- /dev/null +++ b/src/org/ballproject/knime/nodegeneration/KNIMENode.java @@ -0,0 +1,28 @@ +package org.ballproject.knime.nodegeneration; + +import java.util.logging.Logger; + +public class KNIMENode { + + private static Logger logger = Logger.getLogger(NodeGenerator.class + .getCanonicalName()); + + public static boolean checkNodeName(String name) { + if (!name.matches("[[A-Z]|[a-z]][[0-9]|[A-Z]|[a-z]]+")) + return false; + return true; + } + + public static String fixNodeName(String name) { + logger.info("trying to fix node class name " + name); + name = name.replace(".", ""); + name = name.replace("-", ""); + name = name.replace("_", ""); + name = name.replace("#", ""); + name = name.replace("+", ""); + name = name.replace("$", ""); + name = name.replace(":", ""); + logger.info("fixed node name " + name); + return name; + } +} diff --git a/src/org/ballproject/knime/nodegeneration/Main.java b/src/org/ballproject/knime/nodegeneration/Main.java new file mode 100644 index 00000000..6ee2f6cb --- /dev/null +++ b/src/org/ballproject/knime/nodegeneration/Main.java @@ -0,0 +1,25 @@ +package org.ballproject.knime.nodegeneration; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.logging.Logger; + +public class Main { + + private static Logger logger = Logger.getLogger(NodeGenerator.class + .getCanonicalName()); + + public static void main(String[] args) { + File pluginDir = new File((args.length > 0) ? args[0] : ".") + .getAbsoluteFile(); + + try { + NodeGenerator nodeGenerator = new NodeGenerator(pluginDir); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/org/ballproject/knime/nodegeneration/NodeGenerator.java b/src/org/ballproject/knime/nodegeneration/NodeGenerator.java index 1f3043a2..6967fa00 100644 --- a/src/org/ballproject/knime/nodegeneration/NodeGenerator.java +++ b/src/org/ballproject/knime/nodegeneration/NodeGenerator.java @@ -19,13 +19,14 @@ package org.ballproject.knime.nodegeneration; - import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; +import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -34,12 +35,12 @@ import java.util.Map; import java.util.Properties; import java.util.Set; +import java.util.logging.Level; import java.util.logging.Logger; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import org.ballproject.knime.base.config.NodeConfiguration; import org.ballproject.knime.base.config.CTDNodeConfigurationReader; +import org.ballproject.knime.base.config.CTDNodeConfigurationReaderException; +import org.ballproject.knime.base.config.NodeConfiguration; import org.ballproject.knime.base.mime.MIMEtype; import org.ballproject.knime.base.parameter.Parameter; import org.ballproject.knime.base.port.Port; @@ -47,8 +48,10 @@ import org.ballproject.knime.base.schemas.SchemaValidator; import org.ballproject.knime.base.util.Helper; import org.ballproject.knime.base.util.ToolRunner; +import org.ballproject.knime.nodegeneration.exceptions.DuplicateNodeNameException; +import org.ballproject.knime.nodegeneration.exceptions.InvalidNodeNameException; +import org.ballproject.knime.nodegeneration.exceptions.UnknownMimeTypeException; import org.ballproject.knime.nodegeneration.templates.TemplateResources; - import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; @@ -57,648 +60,704 @@ import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; +import org.eclipse.core.commands.ExecutionException; import org.jaxen.JaxenException; import org.jaxen.SimpleNamespaceContext; import org.jaxen.dom4j.Dom4jXPath; -public class NodeGenerator -{ - private static Logger logger = Logger.getLogger(NodeGenerator.class.getCanonicalName()); - - private static Document plugindoc; - private static NodeConfiguration config; - - private static String _pluginname_; - private static String _destdir_; - private static String _destsrcdir_; - private static String _pluginpackage_; - private static String _packagedir_; - private static String _descriptordir_; - private static String _executabledir_; - private static String _abspackagedir_; - private static String _absnodedir_; - private static String _iconpath_; - private static String _useini_ = "true"; - - private static String cur_cat; - private static String cur_path; - private static String _package_root_; - private static String _BINPACKNAME_; - private static String _payloaddir_; - - private static Set<String> ext_tools = new HashSet<String>(); - - private static Properties props; - - public static void assertRestrictedAlphaNumeric(Object obj, String id) - { - if(obj==null||obj.toString().equals("")) - { - panic(id+" was not properly defined"); +public class NodeGenerator { + private static final String PLUGIN_PROPERTIES = "plugin.properties"; + + private static Logger logger = Logger.getLogger(NodeGenerator.class + .getCanonicalName()); + + private String packageName; + private String pluginname; + + private File payloadDirectory; + private File descriptorDirectory; + + private String nodeRepositoryRoot; + + private Set<String> ext_tools = new HashSet<String>(); + + private Properties props; + + public NodeGenerator(File pluginDir) throws IOException, + ExecutionException, DocumentException, DuplicateNodeNameException, + InvalidNodeNameException, CTDNodeConfigurationReaderException, + UnknownMimeTypeException { + if (!pluginDir.isDirectory()) + throw new FileNotFoundException("Path " + pluginDir.getPath() + + " is no valid directory."); + + this.payloadDirectory = getPluginDirectory(pluginDir); + if (!this.payloadDirectory.isDirectory()) + throw new FileNotFoundException("Could not find payload directory " + + this.payloadDirectory.getPath()); + + this.descriptorDirectory = getDescriptorsDirectory(pluginDir); + File executablesDirectory = getExecutablesDirectory(pluginDir); + + File propertyFile = new File(pluginDir, PLUGIN_PROPERTIES); + + Properties props = new Properties(); + try { + props.load(new FileInputStream(propertyFile)); + } catch (FileNotFoundException e) { + throw new FileNotFoundException("Could not find property file " + + propertyFile.getPath()); + } catch (IOException e) { + throw new IOException("Could not load property file", e); } - String re = "^\\w+$"; - if(!obj.toString().matches(re)) - { - panic(id+" is not a proper alpha numeric value "+obj.toString()); + + this.packageName = getPackageName(props); + if (this.packageName == null || this.packageName.isEmpty()) + throw new InvalidParameterException("No package name was specified"); + if (!isValidPackageName(this.packageName)) + throw new InvalidParameterException("The given package name \"" + + this.packageName + "\" is invalid"); + + this.pluginname = getPluginName(props, this.packageName); + if (this.packageName == null || this.packageName.isEmpty()) + throw new InvalidParameterException("No plugin name was specified"); + if (!isPluginNameValid(this.pluginname)) + throw new InvalidParameterException("The package name \"" + + this.pluginname + + "\" must only contain alpha numeric characters"); + + // the root node where to attach the generated nodes + this.nodeRepositoryRoot = getNodeRepositoryRoot(props); + if (this.nodeRepositoryRoot == null + || this.nodeRepositoryRoot.isEmpty()) + throw new InvalidParameterException( + "No node repository root defined"); + // TODO: validation + + if (this.descriptorDirectory.isDirectory()) { + if (executablesDirectory.isDirectory()) { + logger.log( + Level.WARNING, + "Both directories \"" + + this.descriptorDirectory.getPath() + + "\" and \"" + + executablesDirectory + + "\" exists. The latter will be ignored and the provided *.ctd files will be used."); + } else { + + } + } else { + if (!executablesDirectory.isDirectory()) + throw new FileNotFoundException("Neither the directory \"" + + this.descriptorDirectory.getPath() + "\" nor \"" + + executablesDirectory + "\" exists."); + + this.descriptorDirectory = generateDescriptors( + executablesDirectory, getCtdWriteSwitch(props)); } - } - - public static void assertDefinition(Object obj, String id) - { - if(obj==null||obj.toString().equals("")) - { - panic(id+" was not properly defined"); + + // e.g. /tmp/327 + File destinationDirectory = this.getDestinationDirectory(); + + // e.g. /tmp/327/src + File destinationSourceDirectory = new File(destinationDirectory, "src"); + + // e.g. /tmp/327/foo.bar + File destinationFQNDirectory = createPackageDirectory( + destinationSourceDirectory, this.packageName); + + // e.g. /tmp/327/foo.bar/knime/nodes + File destinationFQNNodeDirectory = new File(destinationFQNDirectory, + "knime" + File.separator + "nodes"); + + File destinationPluginXML = new File(destinationDirectory, "plugin.xml"); + Document pluginXML = preparePluginXML(destinationDirectory, + destinationPluginXML); + + try { + installMimeTypes(pluginXML, destinationFQNNodeDirectory, new File( + this.descriptorDirectory, "mimetypes.xml"), this.pluginname); + } catch (JaxenException e) { + throw new DocumentException(e); } + + Set<String> node_names = new HashSet<String>(); + Set<String> ext_tools = new HashSet<String>(); + processDescriptors(node_names, ext_tools, pluginXML, + this.descriptorDirectory, this.nodeRepositoryRoot, + this.pluginname, destinationFQNNodeDirectory, this.packageName); + + // TODO + // this.installIcon(); + + fillProperties(props, destinationFQNDirectory); + + post(pluginXML, destinationPluginXML, this.packageName, + destinationFQNDirectory, destinationFQNNodeDirectory, + this.payloadDirectory, node_names, ext_tools); + } - - public static void assertValidPackageName(String pname, String id) - { - if(pname==null||pname.equals("")) - { - panic(id+" is no proper Java package name"); - } - String re = "^([A-Za-z_]{1}[A-Za-z0-9_]*(\\.[A-Za-z_]{1}[A-Za-z0-9_]*)*)$"; - if(!pname.matches(re)) - panic(id+" is no proper Java package name"); - } - - public static void assertDirectoryExistence(String dirname, String id) - { - File dir = new File(dirname); - if ( !(dir.exists() && dir.isDirectory()) ) - { - panic(dirname+" supplied as "+id+" is no valid directory"); - } + + /** + * Returns the directory containing the payload which consists of binaries + * for each platform and an optional ini-file. + * + * @param rootDirectory + * @return + */ + private static File getPluginDirectory(File rootDirectory) { + File payloadDirectory = new File(rootDirectory, "payload"); + return payloadDirectory; } - - public static void assertFileExistence(String filename, String id) - { - File f = new File(filename); - if ( !f.exists() ) - { - panic(filename+" supplied as "+id+" is no valid file"); - } + + /** + * Returns the package name the generated plugin uses. (e.g. + * org.roettig.foo). + * + * @param props + * @return + */ + private static String getPackageName(Properties props) { + return props.getProperty("pluginpackage"); } - - public static String makePluginName(String s) - { - int idx = s.lastIndexOf("."); - if(idx==-1) - return s; - return s.substring(idx+1); - } - - public static void main(String[] args) throws Exception - { - // read in properties for building the plugin - props = new Properties(); - props.load(new FileInputStream("plugin.properties")); - - // ... these are .. - - // the directory containing the payload (= ini-file,zip with binaries for each platform) - _payloaddir_ = props.getProperty("payloaddir"); - assertDefinition(_payloaddir_,"payloaddir"); - assertDirectoryExistence(_payloaddir_,"payloaddir"); - - // the name of the package (i.e. org.roettig.foo) - _pluginpackage_ = props.getProperty("pluginpackage"); - assertDefinition(_pluginpackage_,"pluginpackage"); - assertValidPackageName(_pluginpackage_,"pluginpackage"); - - _pluginname_ = props.getProperty("pluginname", makePluginName(_pluginpackage_)); - assertRestrictedAlphaNumeric(_pluginname_,"pluginname"); - - // the root node where to attach the generated nodes - _package_root_ = props.getProperty("package_root"); - assertDefinition(_package_root_,"package_root"); - - if( ! (_package_root_.equals("community")||_package_root_.equals("chemistry")) ) - panic("invalid package root given :"+_package_root_); - - _descriptordir_ = props.getProperty("descriptordir"); - - _iconpath_ = props.getProperty("icon"); - _useini_ = props.getProperty("useini","true"); - - // no descriptor directory supplied ... - if(_descriptordir_==null) - { - // .. extract tool descriptor information from executable - _executabledir_ = props.getProperty("executabledir"); - - if(_executabledir_==null) - panic("neither tool descriptors nor executables were supplied"); - - File exedir = new File(_executabledir_); - - if(!exedir.exists()||!exedir.isDirectory()) - panic("supplied executables directory does not exist"); - - generateDescriptors(props); - } - - _destdir_ = System.getProperty("java.io.tmpdir")+File.separator+"GENERIC_KNIME_NODES_PLUGINSRC"; - - // the name of the binary package is simply copied from the plugin name - _BINPACKNAME_ = _pluginpackage_; - _destsrcdir_ = _destdir_+File.separator+"src"; - _packagedir_ = _pluginpackage_.replace(".","/"); - _abspackagedir_ = _destsrcdir_+File.separator+_packagedir_; - _absnodedir_ = _abspackagedir_+String.format("%sknime%snodes",File.separator,File.separator); - - - createPackageDirectory(); - - pre(); - - installMimeTypes(); - - processDescriptors(); - - installIcon(); - - fillProperties(); - - post(); - - } - - public static void fillProperties() throws IOException - { - Properties p = new Properties(); - p.put("use_ini", props.getProperty("use_ini","true")); - p.put("ini_switch", props.getProperty("ini_switch","-ini")); - p.store(new FileOutputStream(_abspackagedir_+File.separator+"knime"+File.separator+"plugin.properties"), null); - } - - public static void installIcon() throws IOException - { - if(_iconpath_!=null) - { - Node node = plugindoc.selectSingleNode("/plugin/extension[@point='org.knime.product.splashExtension']"); - Element elem = (Element) node; - elem.addElement("splashExtension").addAttribute("icon", "icons/logo.png").addAttribute("id", "logo"); - - new File(_destdir_ +File.separator+"icons").mkdirs(); - Helper.copyFile(new File(_iconpath_), new File(_destdir_ +File.separator+"icons"+File.separator+"logo.png")); - } - + /** + * Checks whether a given package name is valid. + * + * @param packageName + * @param id + * @return true if package name is valid; false otherwise + */ + public static boolean isValidPackageName(String packageName) { + return packageName != null + && packageName + .matches("^([A-Za-z_]{1}[A-Za-z0-9_]*(\\.[A-Za-z_]{1}[A-Za-z0-9_]*)*)$"); } - public static void generateDescriptors(Properties props) throws Exception - { - String par_switch = props.getProperty("parswitch","-write_par"); - File bindir = new File(_executabledir_+File.separator+"bin"); - - if(!bindir.exists()||!bindir.isDirectory()) - { - panic("could not find bin directory with executables at executabledir: "+_executabledir_); - } - - String ttd_dir = System.getProperty("java.io.tmpdir")+File.separator+"GENERIC_KNIME_NODES_TTD"; - - try - { - File outdir = new File(ttd_dir); - outdir.mkdirs(); - outdir.deleteOnExit(); - } - catch(Exception e) - { - panic("could not create temporary directory "+ttd_dir); - } - - String[] exes = bindir.list(); - - if(exes.length==0) - { - panic("found no executables at "+bindir); - } - - for(String exe: exes) - { + /** + * Returns the plugin name. + * <p> + * If no configuration could be found, the name is created based on the + * given package name. e.g. org.roettig.foo will result in foo + * + * @param packageName + * @return + */ + public static String getPluginName(Properties props, String packageName) { + String pluginname = props.getProperty("pluginname"); + if (pluginname != null && !pluginname.isEmpty()) + return pluginname; + + int idx = packageName.lastIndexOf("."); + if (idx == -1) + return packageName; + return packageName.substring(idx + 1); + } + + /** + * Checks if the plugin name is valid. + * + * @param obj + * @param id + */ + public static boolean isPluginNameValid(String pluginName) { + return pluginName != null && pluginName.matches("^\\w+$"); + } + + /** + * Returns the path where the generated KNIME nodes will reside. e.g. + * <code>community/my_nodes</code> + * + * @param props + * @return + */ + private static String getNodeRepositoryRoot(Properties props) { + return props.getProperty("package_root"); + } + + /** + * Returns the directory where the Common Tool Descriptors (*.ctd) reside. + * + * @param props + * @return + */ + private static File getDescriptorsDirectory(File rootDirectory) { + File descriptorsDirectory = new File(rootDirectory, "descriptors"); + return descriptorsDirectory; + } + + /** + * Returns the directory where the tools to generate KNIME nodes from + * reside. + * <p> + * Notice: The tools must support the creation of ctd-files. + * + * @param props + * @return + */ + private static File getExecutablesDirectory(File rootDirectory) { + File exectuablesDirectory = new File(rootDirectory, "executables"); + return exectuablesDirectory; + } + + /** + * Creates a ctd file for each binary found in the given {@link File + * Directory} in a temporary directory by calling each binary with the given + * switch (e.g. <code>-ctd-write</code>). + * + * @param executablesDirectory + * @param ctdWriteSwitch + * @return the temporary directory in which the ctd files were created + * @throws IOException + * @throws ExecutionException + */ + public static File generateDescriptors(File executablesDirectory, + String ctdWriteSwitch) throws IOException, ExecutionException { + + File tempDirectory = new File(System.getProperty("java.io.tmpdir"), + "GKN-descriptors-" + Long.toString(System.nanoTime())); + tempDirectory.mkdirs(); + tempDirectory.deleteOnExit(); + + File binDirectory = new File(executablesDirectory, "bin"); + if (!binDirectory.isDirectory()) + throw new FileNotFoundException("The bin directory " + + binDirectory.getPath() + " is not valid."); + + String[] exes = new File(executablesDirectory, "bin").list(); + + if (exes.length == 0) + throw new FileNotFoundException( + "Could not find any executables in " + executablesDirectory); + + for (String exe : exes) { ToolRunner tr = new ToolRunner(); - File outfile = File.createTempFile("TTD",""); + File outfile = File.createTempFile("CTD", ""); outfile.deleteOnExit(); - - // FixMe: this is so *nix style, wont hurt on windows + + // FIXME: this is so *nix style, wont hurt on windows // but probably wont help either - tr.addEnvironmentEntry("LD_LIBRARY_PATH", _executabledir_+File.separator+"lib"); - - String cmd = _executabledir_+File.separator+"bin"+File.separator+exe+" "+par_switch+" "+outfile.getAbsolutePath(); - tr.run(cmd); - - if(tr.getReturnCode()==0) - { - Helper.copyFile(outfile,new File(ttd_dir+File.separator+outfile.getName())); - } - else - { - panic("could not execute tool : "+cmd); + tr.addEnvironmentEntry("LD_LIBRARY_PATH", new File( + executablesDirectory, "lib").getAbsolutePath()); + + String cmd = binDirectory.getAbsolutePath() + File.separator + exe + + " " + ctdWriteSwitch + " " + outfile.getAbsolutePath(); + try { + tr.run(cmd); + + if (tr.getReturnCode() != 0) { + Helper.copyFile(outfile, + new File(tempDirectory, outfile.getName())); + } else + throw new ExecutionException("Tool \"" + cmd + + "\" returned with " + tr.getReturnCode()); + } catch (Exception e) { + throw new ExecutionException("Could not execute tool: " + cmd, + e); } } - - _descriptordir_ = ttd_dir; - } - - private static void createPackageDirectory() - { - File packagedir = new File(_destsrcdir_+File.separator+_packagedir_); - Helper.deleteDirectory(packagedir); - packagedir.mkdirs(); - } - - public static void pre() throws DocumentException, IOException - { - Helper.copyStream(TemplateResources.class.getResourceAsStream("plugin.xml.template"),new File(_destdir_ + File.separator+"plugin.xml")); - - DOMDocumentFactory factory = new DOMDocumentFactory(); + + return tempDirectory; + } + + /** + * Returns the switch needed to make an executable output a ctd-file. + * + * @param props + * @return + */ + private static String getCtdWriteSwitch(Properties props) { + return props.getProperty("parswitch", "-write_par"); + } + + /** + * Returns the {@link File directory} where to put the plugin source in. + * + * @return + */ + private File getDestinationDirectory() { + return new File(System.getProperty("java.io.tmpdir"), + "GKN-pluginsource-" + Long.toString(System.nanoTime())); + } + + /** + * Creates a directory structure representing a package name. + * <p> + * e.g. <code>foo.bar</code> would result in the directory + * <code>foo/bar</code>. + * + * @param directory + * where to create the directory structure in + * @param packageName + * @return + */ + private static File createPackageDirectory(File directory, + String packageName) { + File packageDirectory = new File(directory, packageName.replace(".", + "/")); + Helper.deleteDirectory(packageDirectory); + packageDirectory.mkdirs(); + return packageDirectory; + } + + public static void fillProperties(Properties props, + File destinationFQNDirectory) throws IOException { + Properties p = new Properties(); + p.put("use_ini", props.getProperty("use_ini", "true")); + p.put("ini_switch", props.getProperty("ini_switch", "-ini")); + p.store(new FileOutputStream(destinationFQNDirectory + File.separator + + "knime" + File.separator + PLUGIN_PROPERTIES), null); + } + + // TODO + // public void installIcon() throws IOException { + // if (this._iconpath_ != null) { + // Node node = this.plugindoc + // .selectSingleNode("/plugin/extension[@point='org.knime.product.splashExtension']"); + // Element elem = (Element) node; + // + // elem.addElement("splashExtension") + // .addAttribute("icon", "icons/logo.png") + // .addAttribute("id", "logo"); + // + // new File(this._destdir_ + File.separator + "icons").mkdirs(); + // Helper.copyFile(new File(this._iconpath_), new File(this._destdir_ + // + File.separator + "icons" + File.separator + "logo.png")); + // } + // + // } + + /** + * Prepares a new copy of a template plugin.xml in the given {@link File + * directory} and returns its {@link Document} representation. + * + * @param destinationDirectory + * @return + * @throws DocumentException + * @throws IOException + */ + public static Document preparePluginXML(File destinationDirectory, + File destinationPluginXML) throws DocumentException, IOException { + Helper.copyStream(TemplateResources.class + .getResourceAsStream("plugin.xml.template"), + destinationPluginXML); + SAXReader reader = new SAXReader(); - reader.setDocumentFactory(factory); + reader.setDocumentFactory(new DOMDocumentFactory()); - plugindoc = reader.read(new FileInputStream(new File(_destdir_ + File.separator+"plugin.xml"))); - + return reader.read(new FileInputStream(destinationPluginXML)); } - - private static void installMimeTypes() throws DocumentException, IOException, JaxenException - { - assertFileExistence(_descriptordir_ + File.separator+"mimetypes.xml","mimetypes.xml"); - - + + /** + * TODO + * + * @param pluginXML + * @param destinationFQNNodeDirectory + * @param mimetypesXML + * @param packageName + * @throws DocumentException + * @throws IOException + * @throws JaxenException + */ + private static void installMimeTypes(Document pluginXML, + File destinationFQNNodeDirectory, File mimetypesXML, + String packageName) throws DocumentException, IOException, + JaxenException { + if (!mimetypesXML.isFile() || !mimetypesXML.canRead()) + throw new IOException("Invalid MIME types file: " + + mimetypesXML.getPath()); + SchemaValidator val = new SchemaValidator(); val.addSchema(SchemaProvider.class.getResourceAsStream("mimetypes.xsd")); - if(!val.validates(_descriptordir_ + File.separator+"mimetypes.xml")) - { - panic("supplied mimetypes.xml does not conform to schema "+val.getErrorReport()); - } - - + if (!val.validates(mimetypesXML.getPath())) + throw new DocumentException("Supplied \"" + mimetypesXML.getPath() + + "\" does not conform to schema " + val.getErrorReport()); + DOMDocumentFactory factory = new DOMDocumentFactory(); SAXReader reader = new SAXReader(); reader.setDocumentFactory(factory); - - Document doc = reader.read(new FileInputStream(new File(_descriptordir_ + File.separator+"mimetypes.xml"))); - - InputStream template = TemplateResources.class.getResourceAsStream("MimeFileCellFactory.template"); - - TemplateFiller tf = new TemplateFiller(); + + Document doc = reader.read(new FileInputStream(mimetypesXML)); + + InputStream template = TemplateResources.class + .getResourceAsStream("MimeFileCellFactory.template"); + + TemplateFiller tf = new TemplateFiller(); tf.read(template); - + String mimetypes_template = "\t\tmimetypes.add(new MIMEType(\"__EXT__\"));\n"; - String mimetypes_code = ""; - + String mimetypes_code = ""; + Set<String> mimetypes = new HashSet<String>(); - - Map<String,String> map = new HashMap<String,String>(); - map.put( "bp", "http://www.ball-project.org/mimetypes"); - - Dom4jXPath xpath = new Dom4jXPath( "//bp:mimetype"); - xpath.setNamespaceContext( new SimpleNamespaceContext(map)); + + Map<String, String> map = new HashMap<String, String>(); + map.put("bp", "http://www.ball-project.org/mimetypes"); // TODO + + Dom4jXPath xpath = new Dom4jXPath("//bp:mimetype"); + xpath.setNamespaceContext(new SimpleNamespaceContext(map)); @SuppressWarnings("unchecked") List<Node> nodes = xpath.selectNodes(doc); - - for(Node node: nodes) - { - Element elem = (Element) node; - - String name = elem.valueOf("@name"); - String ext = elem.valueOf("@ext"); - //String descr = elem.valueOf("@description"); - //String demangler = elem.valueOf("@demangler"); - String binary = elem.valueOf("@binary"); + + for (Node node : nodes) { + Element elem = (Element) node; + + String name = elem.valueOf("@name"); + String ext = elem.valueOf("@ext"); + // String descr = elem.valueOf("@description"); + // String demangler = elem.valueOf("@demangler"); + String binary = elem.valueOf("@binary"); binary = (binary.equals("") ? "false" : binary); - - logger.info("read mime type "+name); - - if(mimetypes.contains(name)) - { - warn("skipping duplicate mime type "+name); + + logger.info("read mime type " + name); + + if (mimetypes.contains(name)) { + logger.log(Level.WARNING, "skipping duplicate mime type " + + name); } - - //createMimeTypeLoader(name, ext); - - //String clazz = createMimeCell(name, ext); - //createMimeValue(name); - - ext2type.put(ext.toLowerCase(),name); - //ext2clazz.put(ext.toLowerCase(),clazz); - - String s4 = mimetypes_template.replace("__EXT__", ext.toLowerCase()); + + // createMimeTypeLoader(name, ext); + + // String clazz = createMimeCell(name, ext); + // createMimeValue(name); + + // ext2clazz.put(ext.toLowerCase(),clazz); + + String s4 = mimetypes_template + .replace("__EXT__", ext.toLowerCase()); mimetypes_code += s4; } - + tf.replace("__MIMETYPES__", mimetypes_code); - tf.replace("__BASE__", _pluginpackage_); - tf.write(_absnodedir_ + String.format("%smimetypes%sMimeFileCellFactory.java",File.separator,File.separator)); + tf.replace("__BASE__", packageName); + tf.write(new File(destinationFQNNodeDirectory, "mimetypes" + + File.separator + "MimeFileCellFactory.java")); template.close(); - - } - - private static void processDescriptors() throws Exception - { - File files[] = (new File(_descriptordir_)).listFiles(); - - for (File f : files) - { - String filename = f.getName(); - - if (filename.endsWith(".ctd")) - { - logger.info("start processing node "+f); - processNode(filename, f); + } + + private static void processDescriptors(Set<String> node_names, + Set<String> ext_tools, Document pluginXML, + File descriptorDirectory, String nodeRepositoryRoot, + String pluginName, File destinationFQNNodeDirectory, + String packageName) throws IOException, DuplicateNodeNameException, + InvalidNodeNameException, CTDNodeConfigurationReaderException, + UnknownMimeTypeException { + Set<String> categories = new HashSet<String>(); + for (File file : descriptorDirectory.listFiles()) { + if (file.getName().endsWith(".ctd")) { + logger.info("start processing node " + file); + processNode(pluginXML, file, node_names, ext_tools, + nodeRepositoryRoot, pluginName, + destinationFQNNodeDirectory, categories, packageName); } } } - - private static Set<String> node_names = new HashSet<String>(); - - public static boolean checkNodeName(String name) - { - if(!name.matches("[[A-Z]|[a-z]][[0-9]|[A-Z]|[a-z]]+")) - return false; - return true; - } - - public static String fixNodeName(String name) - { - logger.info("trying to fix node class name "+name); - name = name.replace(".", ""); - name = name.replace("-", ""); - name = name.replace("_", ""); - name = name.replace("#", ""); - name = name.replace("+", ""); - name = name.replace("$", ""); - name = name.replace(":", ""); - logger.info("fixed node name "+name); - return name; - } - - public static String combine (String path1, String path2) - { - File file1 = new File(path1); - File file2 = new File(file1, path2); - return file2.getPath(); - } - - public static void processNode(String name, File descriptor) throws Exception - { - - logger.info("## processing Node "+name); - + + public static void processNode(Document pluginXML, File ctdFile, + Set<String> node_names, Set<String> ext_tools, + String nodeRepositoryRoot, String pluginName, + File destinationFQNNodeDirectory, Set<String> categories, + String packageName) throws IOException, DuplicateNodeNameException, + InvalidNodeNameException, CTDNodeConfigurationReaderException, + UnknownMimeTypeException { + + logger.info("## processing Node " + ctdFile.getName()); + CTDNodeConfigurationReader reader = new CTDNodeConfigurationReader(); - try - { - config = reader.read(new FileInputStream(descriptor)); - } - catch(Exception e) - { - panic(e.getMessage()); - } - + NodeConfiguration config = reader.read(new FileInputStream(ctdFile)); + String nodeName = config.getName(); - + String oldNodeName = null; - - if(!checkNodeName(nodeName)) - { + + if (!KNIMENode.checkNodeName(nodeName)) { oldNodeName = nodeName; - + // we try to fix the nodename - nodeName = fixNodeName(nodeName); - - if(!checkNodeName(nodeName)) - panic("NodeName with invalid name detected "+nodeName); - + nodeName = KNIMENode.fixNodeName(nodeName); + + if (!KNIMENode.checkNodeName(nodeName)) + throw new InvalidNodeNameException("The node name \"" + + nodeName + "\" is invalid."); } - - if(oldNodeName==null) - { - if(node_names.contains(nodeName)) - { - warn("duplicate tool detected "+nodeName); - return; - } - - if(config.getStatus().equals("internal")) + + if (oldNodeName == null) { + if (node_names.contains(nodeName)) + throw new DuplicateNodeNameException(nodeName); + + if (config.getStatus().equals("internal")) { node_names.add(nodeName); - else + } else { ext_tools.add(nodeName); - - } - else - { - if(node_names.contains(oldNodeName)) - { - warn("duplicate tool detected "+oldNodeName); - return; } - - if(config.getStatus().equals("internal")) + } else { + if (node_names.contains(oldNodeName)) + throw new DuplicateNodeNameException(nodeName); + + if (config.getStatus().equals("internal")) { node_names.add(oldNodeName); - else + } else { ext_tools.add(nodeName); + } } - - cur_cat = combine("/"+_package_root_+"/"+_pluginname_,config.getCategory()); - - cur_path = getPathPrefix(cur_cat); - - - File nodeConfigDir = new File(_absnodedir_ + File.separator + nodeName + File.separator+"config"); + + String cur_cat = new File("/" + nodeRepositoryRoot + "/" + pluginName, + config.getCategory()).getPath(); + + File nodeConfigDir = new File(destinationFQNNodeDirectory + + File.separator + nodeName + File.separator + "config"); nodeConfigDir.mkdirs(); - Helper.copyFile(descriptor, new File(_absnodedir_ + File.separator + nodeName + File.separator + "config"+File.separator+"config.xml")); - - registerPath(cur_cat); - - createFactory(nodeName); - - createDialog(nodeName); - - createView(nodeName); - - createModel(nodeName); - - fillMimeTypes(); - - createXMLDescriptor(nodeName); - - writeModel(nodeName); - - registerNode( _pluginpackage_ + ".knime.nodes." + nodeName + "." + nodeName + "NodeFactory", cur_cat); - - } - - /** - * returns the prefix path of the given path. - * - * /foo/bar/baz ---> /foo/bar/ - * - * @param path - * @return - */ - public static String getPathPrefix(String path) - { - File pth = new File(path); - return pth.getParent(); - } - - /** - * returns all prefix paths of a given path. - * - * /foo/bar/baz --> [/foo/bar/,/foo/,/] - * - * @param path - * @return - */ - public static List<String> getPathPrefixes(String path) - { - List<String> ret = new ArrayList<String>(); - File pth = new File(path); - ret.add(path); - while(pth.getParent()!=null) - { - ret.add(pth.getParent()); - pth = pth.getParentFile(); - } - return ret; + Helper.copyFile(ctdFile, new File(destinationFQNNodeDirectory + + File.separator + nodeName + File.separator + "config" + + File.separator + "config.xml")); + + registerPath(cur_cat, pluginXML, categories); + + createFactory(nodeName, destinationFQNNodeDirectory, packageName); + + createDialog(nodeName, destinationFQNNodeDirectory, packageName); + + createView(nodeName, destinationFQNNodeDirectory, packageName); + + TemplateFiller curmodel_tf = createModel(nodeName, + destinationFQNNodeDirectory, packageName); + + fillMimeTypes(config, curmodel_tf); + + TemplateFiller nodeFactoryXML = createXMLDescriptor(nodeName, config); + nodeFactoryXML.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + + nodeName + "NodeFactory.xml"); + + writeModel(nodeName, destinationFQNNodeDirectory, curmodel_tf); + + registerNode(packageName + ".knime.nodes." + nodeName + "." + nodeName + + "NodeFactory", cur_cat, pluginXML, categories); + } - - /** - * returns the path suffix for a given path. - * - * /foo/bar/baz --> baz - * - * @param path - * @return - */ - public static String getPathSuffix(String path) - { - File pth = new File(path); - return pth.getName(); - } - - public static Set<String> categories = new HashSet<String>(); - - public static void registerPath(String path) - { - List<String> prefixes = getPathPrefixes(path); - - for(String prefix: prefixes) - { - registerPathPrefix(prefix); + + public static void registerPath(String path, Document pluginXML, + Set<String> categories) { + List<String> prefixes = Utils.getPathPrefixes(path); + for (String prefix : prefixes) { + registerPathPrefix(prefix, pluginXML, categories); } } - - public static void registerPathPrefix(String path) - { + + public static void registerPathPrefix(String path, Document pluginXML, + Set<String> categories) { // do not register any top level or root path - if(path.equals("/")||new File(path).getParent().equals("/")) + if (path.equals("/") || new File(path).getParent().equals("/")) return; - - if(categories.contains(path)) + + if (categories.contains(path)) return; - + logger.info("registering path prefix " + path); - + categories.add(path); - - String cat_name = getPathSuffix(path); - String path_prefix = getPathPrefix(path); - - Node node = plugindoc.selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.categories']"); - + + String cat_name = Utils.getPathSuffix(path); + String path_prefix = Utils.getPathPrefix(path); + + Node node = pluginXML + .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.categories']"); + Element elem = (Element) node; - logger.info("name="+cat_name); - - elem.addElement("category").addAttribute("description", path).addAttribute("icon", "icons/category.png") - .addAttribute("path", path_prefix).addAttribute("name", cat_name).addAttribute("level-id", cat_name); - } - - public static void createFactory(String nodeName) throws IOException - { - InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeFactory.template"); + logger.info("name=" + cat_name); + + elem.addElement("category").addAttribute("description", path) + .addAttribute("icon", "icons/category.png") + .addAttribute("path", path_prefix) + .addAttribute("name", cat_name) + .addAttribute("level-id", cat_name); + } + + public static void createFactory(String nodeName, + File destinationFQNNodeDirectory, String packageName) + throws IOException { + InputStream template = NodeGenerator.class + .getResourceAsStream("templates/NodeFactory.template"); TemplateFiller tf = new TemplateFiller(); tf.read(template); tf.replace("__NODENAME__", nodeName); - tf.replace("__BASE__", _pluginpackage_); - tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeFactory.java"); + tf.replace("__BASE__", packageName); + tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + nodeName + + "NodeFactory.java"); } - public static void createDialog(String nodeName) throws IOException - { - InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeDialog.template"); + public static void createDialog(String nodeName, + File destinationFQNNodeDirectory, String packageName) + throws IOException { + InputStream template = NodeGenerator.class + .getResourceAsStream("templates/NodeDialog.template"); TemplateFiller tf = new TemplateFiller(); tf.read(template); tf.replace("__NODENAME__", nodeName); - tf.replace("__BASE__", _pluginpackage_); - tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeDialog.java"); + tf.replace("__BASE__", packageName); + tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + nodeName + + "NodeDialog.java"); } - public static String join(Collection<String> col) - { + public static String join(Collection<String> col) { String ret = ""; - for(String s: col) - { - ret += s+","; + for (String s : col) { + ret += s + ","; } - ret = ret.substring(0,ret.length()-1); + ret = ret.substring(0, ret.length() - 1); return ret; } - - public static void createXMLDescriptor(String nodeName) throws IOException - { + + public static TemplateFiller createXMLDescriptor(String nodeName, + NodeConfiguration config) throws IOException { // ports String ip = "<inPort index=\"__IDX__\" name=\"__PORTDESCR__\"><![CDATA[__PORTDESCR__ [__MIMETYPE____OPT__]]]></inPort>"; String inports = ""; int idx = 0; - for (Port port : config.getInputPorts()) - { + for (Port port : config.getInputPorts()) { String ipp = ip; ipp = ip.replace("__PORTNAME__", port.getName()); ipp = ipp.replace("__PORTDESCR__", port.getDescription()); ipp = ipp.replace("__IDX__", String.format("%d", idx++)); - + // fix me - //ipp = ipp.replace("__MIMETYPE__", port.getMimeTypes().get(0).getExt()); + // ipp = ipp.replace("__MIMETYPE__", + // port.getMimeTypes().get(0).getExt()); List<String> mts = new ArrayList<String>(); - for(MIMEtype mt: port.getMimeTypes()) - { + for (MIMEtype mt : port.getMimeTypes()) { mts.add(mt.getExt()); } ipp = ipp.replace("__MIMETYPE__", join(mts)); - - ipp = ipp.replace("__OPT__", (port.isOptional()?",opt.":"")); + + ipp = ipp.replace("__OPT__", (port.isOptional() ? ",opt." : "")); inports += ipp + "\n"; } String op = "<outPort index=\"__IDX__\" name=\"__PORTDESCR__ [__MIMETYPE__]\"><![CDATA[__PORTDESCR__ [__MIMETYPE__]]]></outPort>"; String outports = ""; idx = 0; - for (Port port : config.getOutputPorts()) - { + for (Port port : config.getOutputPorts()) { String opp = op; opp = op.replace("__PORTNAME__", port.getName()); opp = opp.replace("__PORTDESCR__", port.getDescription()); opp = opp.replace("__IDX__", String.format("%d", idx++)); - + // fix me - opp = opp.replace("__MIMETYPE__", port.getMimeTypes().get(0).getExt()); - + opp = opp.replace("__MIMETYPE__", port.getMimeTypes().get(0) + .getExt()); + outports += opp + "\n"; } StringBuffer buf = new StringBuffer(); - for (Parameter<?> p : config.getParameters()) - { - buf.append("\t\t<option name=\"" + p.getKey() + "\"><![CDATA[" + p.getDescription() + "]]></option>\n"); + for (Parameter<?> p : config.getParameters()) { + buf.append("\t\t<option name=\"" + p.getKey() + "\"><![CDATA[" + + p.getDescription() + "]]></option>\n"); } String opts = buf.toString(); - InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeXMLDescriptor.template"); + InputStream template = NodeGenerator.class + .getResourceAsStream("templates/NodeXMLDescriptor.template"); TemplateFiller tf = new TemplateFiller(); tf.read(template); @@ -710,288 +769,273 @@ public static void createXMLDescriptor(String nodeName) throws IOException tf.replace("__DESCRIPTION__", config.getDescription()); String pp = prettyPrint(config.getManual()); tf.replace("__MANUAL__", pp); - if(!config.getDocUrl().equals("")) - { - String ahref = "<a href=\""+config.getDocUrl()+"\">Web Documentation for "+nodeName+"</a>"; - tf.replace("__DOCLINK__", ahref); - } - else - { + if (!config.getDocUrl().equals("")) { + String ahref = "<a href=\"" + config.getDocUrl() + + "\">Web Documentation for " + nodeName + "</a>"; + tf.replace("__DOCLINK__", ahref); + } else { tf.replace("__DOCLINK__", ""); } - tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeFactory.xml"); - + return tf; } - private static String prettyPrint(String manual) - { - if(manual.equals("")) + private static String prettyPrint(String manual) { + if (manual.equals("")) return ""; StringBuffer sb = new StringBuffer(); String[] toks = manual.split("\\n"); - for(String tok: toks) - { - sb.append("<p><![CDATA["+tok+"]]></p>"); + for (String tok : toks) { + sb.append("<p><![CDATA[" + tok + "]]></p>"); } return sb.toString(); } - public static void createView(String nodeName) throws IOException - { - InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeView.template"); + public static void createView(String nodeName, + File destinationFQNNodeDirectory, String packageName) + throws IOException { + InputStream template = NodeGenerator.class + .getResourceAsStream("templates/NodeView.template"); TemplateFiller tf = new TemplateFiller(); tf.read(template); tf.replace("__NODENAME__", nodeName); - tf.replace("__BASE__", _pluginpackage_); - tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeView.java"); + tf.replace("__BASE__", packageName); + tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + nodeName + + "NodeView.java"); } - private static TemplateFiller curmodel_tf = null; - - public static void createModel(String nodeName) throws IOException - { - InputStream template = NodeGenerator.class.getResourceAsStream("templates/NodeModel.template"); - curmodel_tf = new TemplateFiller(); + public static TemplateFiller createModel(String nodeName, + File destinationFQNNodeDirectory, String packageName) + throws IOException { + InputStream template = NodeGenerator.class + .getResourceAsStream("templates/NodeModel.template"); + TemplateFiller curmodel_tf = new TemplateFiller(); curmodel_tf.read(template); curmodel_tf.replace("__NODENAME__", nodeName); - curmodel_tf.replace("__BASE__", _pluginpackage_); - curmodel_tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeModel.java"); + curmodel_tf.replace("__BASE__", packageName); + curmodel_tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + + nodeName + "NodeModel.java"); + return curmodel_tf; } - protected static void writeModel(String nodeName) throws IOException - { - curmodel_tf.write(_absnodedir_ + "/" + nodeName + "/" + nodeName + "NodeModel.java"); + protected static void writeModel(String nodeName, + File destinationFQNNodeDirectory, TemplateFiller curmodel_tf) + throws IOException { + curmodel_tf.write(destinationFQNNodeDirectory + "/" + nodeName + "/" + + nodeName + "NodeModel.java"); } - - - public static Map<String,String> ext2type = new HashMap<String,String>(); - - private static void fillMimeTypes() throws IOException - { + + private static void fillMimeTypes(NodeConfiguration config, + TemplateFiller curmodel_tf) throws UnknownMimeTypeException { String clazzez = ""; - for (Port port : config.getInputPorts()) - { + for (Port port : config.getInputPorts()) { String tmp = "{"; - for(MIMEtype type: port.getMimeTypes()) - { + for (MIMEtype type : port.getMimeTypes()) { String ext = type.getExt().toLowerCase(); - if(ext==null) - { - panic("unknown mime type : |"+type.getExt()+"|"); - } + if (ext == null) + throw new UnknownMimeTypeException(type); /* - if(port.isMultiFile()) - tmp += "DataType.getType(ListCell.class, DataType.getType(" + ext + "FileCell.class)),"; - else - tmp += "DataType.getType(" + ext + "FileCell.class),"; - */ - tmp += "new MIMEType(\""+ext+"\"),"; + * if(port.isMultiFile()) tmp += + * "DataType.getType(ListCell.class, DataType.getType(" + ext + + * "FileCell.class)),"; else tmp += "DataType.getType(" + ext + + * "FileCell.class),"; + */ + tmp += "new MIMEType(\"" + ext + "\"),"; } - tmp = tmp.substring(0,tmp.length()-1); - tmp+="},"; + tmp = tmp.substring(0, tmp.length() - 1); + tmp += "},"; clazzez += tmp; } - - if(!clazzez.equals("")) - clazzez = clazzez.substring(0,clazzez.length()-1); - + + if (!clazzez.equals("")) { + clazzez = clazzez.substring(0, clazzez.length() - 1); + } + clazzez += "}"; - createInClazzezModel(clazzez); - + createInClazzezModel(clazzez, curmodel_tf); + clazzez = ""; - for (Port port : config.getOutputPorts()) - { + for (Port port : config.getOutputPorts()) { String tmp = "{"; - for(MIMEtype type: port.getMimeTypes()) - { + for (MIMEtype type : port.getMimeTypes()) { String ext = type.getExt().toLowerCase(); - if(ext==null) - { - panic("unknown mime type : |"+type.getExt()+"|"); - } + if (ext == null) + throw new UnknownMimeTypeException(type); /* - if(port.isMultiFile()) - tmp += "DataType.getType(ListCell.class, DataType.getType(" + ext + "FileCell.class)),"; - else - tmp += "DataType.getType(" + ext + "FileCell.class),"; - */ - tmp += "new MIMEType(\""+ext+"\"),"; + * if(port.isMultiFile()) tmp += + * "DataType.getType(ListCell.class, DataType.getType(" + ext + + * "FileCell.class)),"; else tmp += "DataType.getType(" + ext + + * "FileCell.class),"; + */ + tmp += "new MIMEType(\"" + ext + "\"),"; } - tmp = tmp.substring(0,tmp.length()-1); - tmp+="},"; + tmp = tmp.substring(0, tmp.length() - 1); + tmp += "},"; clazzez += tmp; - } - - if(!clazzez.equals("")) - clazzez = clazzez.substring(0,clazzez.length()-1); - + } + + if (!clazzez.equals("")) { + clazzez = clazzez.substring(0, clazzez.length() - 1); + } + clazzez += "}"; - - createOutClazzezModel(clazzez); - } - - public static void makeMimeFileCellFactory() - { - - - } - - public static void createInClazzezModel(String clazzez) throws IOException - { - if (clazzez.equals("")) + + createOutClazzezModel(clazzez, curmodel_tf); + } + + public static void createInClazzezModel(String clazzez, + TemplateFiller curmodel_tf) { + if (clazzez.equals("")) { clazzez = "null"; - else + } else { clazzez = clazzez.substring(0, clazzez.length() - 1); + } curmodel_tf.replace("__INCLAZZEZ__", clazzez); } - public static void createOutClazzezModel(String clazzez) throws IOException - { - if (clazzez.equals("")) + public static void createOutClazzezModel(String clazzez, + TemplateFiller curmodel_tf) { + if (clazzez.equals("")) { clazzez = "null"; - else + } else { clazzez = clazzez.substring(0, clazzez.length() - 1); + } curmodel_tf.replace("__OUTCLAZZEZ__", clazzez); } - - public static void registerNode(String clazz, String path) - { + + public static void registerNode(String clazz, String path, + Document pluginXML, Set<String> categories) { logger.info("registering Node " + clazz); - registerPath(path); - - Node node = plugindoc.selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.nodes']"); - Element elem = (Element) node; + registerPath(path, pluginXML, categories); + Node node = pluginXML + .selectSingleNode("/plugin/extension[@point='org.knime.workbench.repository.nodes']"); + Element elem = (Element) node; - elem.addElement("node").addAttribute("factory-class", clazz).addAttribute("id", clazz).addAttribute("category-path", path); + elem.addElement("node").addAttribute("factory-class", clazz) + .addAttribute("id", clazz).addAttribute("category-path", path); } - - public static void post() throws IOException - { + + public static void post(Document pluginXML, File destinationPluginXML, + String packageName, File destinationFQNDirectory, + File destinationFQNNodeDirectory, File payloadDirectory, + Set<String> node_names, Set<String> ext_tools) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); - - XMLWriter writer = new XMLWriter( new FileWriter(_destdir_ + File.separator+"plugin.xml") , format ); - writer.write( plugindoc ); + XMLWriter writer = new XMLWriter(new FileWriter(destinationPluginXML), + format); + writer.write(pluginXML); writer.close(); - + // prepare binary resources - InputStream template = TemplateResources.class.getResourceAsStream("BinaryResources.template"); - curmodel_tf = new TemplateFiller(); + InputStream template = TemplateResources.class + .getResourceAsStream("BinaryResources.template"); + TemplateFiller curmodel_tf = new TemplateFiller(); curmodel_tf.read(template); - curmodel_tf.replace("__BASE__", _pluginpackage_); - curmodel_tf.replace("__BINPACKNAME__", _BINPACKNAME_); - curmodel_tf.write(_absnodedir_ + "/binres/BinaryResources.java"); + curmodel_tf.replace("__BASE__", packageName); + curmodel_tf.replace("__BINPACKNAME__", packageName); + curmodel_tf.write(new File(destinationFQNNodeDirectory, + "/binres/BinaryResources.java")); template.close(); - - String pathsep = System.getProperty("file.separator"); - + // - String[] binFiles = new File(_payloaddir_).list(); - for(String filename: binFiles) - { + String[] binFiles = payloadDirectory.list(); + for (String filename : binFiles) { // do not copy directories - if(new File(_payloaddir_+pathsep+filename).isDirectory()) + if (new File(payloadDirectory, filename).isDirectory()) { continue; - + } + // only copy zip and ini files - if(filename.toLowerCase().endsWith("zip")) - { - Helper.copyFile(new File(_payloaddir_+pathsep+filename),new File(_absnodedir_ +pathsep+"binres"+pathsep+filename)); - verifyZip(_absnodedir_ +pathsep+"binres"+pathsep+filename); + if (filename.toLowerCase().endsWith("zip")) { + Helper.copyFile(new File(payloadDirectory, filename), new File( + destinationFQNNodeDirectory, "binres" + + File.pathSeparator + filename)); + // TODO + // verifyZip(destinationFQNNodeDirectory + pathsep + "binres" + // + pathsep + filename); } - if(filename.toLowerCase().endsWith("ini")) - { - Helper.copyFile(new File(_payloaddir_+pathsep+filename),new File(_absnodedir_ +pathsep+"binres"+pathsep+filename)); + if (filename.toLowerCase().endsWith("ini")) { + Helper.copyFile(new File(payloadDirectory, filename), new File( + destinationFQNNodeDirectory, "binres" + + File.pathSeparator + filename)); } } - - template = TemplateResources.class.getResourceAsStream("PluginActivator.template"); + + template = TemplateResources.class + .getResourceAsStream("PluginActivator.template"); TemplateFiller tf = new TemplateFiller(); tf.read(template); - tf.replace("__BASE__", _pluginpackage_); - tf.replace("__NAME__", _pluginpackage_); - tf.write(_abspackagedir_ + File.separator+"knime"+File.separator+"PluginActivator.java"); + tf.replace("__BASE__", packageName); + tf.replace("__NAME__", packageName); + tf.write(destinationFQNDirectory + File.separator + "knime" + + File.separator + "PluginActivator.java"); template.close(); - - FileWriter ini_writer = new FileWriter(_abspackagedir_ + File.separator+"knime"+File.separator+"ExternalTools.dat"); - for(String ext_tool: ext_tools) - ini_writer.write(ext_tool+"\n"); - ini_writer.close(); - - ini_writer = new FileWriter(_abspackagedir_ + File.separator+"knime"+File.separator+"InternalTools.dat"); - for(String int_tool: node_names) - ini_writer.write(int_tool+"\n"); - ini_writer.close(); - } - - public static void verifyZip(String filename) - { - boolean ok = false; - - Set<String> found_exes = new HashSet<String>(); - - try - { - ZipInputStream zin = new ZipInputStream(new FileInputStream(filename)); - ZipEntry ze = null; - - while ((ze = zin.getNextEntry()) != null) - { - if (ze.isDirectory()) - { - // we need a bin directory at the top level - if(ze.getName().equals("bin/") || ze.getName().equals("bin")) - { - ok = true; - } - - } - else - { - File f = new File(ze.getName()); - if((f.getParent()!=null)&&f.getParent().equals("bin")) - { - found_exes.add(f.getName()); - } - } - } - } - catch(Exception e) - { - e.printStackTrace(); - } - - if(!ok) - { - panic("binary archive has no toplevel bin directory : "+filename); + + FileWriter ini_writer = new FileWriter(destinationFQNDirectory + + File.separator + "knime" + File.separator + + "ExternalTools.dat"); + for (String ext_tool : ext_tools) { + ini_writer.write(ext_tool + "\n"); } - - for(String nodename: node_names) - { - boolean found = false; - if(found_exes.contains(nodename)||found_exes.contains(nodename+".bin")||found_exes.contains(nodename+".exe")) - { - found = true; - } - if(!found) - { - panic("binary archive has no executable in bin directory for node : "+nodename); - } + ini_writer.close(); + + ini_writer = new FileWriter(destinationFQNDirectory + File.separator + + "knime" + File.separator + "InternalTools.dat"); + for (String int_tool : node_names) { + ini_writer.write(int_tool + "\n"); } + ini_writer.close(); } - - public static void panic(String message) - { - logger.severe("PANIC - "+message+" - EXITING"); - System.exit(1); - } - - public static void warn(String message) - { - logger.warning(message); - } + + // TODO + // public static void verifyZip(String filename) { + // boolean ok = false; + // + // Set<String> found_exes = new HashSet<String>(); + // + // try { + // ZipInputStream zin = new ZipInputStream(new FileInputStream( + // filename)); + // ZipEntry ze = null; + // + // while ((ze = zin.getNextEntry()) != null) { + // if (ze.isDirectory()) { + // // we need a bin directory at the top level + // if (ze.getName().equals("bin/") + // || ze.getName().equals("bin")) { + // ok = true; + // } + // + // } else { + // File f = new File(ze.getName()); + // if ((f.getParent() != null) && f.getParent().equals("bin")) { + // found_exes.add(f.getName()); + // } + // } + // } + // } catch (Exception e) { + // e.printStackTrace(); + // } + // + // if (!ok) { + // this.panic("binary archive has no toplevel bin directory : " + // + filename); + // } + // + // for (String nodename : this.node_names) { + // boolean found = false; + // if (found_exes.contains(nodename) + // || found_exes.contains(nodename + ".bin") + // || found_exes.contains(nodename + ".exe")) { + // found = true; + // } + // if (!found) { + // this.panic("binary archive has no executable in bin directory for node : " + // + nodename); + // } + // } + // } } diff --git a/src/org/ballproject/knime/nodegeneration/Utils.java b/src/org/ballproject/knime/nodegeneration/Utils.java new file mode 100644 index 00000000..18f30acc --- /dev/null +++ b/src/org/ballproject/knime/nodegeneration/Utils.java @@ -0,0 +1,52 @@ +package org.ballproject.knime.nodegeneration; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class Utils { + /** + * returns all prefix paths of a given path. + * + * /foo/bar/baz --> [/foo/bar/,/foo/,/] + * + * @param path + * @return + */ + public static List<String> getPathPrefixes(String path) { + List<String> ret = new ArrayList<String>(); + File pth = new File(path); + ret.add(path); + while (pth.getParent() != null) { + ret.add(pth.getParent()); + pth = pth.getParentFile(); + } + return ret; + } + + /** + * returns the prefix path of the given path. + * + * /foo/bar/baz ---> /foo/bar/ + * + * @param path + * @return + */ + public static String getPathPrefix(String path) { + File pth = new File(path); + return pth.getParent(); + } + + /** + * returns the path suffix for a given path. + * + * /foo/bar/baz --> baz + * + * @param path + * @return + */ + public static String getPathSuffix(String path) { + File pth = new File(path); + return pth.getName(); + } +} diff --git a/src/org/ballproject/knime/nodegeneration/exceptions/DuplicateNodeNameException.java b/src/org/ballproject/knime/nodegeneration/exceptions/DuplicateNodeNameException.java new file mode 100644 index 00000000..7e1a5dcc --- /dev/null +++ b/src/org/ballproject/knime/nodegeneration/exceptions/DuplicateNodeNameException.java @@ -0,0 +1,10 @@ +package org.ballproject.knime.nodegeneration.exceptions; + +public class DuplicateNodeNameException extends Exception { + + private static final long serialVersionUID = 998799239240695103L; + + public DuplicateNodeNameException(String nodeName) { + super("Duplicate node name \"" + nodeName + "\" detected."); + } +} diff --git a/src/org/ballproject/knime/nodegeneration/exceptions/InvalidNodeNameException.java b/src/org/ballproject/knime/nodegeneration/exceptions/InvalidNodeNameException.java new file mode 100644 index 00000000..ce43462a --- /dev/null +++ b/src/org/ballproject/knime/nodegeneration/exceptions/InvalidNodeNameException.java @@ -0,0 +1,11 @@ +package org.ballproject.knime.nodegeneration.exceptions; + +public class InvalidNodeNameException extends Exception { + + private static final long serialVersionUID = -5097765649425062813L; + + public InvalidNodeNameException(String description) { + super(description); + } + +} diff --git a/src/org/ballproject/knime/nodegeneration/exceptions/UnknownMimeTypeException.java b/src/org/ballproject/knime/nodegeneration/exceptions/UnknownMimeTypeException.java new file mode 100644 index 00000000..f35b3186 --- /dev/null +++ b/src/org/ballproject/knime/nodegeneration/exceptions/UnknownMimeTypeException.java @@ -0,0 +1,12 @@ +package org.ballproject.knime.nodegeneration.exceptions; + +import org.ballproject.knime.base.mime.MIMEtype; + +public class UnknownMimeTypeException extends Exception { + + private static final long serialVersionUID = 598884824362988075L; + + public UnknownMimeTypeException(MIMEtype type) { + super("Unknown MIME type: " + type.getExt()); + } +}
cff8f47eb7a1ad17442ec0d3c9bb596d29873faf
camel
CAMEL-1338: Added basic operator support for- simple language - end users is confused its not working
a
https://github.com/apache/camel
diff --git a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java index 18ad5f6c5b6dd..dc10bb91e3b4e 100644 --- a/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java +++ b/camel-core/src/main/java/org/apache/camel/builder/ExpressionBuilder.java @@ -289,6 +289,22 @@ public String toString() { }; } + /** + * Returns the expression for the exchanges inbound message body type + */ + public static Expression bodyType() { + return new ExpressionAdapter() { + public Object evaluate(Exchange exchange) { + return exchange.getIn().getBody().getClass(); + } + + @Override + public String toString() { + return "bodyType"; + } + }; + } + /** * Returns the expression for the exchanges inbound message body converted * to the given type @@ -444,6 +460,23 @@ public String toString() { }; } + /** + * Returns an expression which converts the given expression to the given type the type + * expression is evaluted to + */ + public static Expression convertTo(final Expression expression, final Expression type) { + return new ExpressionAdapter() { + public Object evaluate(Exchange exchange) { + return expression.evaluate(exchange, type.evaluate(exchange).getClass()); + } + + @Override + public String toString() { + return "" + expression + ".convertTo(" + type + ")"; + } + }; + } + /** * Returns a tokenize expression which will tokenize the string with the * given token diff --git a/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java b/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java index 96b3bda6ef116..7fbad60098181 100644 --- a/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java +++ b/camel-core/src/main/java/org/apache/camel/language/bean/BeanLanguage.java @@ -82,13 +82,20 @@ public Predicate createPredicate(String expression) { public Expression createExpression(String expression) { ObjectHelper.notNull(expression, "expression"); - int idx = expression.lastIndexOf('.'); String beanName = expression; String method = null; + + // we support both the .method name and the ?method= syntax + // as the ?method= syntax is very common for the bean component + int idx = expression.lastIndexOf('.'); if (idx > 0) { beanName = expression.substring(0, idx); method = expression.substring(idx + 1); + } else if (expression.contains("?method=")) { + beanName = ObjectHelper.before(expression, "?"); + method = ObjectHelper.after(expression, "?method="); } + return new BeanExpression(beanName, method); } diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLangaugeOperator.java b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLangaugeOperator.java new file mode 100644 index 0000000000000..5bb7b7af07410 --- /dev/null +++ b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLangaugeOperator.java @@ -0,0 +1,72 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.language.simple; + +/** + * Operators supported by simple language + * <ul> + * <li>EQ : ==</li> + * <li>GT : ></li> + * <li>GTE : >=</li> + * <li>LT : <</li> + * <li>LTE : <=</li> + * <li>NOT : !=</li> + * </ul> + */ +public enum SimpleLangaugeOperator { + + EQ, GT, GTE, LT, LTE, NOT; + + public static SimpleLangaugeOperator asOperator(String text) { + if ("==".equals(text)) { + return EQ; + } else if (">".equals(text)) { + return GT; + } else if (">=".equals(text)) { + return GTE; + } else if ("<".equals(text)) { + return LT; + } else if ("<=".equals(text)) { + return LTE; + } else if ("!=".equals(text)) { + return NOT; + } + throw new IllegalArgumentException("Operator not supported: " + text); + } + + public String getOperatorText(SimpleLangaugeOperator operator) { + if (operator == EQ) { + return "=="; + } else if (operator == GT) { + return ">"; + } else if (operator == GTE) { + return ">="; + } else if (operator == LT) { + return "<"; + } else if (operator == LTE) { + return "<="; + } else if (operator == NOT) { + return "!="; + } + return ""; + } + + @Override + public String toString() { + return getOperatorText(this); + } +} diff --git a/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java index b7d9d4e375701..2cd984df69eb3 100644 --- a/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java +++ b/camel-core/src/main/java/org/apache/camel/language/simple/SimpleLanguageSupport.java @@ -18,30 +18,113 @@ import java.util.ArrayList; import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.camel.Exchange; import org.apache.camel.Expression; import org.apache.camel.Predicate; import org.apache.camel.builder.ExpressionBuilder; import org.apache.camel.builder.PredicateBuilder; +import org.apache.camel.impl.ExpressionAdapter; import org.apache.camel.spi.Language; +import org.apache.camel.util.ObjectHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import static org.apache.camel.language.simple.SimpleLangaugeOperator.*; /** * Abstract base class for Simple languages. */ public abstract class SimpleLanguageSupport implements Language { - + + protected static final Pattern PATTERN = Pattern.compile("^\\$\\{(.+)\\}\\s+(==|>|>=|<|<=|!=|is)\\s+(.+)$"); + protected final Log log = LogFactory.getLog(getClass()); + public Predicate createPredicate(String expression) { return PredicateBuilder.toPredicate(createExpression(expression)); } public Expression createExpression(String expression) { - if (expression.indexOf("${") >= 0) { - return createComplexExpression(expression); + Matcher matcher = PATTERN.matcher(expression); + if (matcher.matches()) { + if (log.isDebugEnabled()) { + log.debug("Expression is evaluated as operator expression: " + expression); + } + return createOperatorExpression(matcher, expression); + } else if (expression.indexOf("${") >= 0) { + if (log.isDebugEnabled()) { + log.debug("Expression is evaluated as complex expression: " + expression); + } + return createComplexConcatExpression(expression); + } else { + if (log.isDebugEnabled()) { + log.debug("Expression is evaluated as simple expression: " + expression); + } + return createSimpleExpression(expression); + } + } + + private Expression createOperatorExpression(final Matcher matcher, final String expression) { + final Expression left = createSimpleExpression(matcher.group(1)); + final SimpleLangaugeOperator operator = asOperator(matcher.group(2)); + + // the right hand side expression can either be a constant expression wiht ' ' + // or another simple expression using ${ } placeholders + String text = matcher.group(3); + + final Expression right; + // special null handling + if ("null".equals(text)) { + right = createConstantExpression(null); + } else { + // text can either be a constant enclosed by ' ' or another expression using ${ } placeholders + String constant = ObjectHelper.between(text, "'", "'"); + String simple = ObjectHelper.between(text, "${", "}"); + + Expression exp = simple != null ? createSimpleExpression(simple) : createConstantExpression(constant); + // to support numeric comparions using > and < operators we must convert the right hand side + // to the same type as the left + right = ExpressionBuilder.convertTo(exp, left); } - return createSimpleExpression(expression); + + return new ExpressionAdapter() { + @Override + protected String assertionFailureMessage(Exchange exchange) { + return super.assertionFailureMessage(exchange); + } + + @Override + public Object evaluate(Exchange exchange) { + Predicate predicate = null; + if (operator == EQ) { + predicate = PredicateBuilder.isEqualTo(left, right); + } else if (operator == GT) { + predicate = PredicateBuilder.isGreaterThan(left, right); + } else if (operator == GTE) { + predicate = PredicateBuilder.isGreaterThanOrEqualTo(left, right); + } else if (operator == LT) { + predicate = PredicateBuilder.isLessThan(left, right); + } else if (operator == LTE) { + predicate = PredicateBuilder.isLessThanOrEqualTo(left, right); + } else if (operator == NOT) { + predicate = PredicateBuilder.isNotEqualTo(left, right); + } + + if (predicate == null) { + throw new IllegalArgumentException("Unsupported operator: " + operator + " for expression: " + expression); + } + return predicate.matches(exchange); + } + + @Override + public String toString() { + return left + " " + operator + " " + right; + } + }; } - protected Expression createComplexExpression(String expression) { + protected Expression createComplexConcatExpression(String expression) { List<Expression> results = new ArrayList<Expression>(); int pivot = 0; @@ -74,6 +157,10 @@ protected Expression createConstantExpression(String expression, int start, int return ExpressionBuilder.constantExpression(expression.substring(start, end)); } + protected Expression createConstantExpression(String expression) { + return ExpressionBuilder.constantExpression(expression); + } + /** * Creates the simple expression based on the extracted content from the ${ } place holders * diff --git a/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java b/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java index 0ee0bb795d7b9..c1429a98444c5 100644 --- a/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java +++ b/camel-core/src/main/java/org/apache/camel/util/ObjectHelper.java @@ -291,6 +291,28 @@ public static String capitalize(String text) { return answer; } + public static String after(String text, String after) { + if (!text.contains(after)) { + return null; + } + return text.substring(text.indexOf(after) + after.length()); + } + + public static String before(String text, String before) { + if (!text.contains(before)) { + return null; + } + return text.substring(0, text.indexOf(before)); + } + + public static String between(String text, String after, String before) { + text = after(text, after); + if (text == null) { + return null; + } + return before(text, before); + } + /** * Returns true if the collection contains the specified value */ diff --git a/camel-core/src/test/java/org/apache/camel/language/BeanTest.java b/camel-core/src/test/java/org/apache/camel/language/BeanTest.java index 8ef7bfe3ca5c9..a4f2d0b916867 100644 --- a/camel-core/src/test/java/org/apache/camel/language/BeanTest.java +++ b/camel-core/src/test/java/org/apache/camel/language/BeanTest.java @@ -32,10 +32,12 @@ public class BeanTest extends LanguageTestSupport { public void testSimpleExpressions() throws Exception { assertExpression("foo.cheese", "abc"); + assertExpression("foo?method=cheese", "abc"); } public void testPredicates() throws Exception { assertPredicate("foo.isFooHeaderAbc"); + assertPredicate("foo?method=isFooHeaderAbc"); } public void testBeanTypeExpression() throws Exception { diff --git a/camel-core/src/test/java/org/apache/camel/language/SimpleOperatorTest.java b/camel-core/src/test/java/org/apache/camel/language/SimpleOperatorTest.java new file mode 100644 index 0000000000000..cafb0b0adbc1d --- /dev/null +++ b/camel-core/src/test/java/org/apache/camel/language/SimpleOperatorTest.java @@ -0,0 +1,143 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.language; + +import org.apache.camel.Exchange; +import org.apache.camel.LanguageTestSupport; +import org.apache.camel.impl.JndiRegistry; + +/** + * @version $Revision$ + */ +public class SimpleOperatorTest extends LanguageTestSupport { + + @Override + protected JndiRegistry createRegistry() throws Exception { + JndiRegistry jndi = super.createRegistry(); + jndi.bind("generator", new MyFileNameGenerator()); + return jndi; + } + + public void testEqualOperator() throws Exception { + // string to string comparison + assertExpression("${in.header.foo} == 'abc'", true); + assertExpression("${in.header.foo} == 'def'", false); + assertExpression("${in.header.foo} == '1'", false); + + // integer to string comparioson + assertExpression("${in.header.bar} == '123'", true); + assertExpression("${in.header.bar} == '444'", false); + assertExpression("${in.header.bar} == '1'", false); + } + + public void testNotEqualOperator() throws Exception { + // string to string comparison + assertExpression("${in.header.foo} != 'abc'", false); + assertExpression("${in.header.foo} != 'def'", true); + assertExpression("${in.header.foo} != '1'", true); + + // integer to string comparioson + assertExpression("${in.header.bar} != '123'", false); + assertExpression("${in.header.bar} != '444'", true); + assertExpression("${in.header.bar} != '1'", true); + } + + public void testGreatherThanOperator() throws Exception { + // string to string comparison + assertExpression("${in.header.foo} > 'aaa'", true); + assertExpression("${in.header.foo} > 'def'", false); + + // integer to string comparioson + assertExpression("${in.header.bar} > '100'", true); + assertExpression("${in.header.bar} > '123'", false); + assertExpression("${in.header.bar} > '200'", false); + } + + public void testGreatherThanOrEqualOperator() throws Exception { + // string to string comparison + assertExpression("${in.header.foo} >= 'aaa'", true); + assertExpression("${in.header.foo} >= 'abc'", true); + assertExpression("${in.header.foo} >= 'def'", false); + + // integer to string comparioson + assertExpression("${in.header.bar} >= '100'", true); + assertExpression("${in.header.bar} >= '123'", true); + assertExpression("${in.header.bar} >= '200'", false); + } + + public void testLessThanOperator() throws Exception { + // string to string comparison + assertExpression("${in.header.foo} < 'aaa'", false); + assertExpression("${in.header.foo} < 'def'", true); + + // integer to string comparioson + assertExpression("${in.header.bar} < '100'", false); + assertExpression("${in.header.bar} < '123'", false); + assertExpression("${in.header.bar} < '200'", true); + } + + public void testLessThanOrEqualOperator() throws Exception { + // string to string comparison + assertExpression("${in.header.foo} <= 'aaa'", false); + assertExpression("${in.header.foo} <= 'abc'", true); + assertExpression("${in.header.foo} <= 'def'", true); + + // integer to string comparioson + assertExpression("${in.header.bar} <= '100'", false); + assertExpression("${in.header.bar} <= '123'", true); + assertExpression("${in.header.bar} <= '200'", true); + } + + public void testIsNull() throws Exception { + assertExpression("${in.header.foo} == null", false); + assertExpression("${in.header.none} == null", true); + } + + public void testIsNotNull() throws Exception { + assertExpression("${in.header.foo} != null", true); + assertExpression("${in.header.none} != null", false); + } + + public void testRightOperatorIsSimpleLanauge() throws Exception { + // operator on right side is also using ${ } placeholders + assertExpression("${in.header.foo} == ${in.header.foo}", true); + assertExpression("${in.header.foo} == ${in.header.bar}", false); + } + + public void testRightOperatorIsBeanLanauge() throws Exception { + // operator on right side is also using ${ } placeholders + assertExpression("${in.header.foo} == ${bean:generator.generateFilename}", true); + + assertExpression("${in.header.bar} == ${bean:generator.generateId}", true); + assertExpression("${in.header.bar} >= ${bean:generator.generateId}", true); + } + + protected String getLanguageName() { + return "simple"; + } + + public class MyFileNameGenerator { + public String generateFilename(Exchange exchange) { + return "abc"; + } + + public int generateId(Exchange exchange) { + return 123; + } + } + +} \ No newline at end of file diff --git a/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java b/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java index fffec73fd0bb2..624e03b4b6383 100644 --- a/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java +++ b/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java @@ -150,4 +150,22 @@ public void testCreateIteratorWithStringAndSemiColonSeparator() { assertEquals("c", it.next()); } + public void testBefore() { + assertEquals("Hello ", ObjectHelper.before("Hello World", "World")); + assertEquals("Hello ", ObjectHelper.before("Hello World Again", "World")); + assertEquals(null, ObjectHelper.before("Hello Again", "Foo")); + } + + public void testAfter() { + assertEquals(" World", ObjectHelper.after("Hello World", "Hello")); + assertEquals(" World Again", ObjectHelper.after("Hello World Again", "Hello")); + assertEquals(null, ObjectHelper.after("Hello Again", "Foo")); + } + + public void testBetween() { + assertEquals("foo bar", ObjectHelper.between("Hello 'foo bar' how are you", "'", "'")); + assertEquals("foo bar", ObjectHelper.between("Hello ${foo bar} how are you", "${", "}")); + assertEquals(null, ObjectHelper.between("Hello ${foo bar} how are you", "'", "'")); + } + }
5a91d607882e59a6255eff0f144a6efecc749af2
spring-framework
Allow setting WSDL document as a Resource--Prior to this change
a
https://github.com/spring-projects/spring-framework
diff --git a/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java b/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java index 3e8cf74b9024..7f95b3acd651 100644 --- a/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java +++ b/spring-web/src/main/java/org/springframework/remoting/jaxws/LocalJaxWsServiceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2012 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. @@ -16,12 +16,14 @@ package org.springframework.remoting.jaxws; +import java.io.IOException; import java.net.URL; import java.util.concurrent.Executor; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.handler.HandlerResolver; +import org.springframework.core.io.Resource; import org.springframework.util.Assert; /** @@ -53,11 +55,22 @@ public class LocalJaxWsServiceFactory { /** * Set the URL of the WSDL document that describes the service. + * @see #setWsdlDocumentResource(Resource) */ public void setWsdlDocumentUrl(URL wsdlDocumentUrl) { this.wsdlDocumentUrl = wsdlDocumentUrl; } + /** + * Set the WSDL document URL as a {@link Resource}. + * @throws IOException + * @since 3.2 + */ + public void setWsdlDocumentResource(Resource wsdlDocumentResource) throws IOException { + Assert.notNull(wsdlDocumentResource, "WSDL Resource must not be null."); + this.wsdlDocumentUrl = wsdlDocumentResource.getURL(); + } + /** * Return the URL of the WSDL document that describes the service. */
c0d8a840624ff68457c5a9da38e39e19fefe9db1
Mylyn Reviews
-Adapted dsl to review changesets -Added extension to experimental versions changeset list on a seperate page -Fixed error in dsl -Fixed copyright headers
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF index 90bbf5e2..f664b6fe 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/META-INF/MANIFEST.MF @@ -12,7 +12,8 @@ Require-Bundle: org.eclipse.core.runtime, org.eclipse.compare;bundle-version="3.5.0", org.eclipse.mylyn.reviews.tasks.dsl;bundle-version="0.0.1", org.eclipse.xtext;bundle-version="1.0.1", - org.eclipse.swt;bundle-version="3.6.1" + org.eclipse.swt;bundle-version="3.6.1", + org.eclipse.mylyn.versions.core;bundle-version="0.1.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: org.eclipse.mylyn.reviews.tasks.core, org.eclipse.mylyn.reviews.tasks.core.internal;x-friends:="org.eclipse.mylyn.reviews.tasks.ui" diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java new file mode 100644 index 00000000..7da5b03b --- /dev/null +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangeSetReviewFile.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ + +package org.eclipse.mylyn.reviews.tasks.core; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.eclipse.compare.IStreamContentAccessor; +import org.eclipse.compare.ITypedElement; +import org.eclipse.compare.structuremergeviewer.DiffNode; +import org.eclipse.compare.structuremergeviewer.Differencer; +import org.eclipse.compare.structuremergeviewer.ICompareInput; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.mylyn.versions.core.Change; +import org.eclipse.mylyn.versions.core.ChangeType; +import org.eclipse.mylyn.versions.core.ScmArtifact; +import org.eclipse.swt.graphics.Image; + +/** + * + * @author mattk + * + */ +public class ChangeSetReviewFile implements IReviewFile { + + private Change change; + + public ChangeSetReviewFile(Change change) { + this.change = change; + } + + @Override + public String getFileName() { + return change.getTarget().getPath(); + } + + @Override + public boolean isNewFile() { + return change.getChangeType().equals(ChangeType.ADDED); + } + + @Override + public boolean canReview() { + return true; + } + + @Override + public ICompareInput getCompareInput() { + ICompareInput ci = new DiffNode(Differencer.CHANGE, null, + new CompareItem(change.getBase()), new CompareItem(change.getTarget())); + return ci; + } + class CompareItem implements IStreamContentAccessor, ITypedElement { + private final ScmArtifact artifact; + + public CompareItem(ScmArtifact artifact) { + this.artifact=artifact; + } + + public InputStream getContents() throws CoreException { + // FIXME + if (artifact==null) return new ByteArrayInputStream(new byte[0]); + return artifact.getFileRevision(new NullProgressMonitor()).getStorage(new NullProgressMonitor()).getContents(); + } + public Image getImage() { + return null; + } + + public String getName() { + return artifact.getPath(); + } + + public String getType() { + return ITypedElement.TEXT_TYPE; + } + } + +} diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java new file mode 100644 index 00000000..a82ffa43 --- /dev/null +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ChangesetScopeItem.java @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ + +package org.eclipse.mylyn.reviews.tasks.core; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.resources.IStorage; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.mylyn.versions.core.Change; +import org.eclipse.mylyn.versions.core.ChangeSet; +import org.eclipse.mylyn.versions.core.ScmCore; +import org.eclipse.mylyn.versions.core.ScmRepository; +import org.eclipse.mylyn.versions.core.spi.ScmConnector; +import org.eclipse.team.core.history.IFileRevision; +import org.eclipse.team.core.history.ITag; + +/** + * + * @author mattk + * + */ +public class ChangesetScopeItem implements IReviewScopeItem { + + private String revisionId; + private String repositoryUrl; + + public ChangesetScopeItem(String revisionId, String repositoryUrl) { + super(); + this.revisionId = revisionId; + this.repositoryUrl = repositoryUrl; + } + + @Override + public List<IReviewFile> getReviewFiles(NullProgressMonitor monitor) + throws CoreException { + for (ScmConnector connector : ScmCore.getAllRegisteredConnectors()) { + for (ScmRepository repository : connector + .getRepositories(new NullProgressMonitor())) { + if (repositoryUrl.equals(repository.getUrl())) { + ChangeSet changeset = connector.getChangeset(repository, + new IFileRevision() { + + @Override + public IStorage getStorage( + IProgressMonitor monitor) + throws CoreException { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public URI getURI() { + return null; + } + + @Override + public long getTimestamp() { + return 0; + } + + @Override + public boolean exists() { + return false; + } + + @Override + public String getContentIdentifier() { + return revisionId; + } + + @Override + public String getAuthor() { + return null; + } + + @Override + public String getComment() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ITag[] getTags() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isPropertyMissing() { + // TODO Auto-generated method stub + return false; + } + + @Override + public IFileRevision withAllProperties( + IProgressMonitor monitor) + throws CoreException { + // TODO Auto-generated method stub + return null; + } + }, monitor); + List<IReviewFile> list = new ArrayList<IReviewFile>(); + for (Change change : changeset.getChanges()) { + list.add(new ChangeSetReviewFile(change)); + } + return list; + + } + } + + } + return new ArrayList<IReviewFile>(); + } + + public String getRepositoryUrl() { + return repositoryUrl; + } + + public String getRevisionId() { + return revisionId; + } + + @Override + public String getDescription() { + return "Changeset " + revisionId; + } + + @Override + public String getType(int count) { + return count == 1 ? "changeset" : "changesets"; + } + +} diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java index 8ab9c07f..aad5c57d 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java @@ -16,6 +16,7 @@ import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.mylyn.reviews.tasks.core.Attachment; +import org.eclipse.mylyn.reviews.tasks.core.ChangesetScopeItem; import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper; import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; @@ -27,6 +28,7 @@ import org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.ReviewDslParser; import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.AttachmentSource; import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ChangedReviewScope; +import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ChangesetDef; import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.PatchDef; import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ResourceDef; import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ResultEnum; @@ -36,9 +38,10 @@ import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.Source; import org.eclipse.xtext.parser.IParseResult; import org.eclipse.xtext.parsetree.reconstr.Serializer; + /** * @author mattk - * + * */ public class ReviewTaskMapper implements IReviewMapper { private ReviewDslParser parser; @@ -86,11 +89,12 @@ public ReviewScope mapTaskToScope(ITaskProperties properties) org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope = (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope) parsed .getRootASTElement(); ReviewScope originalScope = mapReviewScope(properties, scope); - for(TaskComment comment : properties.getComments()) { - if(properties.getReporter().equals(comment.getAuthor())) { - parsed= parser.doParse(comment.getText()); - if(parsed.getRootASTElement() instanceof ChangedReviewScope) { - ChangedReviewScope changedScope=(ChangedReviewScope) parsed.getRootASTElement(); + for (TaskComment comment : properties.getComments()) { + if (properties.getReporter().equals(comment.getAuthor())) { + parsed = parser.doParse(comment.getText()); + if (parsed.getRootASTElement() instanceof ChangedReviewScope) { + ChangedReviewScope changedScope = (ChangedReviewScope) parsed + .getRootASTElement(); applyChangedScope(properties, originalScope, changedScope); } } @@ -98,9 +102,10 @@ public ReviewScope mapTaskToScope(ITaskProperties properties) return originalScope; } - private void applyChangedScope(ITaskProperties properties, ReviewScope originalScope, - ChangedReviewScope changedScope) throws CoreException { - for(ReviewScopeItem scope :changedScope.getScope()) { + private void applyChangedScope(ITaskProperties properties, + ReviewScope originalScope, ChangedReviewScope changedScope) + throws CoreException { + for (ReviewScopeItem scope : changedScope.getScope()) { IReviewScopeItem item = mapReviewScopeItem(properties, scope); originalScope.addScope(item); } @@ -117,7 +122,7 @@ private ReviewScope mapReviewScope(ITaskProperties properties, for (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem s : scope .getScope()) { IReviewScopeItem item = mapReviewScopeItem(properties, s); - if(item!=null) { + if (item != null) { mappedScope.addScope(item); } } @@ -133,10 +138,18 @@ private IReviewScopeItem mapReviewScopeItem(ITaskProperties properties, } else if (s instanceof ResourceDef) { ResourceDef res = (ResourceDef) s; item = mapResourceDef(properties, res); + } else if (s instanceof ChangesetDef) { + ChangesetDef res = (ChangesetDef) s; + item = mapChangesetDef(properties, res); } return item; } + private ChangesetScopeItem mapChangesetDef(ITaskProperties properties, + ChangesetDef cs) throws CoreException { + return new ChangesetScopeItem(cs.getRevision(), cs.getUrl()); + } + private ResourceScopeItem mapResourceDef(ITaskProperties properties, ResourceDef res) throws CoreException { Source source = res.getSource(); @@ -147,7 +160,8 @@ private ResourceScopeItem mapResourceDef(ITaskProperties properties, return new ResourceScopeItem(att); } - private PatchScopeItem mapPatchDef(ITaskProperties properties, PatchDef patch) throws CoreException { + private PatchScopeItem mapPatchDef(ITaskProperties properties, + PatchDef patch) throws CoreException { Source source = patch.getSource(); Attachment att = null; if (source instanceof AttachmentSource) { @@ -201,6 +215,13 @@ private org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem mapScopeIt AttachmentSource source = mapAttachment(attachment); resource.setSource(source); return resource; + } else if (item instanceof ChangesetScopeItem) { + ChangesetScopeItem changesetItem = (ChangesetScopeItem) item; + ChangesetDef changeset = ReviewDslFactory.eINSTANCE + .createChangesetDef(); + changeset.setRevision(changesetItem.getRevisionId()); + changeset.setUrl(changesetItem.getRepositoryUrl()); + return changeset; } return null; } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext index 5aac21b0..ea536461 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext +++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext @@ -7,49 +7,49 @@ Model: ReviewResult: "Review result:" result=ResultEnum - ("Comment:" comment=STRING )? (filecomments+=FileComment)* ; + ("Comment:" comment=STRING)? (filecomments+=FileComment)*; enum ResultEnum: passed="PASSED" | failed="FAILED" - | todo="TODO" | warning="WARNING"; + | todo="TODO" | warning="WARNING"; FileComment: - "File" path=STRING ":" comment=STRING? + "File" path=STRING ":" comment=STRING? linecomments+=LineComment*; LineComment: - "Line " start=INT ("-" end=INT)? ":" comment=STRING; + "Line" start=INT ("-" end=INT)? ":" comment=STRING; ReviewScope: -{ReviewScope}"Review scope:" - ( - scope+=ReviewScopeItem - )* - ; + {ReviewScope} "Review scope:" + (scope+=ReviewScopeItem)*; ChangedReviewScope: - "Updated review scope:" + "Updated review scope:" //(refines" (refineOriginal?="original scope"| ("scope from comment #" refineComment=INT)) ":" (scope+=ReviewScopeItem)+; -//ChangesetDef: -// ("Changeset" revision=INT " from " repoType=ID url=STRING ); + +ChangesetDef: + ("Changeset" revision=STRING "from" url=STRING); + ReviewScopeItem: - ResourceDef|PatchDef; + ResourceDef | PatchDef | ChangesetDef; + ResourceDef: - ("Resource" source=Source ); + ("Resource" source=Source); PatchDef: - ("Patch" source=Source ); + ("Patch" source=Source); Source: AttachmentSource; AttachmentSource: - "from Attachment" filename=STRING - "by" author=STRING - "on" createdDate=STRING + "from Attachment" filename=STRING + "by" author=STRING + "on" createdDate=STRING "of task" taskId=TASK_ID; - -terminal TASK_ID : ('a'..'z'|'A'..'Z'|'_'|'-'|'0'..'9')*; +terminal TASK_ID: + ('a'..'z' | 'A'..'Z' | '_' | '-' | '0'..'9')*; diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF index 19215461..f628ec2f 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/META-INF/MANIFEST.MF @@ -12,7 +12,9 @@ Require-Bundle: org.eclipse.ui, org.eclipse.mylyn.tasks.core;bundle-version="3.3.0", org.eclipse.compare;bundle-version="3.5.0", org.eclipse.core.resources;bundle-version="3.6.0", - org.eclipse.mylyn.reviews.tasks.core;bundle-version="0.0.1" + org.eclipse.mylyn.reviews.tasks.core;bundle-version="0.0.1", + org.eclipse.mylyn.versions.core;bundle-version="0.1.0", + org.eclipse.mylyn.versions.tasks.core;bundle-version="0.0.1" Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: org.eclipse.mylyn.reviews.tasks.ui.internal;x-internal:=true, diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml b/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml index e9863184..660dbcfd 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/plugin.xml @@ -25,6 +25,16 @@ tooltip="Create a new review from this attachment"> </action> </objectContribution> + <objectContribution + adaptable="false" + id="org.eclipse.mylyn.reviews.tasks.ui.changesets" + objectClass="org.eclipse.mylyn.versions.tasks.core.TaskChangeSet"> + <action + class="org.eclipse.mylyn.reviews.tasks.ui.internal.CreateReviewFromChangeSetAction" + id="org.eclipse.mylyn.reviews.tasks.ui.action1" + label="Create Review"> + </action> + </objectContribution> </extension> <extension point="org.eclipse.mylyn.tasks.ui.editors"> diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java new file mode 100644 index 00000000..e5699b10 --- /dev/null +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewFromChangeSetAction.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation + *******************************************************************************/ + +package org.eclipse.mylyn.reviews.tasks.ui.internal; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jface.action.Action; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; +import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; +import org.eclipse.mylyn.reviews.tasks.core.ChangesetScopeItem; +import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper; +import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; +import org.eclipse.mylyn.reviews.tasks.core.ReviewScope; +import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties; +import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; +import org.eclipse.mylyn.tasks.core.ITask; +import org.eclipse.mylyn.tasks.core.TaskRepository; +import org.eclipse.mylyn.tasks.core.data.ITaskDataManager; +import org.eclipse.mylyn.tasks.core.data.TaskData; +import org.eclipse.mylyn.tasks.core.data.TaskMapper; +import org.eclipse.mylyn.tasks.ui.TasksUi; +import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet; +import org.eclipse.ui.IActionDelegate; + +/** + * + * @author mattk + * + */ +@SuppressWarnings("restriction") +public class CreateReviewFromChangeSetAction extends Action implements + IActionDelegate { + + private IStructuredSelection selection; + + @Override + public void run(IAction action) { + try { + ITask task = ((TaskChangeSet)selection.getFirstElement()).getTask(); + TaskRepository taskRepository = TasksUi.getRepositoryManager() + .getRepository(task.getConnectorKind(), + task.getRepositoryUrl()); + ITaskDataManager manager = TasksUi.getTaskDataManager(); + TaskData parentTaskData = manager.getTaskData(task); + ITaskProperties parentTask = TaskProperties.fromTaskData(manager, + parentTaskData); + + TaskMapper initializationData = new TaskMapper(parentTaskData); + IReviewMapper taskMapper = ReviewsUiPlugin.getMapper(); + + TaskData taskData = TasksUiInternal.createTaskData(taskRepository, + initializationData, null, new NullProgressMonitor()); + AbstractRepositoryConnector connector = TasksUiPlugin + .getConnector(taskRepository.getConnectorKind()); + + connector.getTaskDataHandler().initializeSubTaskData( + taskRepository, taskData, parentTaskData, + new NullProgressMonitor()); + + ITaskProperties taskProperties = TaskProperties.fromTaskData( + manager, taskData); + taskProperties + .setSummary("[review] " + parentTask.getDescription()); + + String reviewer = taskRepository.getUserName(); + taskProperties.setAssignedTo(reviewer); + + initTaskProperties(taskMapper, taskProperties, parentTask,task); + + TasksUiInternal.createAndOpenNewTask(taskData); + } catch (CoreException e) { + throw new RuntimeException(e); + } + + } + + private void initTaskProperties(IReviewMapper taskMapper, + ITaskProperties taskProperties, ITaskProperties parentTask,ITask task) { + taskMapper.mapScopeToTask(getScope(task), taskProperties); + } + + private ReviewScope getScope(ITask task) { + List<TaskChangeSet> changesets = getSelectedChangesets(task); + ReviewScope scope = new ReviewScope(); + for (TaskChangeSet cs : changesets) { + scope.addScope(new ChangesetScopeItem(cs.getChangeset().getId(), cs + .getChangeset().getRepository().getUrl())); + } + return scope; + } + + private List<TaskChangeSet> getSelectedChangesets(ITask task) { + List<TaskChangeSet> cs = new ArrayList<TaskChangeSet>(); + for (Object obj : selection.toArray()) { + cs.add((TaskChangeSet) obj); + } + return cs; + } + + @Override + public void selectionChanged(IAction action, ISelection selection) { + setEnabled(selection.isEmpty() + && selection instanceof IStructuredSelection); + this.selection = (IStructuredSelection) selection; + } + +}
ccedd8f8e0e01c6472cd32d371d8f579f60af9fc
orientdb
fixed cluster id selection in distributed mode.--
c
https://github.com/orientechnologies/orientdb
diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java index 8a2b793b258..113f0231f3d 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java +++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java @@ -20,6 +20,8 @@ package com.orientechnologies.orient.server.distributed.task; import com.orientechnologies.orient.core.Orient; +import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; +import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.db.record.OPlaceholder; import com.orientechnologies.orient.core.id.ORID; @@ -28,6 +30,7 @@ import com.orientechnologies.orient.core.record.ORecord; import com.orientechnologies.orient.core.record.ORecordInternal; import com.orientechnologies.orient.core.record.impl.ODocument; +import com.orientechnologies.orient.core.record.impl.ODocumentInternal; import com.orientechnologies.orient.core.version.ORecordVersion; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.distributed.ODistributedRequest; @@ -65,11 +68,14 @@ public OCreateRecordTask(final ORecordId iRid, final byte[] iContent, final ORec public OCreateRecordTask(final ORecord record) { this((ORecordId) record.getIdentity(), record.toStream(), record.getRecordVersion(), ORecordInternal.getRecordType(record)); - if (rid.getClusterId() == ORID.CLUSTER_ID_INVALID && record instanceof ODocument) { - final OClass clazz = ((ODocument) record).getSchemaClass(); - if (clazz != null) { + if (rid.getClusterId() == ORID.CLUSTER_ID_INVALID) { + final OClass clazz; + if (record instanceof ODocument && (clazz = ODocumentInternal.getImmutableSchemaClass((ODocument) record)) != null) { // PRE-ASSIGN THE CLUSTER ID ON CALLER NODE clusterId = clazz.getClusterSelection().getCluster(clazz, (ODocument) record); + } else { + ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.get(); + clusterId = db.getDefaultClusterId(); } } }
46b70c58eb6ae13bb640f7bebd8e088728db77f2
evllabs$jgaap
Updating API & Document Formatting API is ready to add cullers to EventDrivers but currently previous functionality is being preserved Output has been updated to allow for Cullers attached to EventDrivers and for Multiple EventDrivers
p
https://github.com/evllabs/jgaap
diff --git a/src/com/jgaap/backend/API.java b/src/com/jgaap/backend/API.java index d9b881d6e..e2d0551d5 100644 --- a/src/com/jgaap/backend/API.java +++ b/src/com/jgaap/backend/API.java @@ -30,7 +30,6 @@ import org.apache.log4j.Logger; -import com.jgaap.classifiers.NearestNeighborDriver; import com.jgaap.generics.*; import com.jgaap.languages.English; @@ -79,7 +78,6 @@ private API() { documents = new ArrayList<Document>(); language = new English(); eventDrivers = new ArrayList<EventDriver>(); - eventCullers = new ArrayList<EventCuller>(); analysisDrivers = new ArrayList<AnalysisDriver>(); } @@ -122,9 +120,7 @@ public static API getPrivateInstance(){ public Document addDocument(String filepath, String author, String title) throws Exception { Document document = new Document(filepath, author, title); - documents.add(document); - logger.info("Adding Document "+document.toString()); - return document; + return addDocument(document); } /** @@ -154,6 +150,7 @@ public Boolean removeDocument(Document document) { * Removes all documents loaded into the system. */ public void removeAllDocuments() { + logger.info("Removing all Documents"); documents.clear(); } @@ -245,12 +242,15 @@ public void loadDocuments() throws Exception{ * Adds the specified canonicizer to all documents currently loaded in the system. * * @param action - the unique string name representing a canonicizer (displayName()) + * @return - a reference to the canonicizer added * @throws Exception - if the canonicizer specified cannot be found or instanced */ - public void addCanonicizer(String action) throws Exception { + public Canonicizer addCanonicizer(String action) throws Exception { + Canonicizer canonicizer = CanonicizerFactory.getCanonicizer(action); for (Document document : documents) { - addCanonicizer(action, document); + addCanonicizer(canonicizer, document); } + return canonicizer; } /** @@ -258,14 +258,17 @@ public void addCanonicizer(String action) throws Exception { * * @param action - the unique string name representing a canonicizer (displayName()) * @param docType - The DocType this canonicizer is restricted to + * @return - a reference to the canonicizer added * @throws Exception - if the canonicizer specified cannot be found or instanced */ - public void addCanonicizer(String action, DocType docType) throws Exception { + public Canonicizer addCanonicizer(String action, DocType docType) throws Exception { + Canonicizer canonicizer = CanonicizerFactory.getCanonicizer(action); for (Document document : documents) { if (document.getDocType().equals(docType)) { - addCanonicizer(action, document); + addCanonicizer(canonicizer, document); } } + return canonicizer; } /** @@ -279,6 +282,17 @@ public void addCanonicizer(String action, DocType docType) throws Exception { public Canonicizer addCanonicizer(String action, Document document) throws Exception { Canonicizer canonicizer = CanonicizerFactory.getCanonicizer(action); + return addCanonicizer(canonicizer, document); + } + + /** + * Add the Canonicizer specified to the document referenced. + * + * @param canonicizer - the canonicizer to add + * @param document - the Document to add the canonicizer to + * @return - a reference to the canonicizer added + */ + public Canonicizer addCanonicizer(Canonicizer canonicizer, Document document) { document.addCanonicizer(canonicizer); logger.info("Adding Canonicizer "+canonicizer.displayName()+" to Document "+document.toString()); return canonicizer; @@ -291,8 +305,8 @@ public Canonicizer addCanonicizer(String action, Document document) * @param action - the unique string name representing a canonicizer (displayName()) * @param document - a reference to the Document to remove the canonicizer from */ - public void removeCanonicizer(String action, Document document) { - document.removeCanonicizer(action); + public void removeCanonicizer(Canonicizer canonicizer, Document document) { + document.removeCanonicizer(canonicizer); } /** @@ -301,9 +315,9 @@ public void removeCanonicizer(String action, Document document) { * * @param action - the unique string name representing a canonicizer (displayName()) */ - public void removeCanonicizer(String action) { + public void removeCanonicizer(Canonicizer canonicizer) { for (Document document : documents) { - removeCanonicizer(action, document); + removeCanonicizer(canonicizer, document); } } @@ -313,10 +327,10 @@ public void removeCanonicizer(String action) { * @param action - the unique string name representing a canonicizer (displayName()) * @param docType - the DocType to remove the canonicizer from */ - public void removeCanonicizer(String action, DocType docType) { + public void removeCanonicizer(Canonicizer canonicizer, DocType docType) { for (Document document : documents) { if (document.getDocType().equals(docType)) { - removeCanonicizer(action, document); + removeCanonicizer(canonicizer, document); } } } @@ -351,6 +365,17 @@ public void removeAllCanonicizers() { */ public EventDriver addEventDriver(String action) throws Exception { EventDriver eventDriver = EventDriverFactory.getEventDriver(action); + return addEventDriver(eventDriver); + } + + /** + * Add an Event Driver which will be used to + * eventify(Generate a List of Events order in the sequence they are found in the document) + * all of the documents + * @param eventDriver - the EventDriver to add + * @return - a reference to the added EventDriver + */ + public EventDriver addEventDriver(EventDriver eventDriver) { eventDrivers.add(eventDriver); logger.info("Adding EventDriver "+eventDriver.displayName()); return eventDriver; @@ -393,8 +418,15 @@ public List<EventDriver> getEventDrivers() { */ public EventCuller addEventCuller(String action) throws Exception { EventCuller eventCuller = EventCullerFactory.getEventCuller(action); - eventCullers.add(eventCuller); - logger.info("Adding EventCuller "+eventCuller.displayName()); + for(EventDriver eventDriver : eventDrivers) { + addEventCuller(eventCuller, eventDriver); + } + return eventCuller; + } + + public EventCuller addEventCuller(EventCuller eventCuller, EventDriver eventDriver) { + eventDriver.addCuller(eventCuller); + logger.info("Adding EventCuller "+eventCuller.displayName()+" to "+eventDriver.displayName()); return eventCuller; } @@ -426,25 +458,17 @@ public List<EventCuller> getEventCullers() { /** * Add an AnalysisDriver to the system as referenced by the action. - * - * NOTE! for legacy purposes this methods also accepts actions that reference DistanceFunctions - * it will use the supplied distance function along with the NeighborAnalysisDriver NearestNeighborDriver - * which had been the only NeighbotAnalysisDriver prior to version 5.0 - * !!!WARNING!!! There are no guarantees that this functionality will remain in future releases please use addDistanceFunction - * + * * @param action - the unique identifier for a AnalysisDriver (alternately a DistanceFunction) * @return - a reference to the generated Analysis Driver * @throws Exception - If the AnalysisDriver cannot be found or if it cannot be instanced */ public AnalysisDriver addAnalysisDriver(String action) throws Exception { - AnalysisDriver analysisDriver; - try { - analysisDriver = AnalysisDriverFactory.getAnalysisDriver(action); - } catch (Exception e) { - logger.warn("Unable to load action "+action+" as AnalysisDriver attempting to load as DistanceFunction using NearestNeighborDriver", e); - analysisDriver = new NearestNeighborDriver(); - addDistanceFunction(action, analysisDriver); - } + AnalysisDriver analysisDriver = AnalysisDriverFactory.getAnalysisDriver(action); + return addAnalysisDriver(analysisDriver); + } + + public AnalysisDriver addAnalysisDriver(AnalysisDriver analysisDriver) { logger.info("Adding AnalysisDriver "+analysisDriver.displayName()); analysisDrivers.add(analysisDriver); return analysisDriver; @@ -480,10 +504,22 @@ public DistanceFunction addDistanceFunction(String action, AnalysisDriver analysisDriver) throws Exception { DistanceFunction distanceFunction = DistanceFunctionFactory .getDistanceFunction(action); + return addDistanceFunction(distanceFunction, analysisDriver); + } + + /** + * Adds a DistanceFunction to the AnalysisDriver supplied. + * Only AnalysisDrivers that extend the NeighborAnalysisDriver can be used + * + * @param distanceFunction - the DistanceFunction you want to add + * @param analysisDriver - a reference to the AnalysisDriver you want the distance added to + * @return - a reference to the generated DistanceFunction + */ + public DistanceFunction addDistanceFunction(DistanceFunction distanceFunction, AnalysisDriver analysisDriver) { ((NeighborAnalysisDriver) analysisDriver).setDistance(distanceFunction); return distanceFunction; } - + /** * Get a List of All AnalysisDrivers currently loaded on the system * @return List of All AnalysisDrivers @@ -585,13 +621,13 @@ public Document call() throws Exception { * @throws EventCullingException */ private void cull() throws EventCullingException { - if(eventCullers.isEmpty()) return; List<EventSet> eventSets = new ArrayList<EventSet>(documents.size()); for (EventDriver eventDriver : eventDrivers) { + //TODO: Possibly add threading here for (Document document : documents) { eventSets.add(document.getEventSet(eventDriver)); } - for (EventCuller culler : eventCullers) { + for (EventCuller culler : eventDriver.getEventCullers()) { eventSets = culler.cull(eventSets); } for (Document document : documents) { @@ -614,11 +650,10 @@ private void analyze() throws AnalyzeException { unknownDocuments.add(document); } } - + // ExecutorService analysisExecutor = Executors.newFixedThreadPool(workers); for (AnalysisDriver analysisDriver : analysisDrivers) { logger.info("Training " + analysisDriver.displayName()); analysisDriver.train(knownDocuments); - // ExecutorService analysisExecutor = Executors.newFixedThreadPool(workers); if (analysisDriver instanceof ValidationDriver) { for (Document knownDocument : knownDocuments) { // TODO: change to threaded here @@ -665,52 +700,4 @@ public void clearData() { document.clearResults(); } } - - /** - * Get a List of All Canonicizers that are available to be used - * @return List of All Canonicizers - */ - public List<Canonicizer> getAllCanonicizers() { - return Canonicizer.getCanonicizers(); - } - - /** - * Get a List of All EventDrivers that are available to be used - * @return List of All EventDrivers - */ - public List<EventDriver> getAllEventDrivers() { - return EventDriver.getEventDrivers(); - } - - /** - * Get a List of All EventCuller that are available to be used - * @return List of All EventCullers - */ - public List<EventCuller> getAllEventCullers() { - return EventCuller.getEventCullers(); - } - - /** - * Get a List of All AnalysisDriver that are available to be used - * @return List of All AnalysisDrivers - */ - public List<AnalysisDriver> getAllAnalysisDrivers() { - return AnalysisDriver.getAnalysisDrivers(); - } - - /** - * Get a List of All DistanceFunctions that are available to be used - * @return List of All DistanceFunctions - */ - public List<DistanceFunction> getAllDistanceFunctions() { - return DistanceFunction.getDistanceFunctions(); - } - - /** - * Get a List of All Languages that are available to be used - * @return List of All Languages - */ - public List<Language> getAllLanguages() { - return Language.getLanguages(); - } } diff --git a/src/com/jgaap/generics/Document.java b/src/com/jgaap/generics/Document.java index 2032b2d95..fb803b806 100644 --- a/src/com/jgaap/generics/Document.java +++ b/src/com/jgaap/generics/Document.java @@ -250,20 +250,6 @@ public boolean removeCanonicizer(Canonicizer canonicizer) { return canonicizers.remove(canonicizer); } - /** - * Remove the first canonicizer whose displayname matches the passed string - * @param action - * @return - */ - public boolean removeCanonicizer(String action) { - for (Canonicizer canonicizer : canonicizers) { - if (canonicizer.displayName().equalsIgnoreCase(action)) { - return canonicizers.remove(canonicizer); - } - } - return false; - } - /** * Get all the canonicizers associated with this Document. * @@ -353,7 +339,7 @@ public String getFormattedResult(AnalysisDriver analysisDriver) { StringBuilder buffer = new StringBuilder(); buffer.append(getTitle() + " "); buffer.append(getFilePath() + "\n"); - buffer.append("Canonicizers: "); + buffer.append("Canonicizers: \n"); if (canonicizers.isEmpty()) { buffer.append("none"); } else { @@ -363,11 +349,15 @@ public String getFormattedResult(AnalysisDriver analysisDriver) { buffer.delete(buffer.length()-2, buffer.length()-1); } buffer.append("\n"); - buffer.append("EventDrivers: "); - for(EventDriver eventDriver : eventSets.keySet()) - buffer.append(eventDriver.displayName()).append(" ").append(eventDriver.getParameters()).append(" "); + buffer.append("EventDrivers: \n"); + for(EventDriver eventDriver : eventSets.keySet()){ + buffer.append(eventDriver.displayName()).append(" ").append(eventDriver.getParameters()); + for(EventCuller eventCuller : eventDriver.getEventCullers()){ + buffer.append("\n\t").append(eventCuller.displayName()).append(" ").append(eventDriver.getParameters()); + } + } buffer.append("\n"); - buffer.append("Analysis: ").append(analysisDriver.displayName()).append(" ").append(analysisDriver.getParameters()); + buffer.append("Analysis: \n").append(analysisDriver.displayName()).append(" ").append(analysisDriver.getParameters()); buffer.append("\n"); int count = 0; // Keeps a relative count (adjusted for ties) int fullCount = 0; // Keeps the absolute count (does not count ties) diff --git a/src/com/jgaap/generics/EventDriver.java b/src/com/jgaap/generics/EventDriver.java index 5d50cf81d..f2f461761 100644 --- a/src/com/jgaap/generics/EventDriver.java +++ b/src/com/jgaap/generics/EventDriver.java @@ -43,6 +43,8 @@ public abstract class EventDriver extends Parameterizable implements Comparable< public String longDescription() { return tooltipText(); } public abstract boolean showInGUI(); + + private List<EventCuller> cullers; /** * Creates an EventSet from a given DocumentSet after preprocessing. @@ -82,6 +84,24 @@ private static List<EventDriver> loadEventDrivers() { Collections.sort(eventDrivers); return eventDrivers; } + + public boolean addCuller(EventCuller eventCuller) { + if(cullers == null) + cullers = new ArrayList<EventCuller>(); + return cullers.add(eventCuller); + } + + public boolean removeCuller(EventCuller eventCuller) { + return cullers.remove(eventCuller); + } + + public void clearCullers(){ + cullers.clear(); + } + + public List<EventCuller> getEventCullers() { + return cullers; + } } diff --git a/src/com/jgaap/ui/JGAAP_UI_MainForm.java b/src/com/jgaap/ui/JGAAP_UI_MainForm.java index 5e6356725..1f052e9d8 100644 --- a/src/com/jgaap/ui/JGAAP_UI_MainForm.java +++ b/src/com/jgaap/ui/JGAAP_UI_MainForm.java @@ -3598,28 +3598,27 @@ private void SanatizeMasterLists() { EventDriverMasterList = new ArrayList<EventDriver>(); LanguagesMasterList = new ArrayList<Language>(); - for (AnalysisDriver analysisDriver : JGAAP_API.getAllAnalysisDrivers()) { + for (AnalysisDriver analysisDriver : AnalysisDriver.getAnalysisDrivers()) { if (analysisDriver.showInGUI()) AnalysisDriverMasterList.add(analysisDriver); } - for (Canonicizer canonicizer : JGAAP_API.getAllCanonicizers()) { + for (Canonicizer canonicizer : Canonicizer.getCanonicizers()) { if (canonicizer.showInGUI()) CanonicizerMasterList.add(canonicizer); } - for (DistanceFunction distanceFunction : JGAAP_API - .getAllDistanceFunctions()) { + for (DistanceFunction distanceFunction : DistanceFunction.getDistanceFunctions()) { if (distanceFunction.showInGUI()) DistanceFunctionsMasterList.add(distanceFunction); } - for (EventCuller eventCuller : JGAAP_API.getAllEventCullers()) { + for (EventCuller eventCuller : EventCuller.getEventCullers()) { if (eventCuller.showInGUI()) EventCullersMasterList.add(eventCuller); } - for (EventDriver eventDriver : JGAAP_API.getAllEventDrivers()) { + for (EventDriver eventDriver : EventDriver.getEventDrivers()) { if (eventDriver.showInGUI()) EventDriverMasterList.add(eventDriver); } - for (Language language : JGAAP_API.getAllLanguages()) { + for (Language language : Language.getLanguages()) { if (language.showInGUI()) LanguagesMasterList.add(language); }
4664ec0c3a5ee0928e934451b47f51a32f4dfd66
echo3$echo3
Refactor for BorderPeer, exposed functionality to render Border XML element.
p
https://github.com/echo3/echo3
diff --git a/src/server-java/app/nextapp/echo/app/serial/property/BorderPeer.java b/src/server-java/app/nextapp/echo/app/serial/property/BorderPeer.java index 2df92496..6602d540 100644 --- a/src/server-java/app/nextapp/echo/app/serial/property/BorderPeer.java +++ b/src/server-java/app/nextapp/echo/app/serial/property/BorderPeer.java @@ -33,6 +33,7 @@ import java.util.StringTokenizer; import org.w3c.dom.Element; +import org.w3c.dom.Node; import nextapp.echo.app.Border; import nextapp.echo.app.Color; @@ -65,6 +66,60 @@ public class BorderPeer private static final String[] borderSideAttributeNames = new String[]{"t", "r", "b", "l"}; + /** + * Generates a <code>Border.Side</code> from a string representation. + * To create a non-multisided border from a string, simply pass the returned + * <code>Border.Side</code> to the constructor of a new <code>Border</code>. + * + * @param value the string representation + * @return the generated <code>Border.Side</code> + * @throws SerialException if the string is not a valid representation of a <code>Border.Side</code> + */ + public static final Border.Side fromString(String value) + throws SerialException { + try { + StringTokenizer st = new StringTokenizer(value, " "); + String sizeString = st.nextToken(); + String styleString = st.nextToken(); + String colorString = st.nextToken(); + + Extent size = ExtentPeer.fromString(sizeString); + int style = STYLE_CONSTANT_MAP.get(styleString, Border.STYLE_SOLID); + Color color = ColorPeer.fromString(colorString); + + return new Border.Side(size, color, style); + } catch (NoSuchElementException ex) { + throw new SerialException("Unable to parse border side value: " + value, ex); + } + } + + /** + * Creates a <code>Node</code> representation of the border state suitable for appending to a property element. + * + * @param context the relevant <code>Context</code> + * @param border the border to render + * @return the created node, may be a <code>Text</code> or <code>Element</code> node + */ + public static final Node toNode(Context context, Border border) + throws SerialException { + SerialContext serialContext = (SerialContext) context.get(SerialContext.class); + if (border.isMultisided()) { + Element borderElement = serialContext.getDocument().createElement("b"); + Border.Side[] sides = border.getSides(); + for (int i = 0; i < sides.length; ++i) { + if (sides[i] == null) { + borderElement.setAttribute(borderSideAttributeNames[i], ""); + } else { + borderElement.setAttribute(borderSideAttributeNames[i], toString(sides[i])); + } + } + return borderElement; + } else { + return serialContext.getDocument().createTextNode(toString(border)); + } + } + + /** * Generates a string representation of a <code>Border</code> * @@ -95,33 +150,6 @@ public static final String toString(Border.Side side) return out.toString(); } - /** - * Generates a <code>Border.Side</code> from a string representation. - * To create a non-multisided border from a string, simply pass the returned - * <code>Border.Side</code> to the constructor of a new <code>Border</code>. - * - * @param value the string representation - * @return the generated <code>Border.Side</code> - * @throws SerialException if the string is not a valid representation of a <code>Border.Side</code> - */ - public static final Border.Side fromString(String value) - throws SerialException { - try { - StringTokenizer st = new StringTokenizer(value, " "); - String sizeString = st.nextToken(); - String styleString = st.nextToken(); - String colorString = st.nextToken(); - - Extent size = ExtentPeer.fromString(sizeString); - int style = STYLE_CONSTANT_MAP.get(styleString, Border.STYLE_SOLID); - Color color = ColorPeer.fromString(colorString); - - return new Border.Side(size, color, style); - } catch (NoSuchElementException ex) { - throw new SerialException("Unable to parse border side value: " + value, ex); - } - } - /** * @see nextapp.echo.app.serial.SerialPropertyPeer#toProperty(Context, * Class, org.w3c.dom.Element) @@ -157,7 +185,7 @@ public Object toProperty(Context context, Class objectClass, Element propertyEle return new Border(sides); } } - + /** * @see nextapp.echo.app.serial.SerialPropertyPeer#toXml(nextapp.echo.app.util.Context, * java.lang.Class, org.w3c.dom.Element, java.lang.Object) @@ -168,19 +196,6 @@ public void toXml(Context context, Class objectClass, Element propertyElement, O propertyElement.setAttribute("t", (serialContext.getFlags() & SerialContext.FLAG_RENDER_SHORT_NAMES) == 0 ? "Border" : "BO"); Border border = (Border) propertyValue; - if (border.isMultisided()) { - Element borderElement = serialContext.getDocument().createElement("b"); - Border.Side[] sides = border.getSides(); - for (int i = 0; i < sides.length; ++i) { - if (sides[i] == null) { - borderElement.setAttribute(borderSideAttributeNames[i], ""); - } else { - borderElement.setAttribute(borderSideAttributeNames[i], toString(sides[i])); - } - } - propertyElement.appendChild(borderElement); - } else { - propertyElement.appendChild(serialContext.getDocument().createTextNode(toString(border))); - } + propertyElement.appendChild(toNode(context, border)); } }
42d43310ecb03895bc327bdc788375fde57b5f2d
drools
JBRULES-527: adding primitive support to indexing--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@7158 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-
a
https://github.com/kiegroup/drools
diff --git a/drools-core/src/main/java/org/drools/base/evaluators/ArrayFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/ArrayFactory.java index 66fa281998a..67ec1c422e6 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/ArrayFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/ArrayFactory.java @@ -101,9 +101,21 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "Array =="; } + } static class ArrayNotEqualEvaluator extends BaseEvaluator { @@ -124,7 +136,7 @@ public boolean evaluate(final Extractor extractor, final Object value1 = extractor.getValue( object1 ); final Object value2 = object2.getValue(); if ( value1 == null ) { - return value2 == null; + return value2 != null; } return !value1.equals( value2 ); } @@ -133,7 +145,7 @@ public boolean evaluateCachedRight(final VariableContextEntry context, final Object left) { final Object value = context.declaration.getExtractor().getValue( left ); if ( value == null ) { - return ((ObjectVariableContextEntry) context).right == null; + return ((ObjectVariableContextEntry) context).right != null; } return !value.equals( ((ObjectVariableContextEntry) context).right ); } @@ -142,11 +154,22 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, final Object right) { final Object value = context.extractor.getValue( right ); if ( ((ObjectVariableContextEntry) context).left == null ) { - return value == null; + return value != null; } return !((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 != null; + } + return !value1.equals( value2 ); + } + public String toString() { return "Array !="; } @@ -169,34 +192,34 @@ public boolean evaluate(final Extractor extractor, final FieldValue object2) { final Object value = object2.getValue(); final Object[] array = (Object[]) extractor.getValue( object1 ); - - if ( Arrays.binarySearch( array, - value ) == -1 ) { - return false; - } - return true; + return Arrays.binarySearch( array, + value ) != -1; } public boolean evaluateCachedRight(final VariableContextEntry context, final Object left) { final Object value = context.declaration.getExtractor().getValue( left ); final Object[] array = (Object[]) ((ObjectVariableContextEntry) context).right; - if ( Arrays.binarySearch( array, - value ) == -1 ) { - return false; - } - return true; + return Arrays.binarySearch( array, + value ) != -1; } public boolean evaluateCachedLeft(final VariableContextEntry context, final Object right) { final Object value = ((ObjectVariableContextEntry) context).left; final Object[] array = (Object[]) context.extractor.getValue( right ); - if ( Arrays.binarySearch( array, - value ) == -1 ) { - return false; - } - return true; + return Arrays.binarySearch( array, + value ) != -1; + } + + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value = extractor.getValue( object2 ); + final Object[] array = (Object[]) extractor.getValue( object1 ); + + return Arrays.binarySearch( array, + value ) != -1 ; } public String toString() { diff --git a/drools-core/src/main/java/org/drools/base/evaluators/BigDecimalFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/BigDecimalFactory.java index 10195cfbac7..91114ce6ff8 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/BigDecimalFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/BigDecimalFactory.java @@ -103,9 +103,21 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "BigDecimal =="; } + } static class BigDecimalNotEqualEvaluator extends BaseEvaluator { @@ -149,6 +161,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return !((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 != null; + } + return !value1.equals( value2 ); + } + public String toString() { return "BigDecimal !="; } @@ -185,6 +208,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) < 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigDecimal comp = (BigDecimal) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) < 0; + } + public String toString() { return "BigDecimal <"; } @@ -221,6 +251,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) <= 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigDecimal comp = (BigDecimal) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) <= 0; + } + public String toString() { return "BigDecimal <="; } @@ -257,6 +294,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) > 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigDecimal comp = (BigDecimal) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) > 0; + } + public String toString() { return "BigDecimal >"; } @@ -293,6 +337,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) >= 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigDecimal comp = (BigDecimal) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) >= 0; + } + public String toString() { return "BigDecimal >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/BigIntegerFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/BigIntegerFactory.java index d689acb07cf..c809c1ff841 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/BigIntegerFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/BigIntegerFactory.java @@ -103,6 +103,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "BigInteger =="; } @@ -149,6 +160,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return !((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "BigInteger !="; } @@ -185,6 +207,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) < 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigInteger comp = (BigInteger) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) < 0; + } + public String toString() { return "BigInteger <"; } @@ -221,6 +250,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) <= 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigInteger comp = (BigInteger) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) <= 0; + } + public String toString() { return "BigInteger <="; } @@ -257,6 +293,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) > 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigInteger comp = (BigInteger) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) > 0; + } + public String toString() { return "BigInteger >"; } @@ -293,6 +336,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) >= 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final BigInteger comp = (BigInteger) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) >= 0; + } + public String toString() { return "BigInteger >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/BooleanFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/BooleanFactory.java index 53db9a6ba47..04aa9ee4bd4 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/BooleanFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/BooleanFactory.java @@ -80,9 +80,16 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getBooleanValue( object2 ) == ((BooleanVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getBooleanValue( object1 ) == extractor.getBooleanValue( object2 ); + } + public String toString() { return "Boolean =="; } + } static class BooleanNotEqualEvaluator extends BaseEvaluator { @@ -113,6 +120,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getBooleanValue( object2 ) != ((BooleanVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getBooleanValue( object1 ) != extractor.getBooleanValue( object2 ); + } + public String toString() { return "Boolean !="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/ByteFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/ByteFactory.java index 208db1e1cca..9ca7b31128a 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/ByteFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/ByteFactory.java @@ -88,9 +88,16 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left == context.extractor.getByteValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getByteValue( object1 ) == extractor.getByteValue( object2 ); + } + public String toString() { return "Byte =="; } + } static class ByteNotEqualEvaluator extends BaseEvaluator { @@ -121,6 +128,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left != context.extractor.getByteValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getByteValue( object1 ) != extractor.getByteValue( object2 ); + } + public String toString() { return "Byte !="; } @@ -154,6 +167,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getByteValue( right ) < ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getByteValue( object1 ) < extractor.getByteValue( object2 ); + } + public String toString() { return "Byte <"; } @@ -187,6 +206,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getByteValue( right ) <= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getByteValue( object1 ) <= extractor.getByteValue( object2 ); + } + public String toString() { return "Byte <="; } @@ -220,6 +245,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getByteValue( right ) > ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getByteValue( object1 ) > extractor.getByteValue( object2 ); + } + public String toString() { return "Byte >"; } @@ -253,6 +284,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getByteValue( right ) >= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getByteValue( object1 ) >= extractor.getByteValue( object2 ); + } + public String toString() { return "Byte >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/CharacterFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/CharacterFactory.java index 37876d93458..67366e30807 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/CharacterFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/CharacterFactory.java @@ -88,6 +88,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left == context.extractor.getCharValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getCharValue( object1 ) == extractor.getCharValue( object2 ); + } + public String toString() { return "Character =="; } @@ -121,6 +127,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left != context.extractor.getCharValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getCharValue( object1 ) != extractor.getCharValue( object2 ); + } + public String toString() { return "Character !="; } @@ -154,6 +166,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getCharValue( right ) <((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getCharValue( object1 ) < extractor.getCharValue( object2 ); + } + public String toString() { return "Character <"; } @@ -187,6 +205,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getCharValue( right ) <= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getCharValue( object1 ) <= extractor.getCharValue( object2 ); + } + public String toString() { return "Character <="; } @@ -220,6 +244,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getCharValue( right ) > ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getCharValue( object1 ) > extractor.getCharValue( object2 ); + } + public String toString() { return "Character >"; } @@ -253,6 +283,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getCharValue( right ) >= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getCharValue( object1 ) >= extractor.getCharValue( object2 ); + } + public String toString() { return "Character >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/DateFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/DateFactory.java index bb22ef9eb4a..5391489f24a 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/DateFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/DateFactory.java @@ -131,9 +131,21 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return value1.compareTo( getRightDate( value2 ) ) == 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Date value1 = (Date) extractor.getValue( object1 ); + final Date value2 = (Date) extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.compareTo( value2 ) == 0; + } + public String toString() { return "Date =="; } + } static class DateNotEqualEvaluator extends BaseEvaluator { @@ -188,6 +200,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return value1.compareTo( getRightDate( value2 ) ) != 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Date value1 = (Date) extractor.getValue( object1 ); + final Date value2 = (Date) extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.compareTo( value2 ) != 0; + } + public String toString() { return "Date !="; } @@ -227,6 +250,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return getRightDate( value2 ).compareTo( value1 ) < 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Date value1 = (Date) extractor.getValue( object1 ); + final Date value2 = (Date) extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.compareTo( value2 ) < 0; + } + public String toString() { return "Date <"; } @@ -266,6 +300,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return getRightDate( value2 ).compareTo( value1 ) <= 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Date value1 = (Date) extractor.getValue( object1 ); + final Date value2 = (Date) extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.compareTo( value2 ) <= 0; + } + public String toString() { return "Date <="; } @@ -305,6 +350,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return getRightDate( value2 ).compareTo( value1 ) > 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Date value1 = (Date) extractor.getValue( object1 ); + final Date value2 = (Date) extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.compareTo( value2 ) > 0; + } + public String toString() { return "Date >"; } @@ -344,6 +400,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return getRightDate( value2 ).compareTo( value1 ) >= 0; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Date value1 = (Date) extractor.getValue( object1 ); + final Date value2 = (Date) extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.compareTo( value2 ) >= 0; + } + public String toString() { return "Date >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/DoubleFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/DoubleFactory.java index 088340dde7d..45d61d91c2c 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/DoubleFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/DoubleFactory.java @@ -91,6 +91,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((DoubleVariableContextEntry) context).left == context.extractor.getDoubleValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getDoubleValue( object1 ) == extractor.getDoubleValue( object2 ); + } + public String toString() { return "Double =="; } @@ -127,6 +134,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((DoubleVariableContextEntry) context).left != context.extractor.getDoubleValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getDoubleValue( object1 ) != extractor.getDoubleValue( object2 ); + } + public String toString() { return "Double !="; } @@ -163,6 +177,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getDoubleValue( right ) < ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getDoubleValue( object1 ) < extractor.getDoubleValue( object2 ); + } + public String toString() { return "Double <"; } @@ -199,6 +220,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getDoubleValue( right ) <= ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getDoubleValue( object1 ) <= extractor.getDoubleValue( object2 ); + } + public String toString() { return "Double <="; } @@ -235,6 +263,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getDoubleValue( right ) > ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getDoubleValue( object1 ) > extractor.getDoubleValue( object2 ); + } + public String toString() { return "Double >"; } @@ -271,6 +306,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getDoubleValue( right ) >= ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getDoubleValue( object1 ) >= extractor.getDoubleValue( object2 ); + } + public String toString() { return "Double >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/FactTemplateFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/FactTemplateFactory.java index 7433a9070b4..f1be3da3e8c 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/FactTemplateFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/FactTemplateFactory.java @@ -82,17 +82,6 @@ public boolean evaluate(final Extractor extractor, return value1.equals( value2 ); } - public boolean evaluate(final FieldValue object1, - final Extractor extractor, - final Object object2) { - final Object value1 = object1.getValue(); - final Object value2 = extractor.getValue( object2 ); - if ( value1 == null ) { - return value2 == null; - } - return value1.equals( value2 ); - } - public boolean evaluateCachedRight(final VariableContextEntry context, final Object left) { final Object value = context.declaration.getExtractor().getValue( left ); @@ -111,9 +100,21 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "FactTemplate =="; } + } static class FactTemplateNotEqualEvaluator extends BaseEvaluator { @@ -139,17 +140,6 @@ public boolean evaluate(final Extractor extractor, return !value1.equals( value2 ); } - public boolean evaluate(final FieldValue object1, - final Extractor extractor, - final Object object2) { - final Object value1 = object1.getValue(); - final Object value2 = extractor.getValue( object2 ); - if ( value1 == null ) { - return value2 != null; - } - return !value1.equals( value2 ); - } - public boolean evaluateCachedRight(final VariableContextEntry context, final Object left) { final Object value = context.declaration.getExtractor().getValue( left ); @@ -168,6 +158,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return !((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 != null; + } + return !value1.equals( value2 ); + } + public String toString() { return "FactTemplate !="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/FloatFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/FloatFactory.java index 0d698acc849..5dfd9f950d1 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/FloatFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/FloatFactory.java @@ -89,6 +89,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((DoubleVariableContextEntry) context).left == context.extractor.getFloatValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getFloatValue( object1 ) == extractor.getFloatValue( object2 ); + } + public String toString() { return "Float =="; } @@ -125,6 +132,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((DoubleVariableContextEntry) context).left != context.extractor.getFloatValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getFloatValue( object1 ) != extractor.getFloatValue( object2 ); + } + public String toString() { return "Float !="; } @@ -161,6 +175,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getFloatValue( right ) < ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getFloatValue( object1 ) < extractor.getFloatValue( object2 ); + } + public String toString() { return "Float <"; } @@ -197,6 +218,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getFloatValue( right ) <= ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getFloatValue( object1 ) <= extractor.getFloatValue( object2 ); + } + public String toString() { return "Float <="; } @@ -233,6 +261,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getFloatValue( right ) > ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getFloatValue( object1 ) > extractor.getFloatValue( object2 ); + } + public String toString() { return "Float >"; } @@ -269,6 +304,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getFloatValue( right ) >= ((DoubleVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + // TODO: we are not handling delta right now... maybe we should + return extractor.getFloatValue( object1 ) >= extractor.getFloatValue( object2 ); + } + public String toString() { return "Float >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/IntegerFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/IntegerFactory.java index 3fbd6c98cbb..c1ba19fce1a 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/IntegerFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/IntegerFactory.java @@ -88,6 +88,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getIntValue( object2 ) == ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getIntValue( object1 ) == extractor.getIntValue( object2 ); + } + public String toString() { return "Integer =="; } @@ -122,6 +128,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getIntValue( object2 ) != ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getIntValue( object1 ) != extractor.getIntValue( object2 ); + } + public String toString() { return "Integer !="; } @@ -155,6 +167,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getIntValue( right ) < ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getIntValue( object1 ) < extractor.getIntValue( object2 ); + } + public String toString() { return "Integer <"; } @@ -188,6 +206,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getIntValue( right ) <= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getIntValue( object1 ) <= extractor.getIntValue( object2 ); + } + public String toString() { return "Integer <="; } @@ -221,6 +245,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getIntValue( right ) > ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getIntValue( object1 ) > extractor.getIntValue( object2 ); + } + public String toString() { return "Integer >"; } @@ -254,6 +284,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getIntValue( right ) >= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getIntValue( object1 ) >= extractor.getIntValue( object2 ); + } + public String toString() { return "Integer >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/LongFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/LongFactory.java index e612d57b527..b48381f021b 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/LongFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/LongFactory.java @@ -88,6 +88,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left == context.extractor.getLongValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getLongValue( object1 ) == extractor.getLongValue( object2 ); + } + public String toString() { return "Long =="; } @@ -121,6 +127,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left != context.extractor.getLongValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getLongValue( object1 ) != extractor.getLongValue( object2 ); + } + public String toString() { return "Long !="; } @@ -154,6 +166,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getLongValue( right ) < ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getLongValue( object1 ) < extractor.getLongValue( object2 ); + } + public String toString() { return "Long <"; } @@ -187,6 +205,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getLongValue( right ) <= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getLongValue( object1 ) <= extractor.getLongValue( object2 ); + } + public String toString() { return "Long <="; } @@ -220,6 +244,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getLongValue( right ) > ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getLongValue( object1 ) > extractor.getLongValue( object2 ); + } + public String toString() { return "Long >"; } @@ -253,6 +283,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getLongValue( right ) >= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getLongValue( object1 ) >= extractor.getLongValue( object2 ); + } + public String toString() { return "Long >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/ObjectFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/ObjectFactory.java index a387a32554d..93b11b97dc2 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/ObjectFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/ObjectFactory.java @@ -118,6 +118,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "Object =="; } @@ -165,6 +176,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return !((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 != null; + } + return !value1.equals( value2 ); + } + public String toString() { return "Object !="; } @@ -198,6 +220,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) < 0; } + public boolean evaluate(final Extractor extractor, + final Object object1, + final Object object2) { + final Comparable comp = (Comparable) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) < 0; + } + public String toString() { return "Object <"; } @@ -234,6 +263,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) <= 0; } + public boolean evaluate(final Extractor extractor, + final Object object1, + final Object object2) { + final Comparable comp = (Comparable) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) <= 0; + } + public String toString() { return "Object <="; } @@ -270,6 +306,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) > 0; } + public boolean evaluate(final Extractor extractor, + final Object object1, + final Object object2) { + final Comparable comp = (Comparable) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) > 0; + } + public String toString() { return "Object >"; } @@ -306,6 +349,13 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return comp.compareTo( ((ObjectVariableContextEntry) context).left ) >= 0; } + public boolean evaluate(final Extractor extractor, + final Object object1, + final Object object2) { + final Comparable comp = (Comparable) extractor.getValue( object1 ); + return comp.compareTo( extractor.getValue( object2 ) ) >= 0; + } + public String toString() { return "Object >="; } @@ -345,6 +395,14 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return col.contains( value ); } + public boolean evaluate(final Extractor extractor, + final Object object1, + final Object object2) { + final Object value = extractor.getValue( object2 ); + final Collection col = (Collection) extractor.getValue( object1 ); + return col.contains( value ); + } + public String toString() { return "Object contains"; } @@ -384,6 +442,14 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return !col.contains( value ); } + public boolean evaluate(final Extractor extractor, + final Object object1, + final Object object2) { + final Object value = extractor.getValue( object2 ); + final Collection col = (Collection) extractor.getValue( object1 ); + return !col.contains( value ); + } + public String toString() { return "Object excludes"; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/ShortFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/ShortFactory.java index 349ac21ad6f..8cf3857c0ee 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/ShortFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/ShortFactory.java @@ -88,6 +88,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left == context.extractor.getShortValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getShortValue( object1 ) == extractor.getShortValue( object2 ); + } + public String toString() { return "Short =="; } @@ -121,6 +127,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((LongVariableContextEntry) context).left != context.extractor.getShortValue( right ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getShortValue( object1 ) != extractor.getShortValue( object2 ); + } + public String toString() { return "Short !="; } @@ -154,6 +166,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getShortValue( right ) < ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getShortValue( object1 ) < extractor.getShortValue( object2 ); + } + public String toString() { return "Short <"; } @@ -187,6 +205,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getShortValue( right ) <= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getShortValue( object1 ) <= extractor.getShortValue( object2 ); + } + public String toString() { return "Boolean <="; } @@ -220,6 +244,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getShortValue( right ) > ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getShortValue( object1 ) > extractor.getShortValue( object2 ); + } + public String toString() { return "Short >"; } @@ -253,6 +283,12 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return context.extractor.getShortValue( right ) >= ((LongVariableContextEntry) context).left; } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + return extractor.getShortValue( object1 ) >= extractor.getShortValue( object2 ); + } + public String toString() { return "Short >="; } diff --git a/drools-core/src/main/java/org/drools/base/evaluators/StringFactory.java b/drools-core/src/main/java/org/drools/base/evaluators/StringFactory.java index 200b416fe05..1c0828f1321 100644 --- a/drools-core/src/main/java/org/drools/base/evaluators/StringFactory.java +++ b/drools-core/src/main/java/org/drools/base/evaluators/StringFactory.java @@ -102,9 +102,21 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return ((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 == null; + } + return value1.equals( value2 ); + } + public String toString() { return "String =="; } + } static class StringNotEqualEvaluator extends BaseEvaluator { @@ -148,6 +160,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return !((ObjectVariableContextEntry) context).left.equals( value ); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return value2 != null; + } + return !value1.equals( value2 ); + } + public String toString() { return "String !="; } @@ -194,6 +217,17 @@ public boolean evaluateCachedLeft(final VariableContextEntry context, return value.matches( (String) ((ObjectVariableContextEntry) context).left); } + public boolean evaluate(Extractor extractor, + Object object1, + Object object2) { + final Object value1 = extractor.getValue( object1 ); + final Object value2 = extractor.getValue( object2 ); + if ( value1 == null ) { + return false; + } + return ((String) value1).matches( (String) value2 ); + } + public String toString() { return "String !="; } diff --git a/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java b/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java index f96650b940f..03cfde7a75d 100644 --- a/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java +++ b/drools-core/src/main/java/org/drools/common/DefaultBetaConstraints.java @@ -185,7 +185,8 @@ public BetaMemory createBetaMemory() { final Constraint constraint = (Constraint) entry.getObject(); final VariableConstraint variableConstraint = (VariableConstraint) constraint; final FieldIndex index = new FieldIndex( variableConstraint.getFieldExtractor(), - variableConstraint.getRequiredDeclarations()[0] ); + variableConstraint.getRequiredDeclarations()[0], + variableConstraint.getEvaluator()); list.add( index ); entry = (LinkedListEntry) entry.getNext(); } diff --git a/drools-core/src/main/java/org/drools/spi/Evaluator.java b/drools-core/src/main/java/org/drools/spi/Evaluator.java index 898aaa03d3e..f4c188a3ac1 100644 --- a/drools-core/src/main/java/org/drools/spi/Evaluator.java +++ b/drools-core/src/main/java/org/drools/spi/Evaluator.java @@ -46,6 +46,10 @@ public interface Evaluator public boolean evaluate(Extractor extractor, Object object1, FieldValue value); + + public boolean evaluate(Extractor extractor, + Object object1, + Object object2); public boolean evaluateCachedLeft(VariableContextEntry context, Object object1); diff --git a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java index a815e2ab06d..de1c42baedb 100644 --- a/drools-core/src/main/java/org/drools/util/AbstractHashTable.java +++ b/drools-core/src/main/java/org/drools/util/AbstractHashTable.java @@ -8,6 +8,7 @@ import org.drools.common.InternalFactHandle; import org.drools.reteoo.ReteTuple; import org.drools.rule.Declaration; +import org.drools.spi.Evaluator; import org.drools.spi.FieldExtractor; public abstract class AbstractHashTable @@ -72,7 +73,7 @@ protected void resize(final int newCapacity) { next = entry.getNext(); final int index = indexOf( entry.hashCode(), - newTable.length ); + newTable.length ); entry.setNext( newTable[index] ); newTable[index] = entry; @@ -179,7 +180,9 @@ protected int indexOf(final int hashCode, public abstract Entry getBucket(Object object); - public interface ObjectComparator extends Serializable { + public interface ObjectComparator + extends + Serializable { public int hashCodeOf(Object object); public int rehash(int hashCode); @@ -242,6 +245,8 @@ public void reset() { public static class InstanceEquals implements ObjectComparator { + + private static final long serialVersionUID = 1835792402650440794L; public static ObjectComparator INSTANCE = new InstanceEquals(); public static ObjectComparator getInstance() { @@ -273,6 +278,8 @@ public boolean equal(final Object object1, public static class EqualityEquals implements ObjectComparator { + + private static final long serialVersionUID = 8004812231695147987L; public static ObjectComparator INSTANCE = new EqualityEquals(); public static ObjectComparator getInstance() { @@ -297,9 +304,9 @@ private EqualityEquals() { public boolean equal(final Object object1, final Object object2) { - if ( object1 == null ) { - return object2 == null; - } + if ( object1 == null ) { + return object2 == null; + } return object1.equals( object2 ); } } @@ -307,6 +314,9 @@ public boolean equal(final Object object1, public static class FactEntry implements Entry { + + private static final long serialVersionUID = 1776798977330980128L; + public InternalFactHandle handle; public int hashCode; @@ -356,13 +366,15 @@ public boolean equals(final Object object) { return (object == this) || (this.handle == ((FactEntry) object).handle); } } - + public static class FieldIndex { public FieldExtractor extractor; public Declaration declaration; + public Evaluator evaluator; public FieldIndex(final FieldExtractor extractor, - final Declaration declaration) { + final Declaration declaration, + final Evaluator evaluator) { super(); this.extractor = extractor; this.declaration = declaration; @@ -375,8 +387,12 @@ public Declaration getDeclaration() { public FieldExtractor getExtractor() { return this.extractor; } + + public Evaluator getEvaluator() { + return this.evaluator; + } } - + public static interface Index { public int hashCodeOf(ReteTuple tuple); @@ -387,200 +403,176 @@ public boolean equal(Object object, public boolean equal(ReteTuple tuple1, ReteTuple tuple2); - + public boolean equal(Object object1, - Object object2); + Object object2); } public static class SingleIndex implements Index { - private FieldExtractor extractor; - private Declaration declaration; - private int startResult; + private FieldExtractor extractor; + private Declaration declaration; + private Evaluator evaluator; - private ObjectComparator comparator; + private int startResult; public SingleIndex(final FieldIndex[] indexes, - final int startResult, - final ObjectComparator comparator) { + final int startResult) { this.startResult = startResult; this.extractor = indexes[0].extractor; this.declaration = indexes[0].declaration; + this.evaluator = indexes[0].evaluator; - this.comparator = comparator; } public int hashCodeOf(final Object object) { int hashCode = this.startResult; hashCode = TupleIndexHashTable.PRIME * hashCode + this.extractor.getHashCode( object ); - return this.comparator.rehash( hashCode ); + return rehash( hashCode ); } public int hashCodeOf(final ReteTuple tuple) { int hashCode = this.startResult; hashCode = TupleIndexHashTable.PRIME * hashCode + this.declaration.getHashCode( tuple.get( this.declaration ).getObject() ); - return this.comparator.rehash( hashCode ); + return rehash( hashCode ); } public boolean equal(final Object object1, final ReteTuple tuple) { - final Object value1 = this.extractor.getValue( object1 ); - final Object value2 = this.declaration.getValue( tuple.get( this.declaration ).getObject() ); + final Object object2 = tuple.get( this.declaration ).getObject(); - return this.comparator.equal( value1, - value2 ); + return this.evaluator.evaluate( this.extractor, + object1, + object2 ); } - + public boolean equal(final Object object1, final Object object2) { - final Object value1 = this.extractor.getValue( object1 ); - final Object value2 = this.extractor.getValue( object2 ); - - return this.comparator.equal( value1, - value2 ); - } + return this.evaluator.evaluate( this.extractor, + object1, + object2 ); + } public boolean equal(final ReteTuple tuple1, final ReteTuple tuple2) { - final Object value1 = this.declaration.getValue( tuple1.get( this.declaration ).getObject() ); - final Object value2 = this.declaration.getValue( tuple2.get( this.declaration ).getObject() ); - return this.comparator.equal( value1, - value2 ); + final Object object1 = tuple1.get( this.declaration ).getObject(); + final Object object2 = tuple2.get( this.declaration ).getObject(); + return this.evaluator.evaluate( this.extractor, + object1, + object2 ); } + + public int rehash(int h) { + h += ~(h << 9); + h ^= (h >>> 14); + h += (h << 4); + h ^= (h >>> 10); + return h; + } + } public static class DoubleCompositeIndex implements Index { - private FieldIndex index0; - private FieldIndex index1; - - private int startResult; + private FieldIndex index0; + private FieldIndex index1; - private ObjectComparator comparator; + private int startResult; public DoubleCompositeIndex(final FieldIndex[] indexes, - final int startResult, - final ObjectComparator comparator) { + final int startResult) { this.startResult = startResult; this.index0 = indexes[0]; this.index1 = indexes[1]; - this.comparator = comparator; } public int hashCodeOf(final Object object) { int hashCode = this.startResult; - int hash = this.index0.extractor.getHashCode( object ); - hashCode = TupleIndexHashTable.PRIME * hashCode + hash; - - hash = this.index1.extractor.getHashCode( object ); - hashCode = TupleIndexHashTable.PRIME * hashCode + hash; + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index0.extractor.getHashCode( object ); + hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.extractor.getHashCode( object ); - return this.comparator.rehash( hashCode ); + return rehash( hashCode ); } public int hashCodeOf(final ReteTuple tuple) { int hashCode = this.startResult; hashCode = TupleIndexHashTable.PRIME * hashCode + this.index0.declaration.getHashCode( tuple.get( this.index0.declaration ).getObject() ); - hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.declaration.getHashCode( tuple.get( this.index1.declaration ).getObject() ); - return this.comparator.rehash( hashCode ); + return rehash( hashCode ); } public boolean equal(final Object object1, final ReteTuple tuple) { - Object value1 = this.index0.extractor.getValue( object1 ); - Object value2 = this.index0.declaration.getValue( tuple.get( this.index0.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index1.extractor.getValue( object1 ); - value2 = this.index1.declaration.getValue( tuple.get( this.index1.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } + Object object12 = tuple.get( this.index0.declaration ).getObject(); + Object object22 = tuple.get( this.index1.declaration ).getObject(); - return true; + return this.index0.evaluator.evaluate( this.index0.extractor, + object1, + object12 ) && this.index1.evaluator.evaluate( this.index1.extractor, + object1, + object22 ); } public boolean equal(final ReteTuple tuple1, final ReteTuple tuple2) { - Object value1 = this.index0.declaration.getValue( tuple1.get( this.index0.declaration ).getObject() ); - Object value2 = this.index0.declaration.getValue( tuple2.get( this.index0.declaration ).getObject() ); + Object object11 = tuple1.get( this.index0.declaration ).getObject(); + Object object12 = tuple2.get( this.index0.declaration ).getObject(); - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index1.declaration.getValue( tuple1.get( this.index1.declaration ).getObject() ); - value2 = this.index1.declaration.getValue( tuple2.get( this.index1.declaration ).getObject() ); + Object object21 = tuple1.get( this.index1.declaration ).getObject(); + Object object22 = tuple2.get( this.index1.declaration ).getObject(); - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - return true; + return this.index0.evaluator.evaluate( this.index0.extractor, + object11, + object12 ) && this.index1.evaluator.evaluate( this.index1.extractor, + object21, + object22 ); } - + public boolean equal(final Object object1, final Object object2) { - Object value1 = this.index0.extractor.getValue( object1 ); - Object value2 = this.index0.extractor.getValue( object2 ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index1.extractor.getValue( object1 ); - value2 = this.index1.extractor.getValue( object2 ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } + return this.index0.evaluator.evaluate( this.index0.extractor, + object1, + object2 ) && this.index1.evaluator.evaluate( this.index1.extractor, + object1, + object2 ); + } - return true; - } + public int rehash(int h) { + h += ~(h << 9); + h ^= (h >>> 14); + h += (h << 4); + h ^= (h >>> 10); + return h; + } } public static class TripleCompositeIndex implements Index { - private FieldIndex index0; - private FieldIndex index1; - private FieldIndex index2; + private FieldIndex index0; + private FieldIndex index1; + private FieldIndex index2; private int startResult; - private ObjectComparator comparator; - public TripleCompositeIndex(final FieldIndex[] indexes, - final int startResult, - final ObjectComparator comparator) { + final int startResult) { this.startResult = startResult; this.index0 = indexes[0]; this.index1 = indexes[1]; this.index2 = indexes[2]; - this.comparator = comparator; } public int hashCodeOf(final Object object) { @@ -590,7 +582,7 @@ public int hashCodeOf(final Object object) { hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.extractor.getHashCode( object );; hashCode = TupleIndexHashTable.PRIME * hashCode + this.index2.extractor.getHashCode( object );; - return this.comparator.rehash( hashCode ); + return rehash( hashCode ); } public int hashCodeOf(final ReteTuple tuple) { @@ -600,94 +592,60 @@ public int hashCodeOf(final ReteTuple tuple) { hashCode = TupleIndexHashTable.PRIME * hashCode + this.index1.declaration.getHashCode( tuple.get( this.index1.declaration ).getObject() ); hashCode = TupleIndexHashTable.PRIME * hashCode + this.index2.declaration.getHashCode( tuple.get( this.index2.declaration ).getObject() ); - return this.comparator.rehash( hashCode ); + return rehash( hashCode ); } public boolean equal(final Object object1, final ReteTuple tuple) { - Object value1 = this.index0.extractor.getValue( object1 ); - Object value2 = this.index0.declaration.getValue( tuple.get( this.index0.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } + Object object12 = tuple.get( this.index0.declaration ).getObject(); + Object object22 = tuple.get( this.index1.declaration ).getObject(); + Object object32 = tuple.get( this.index2.declaration ).getObject(); - value1 = this.index1.extractor.getValue( object1 ); - value2 = this.index1.declaration.getValue( tuple.get( this.index1.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index2.extractor.getValue( object1 ); - value2 = this.index2.declaration.getValue( tuple.get( this.index2.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - return true; + return this.index0.evaluator.evaluate( this.index0.extractor, + object1, + object12 ) && this.index1.evaluator.evaluate( this.index1.extractor, + object1, + object22 ) && this.index2.evaluator.evaluate( this.index2.extractor, + object1, + object32 ); } public boolean equal(final ReteTuple tuple1, final ReteTuple tuple2) { - Object value1 = this.index0.declaration.getValue( tuple1.get( this.index0.declaration ).getObject() ); - Object value2 = this.index0.declaration.getValue( tuple2.get( this.index0.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index1.declaration.getValue( tuple1.get( this.index1.declaration ).getObject() ); - value2 = this.index1.declaration.getValue( tuple2.get( this.index1.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index2.declaration.getValue( tuple1.get( this.index2.declaration ).getObject() ); - value2 = this.index2.declaration.getValue( tuple2.get( this.index2.declaration ).getObject() ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - return true; + Object object11 = tuple1.get( this.index0.declaration ).getObject(); + Object object12 = tuple2.get( this.index0.declaration ).getObject(); + Object object21 = tuple1.get( this.index1.declaration ).getObject(); + Object object22 = tuple2.get( this.index1.declaration ).getObject(); + Object object31 = tuple1.get( this.index2.declaration ).getObject(); + Object object32 = tuple2.get( this.index2.declaration ).getObject(); + + return this.index0.evaluator.evaluate( this.index0.extractor, + object11, + object12 ) && this.index1.evaluator.evaluate( this.index1.extractor, + object21, + object22 ) && this.index2.evaluator.evaluate( this.index2.extractor, + object31, + object32 ); } - + public boolean equal(final Object object1, final Object object2) { - Object value1 = this.index0.extractor.getValue( object1 ); - Object value2 = this.index0.extractor.getValue( object2 ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index1.extractor.getValue( object1 ); - value2 = this.index1.extractor.getValue( object2 ); - - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } - - value1 = this.index2.extractor.getValue( object1 ); - value2 = this.index2.extractor.getValue( object2 ); + return this.index0.evaluator.evaluate( this.index0.extractor, + object1, + object2 ) && this.index1.evaluator.evaluate( this.index1.extractor, + object1, + object2 ) && this.index2.evaluator.evaluate( this.index2.extractor, + object1, + object2 ); + } - if ( !this.comparator.equal( value1, - value2 ) ) { - return false; - } + public int rehash(int h) { + h += ~(h << 9); + h ^= (h >>> 14); + h += (h << 4); + h ^= (h >>> 10); + return h; + } - return true; - } - } + } } \ No newline at end of file diff --git a/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java b/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java index a182bd7a6be..828d7e65c60 100644 --- a/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java +++ b/drools-core/src/main/java/org/drools/util/FactHandleIndexHashTable.java @@ -6,13 +6,13 @@ import org.drools.common.InternalFactHandle; import org.drools.reteoo.FactHandleMemory; import org.drools.reteoo.ReteTuple; -import org.drools.rule.Declaration; -import org.drools.spi.FieldExtractor; -import org.drools.util.ObjectHashMap.ObjectEntry; public class FactHandleIndexHashTable extends AbstractHashTable implements FactHandleMemory { + + private static final long serialVersionUID = -6033183838054653227L; + public static final int PRIME = 31; private int startResult; @@ -37,7 +37,7 @@ public FactHandleIndexHashTable(final int capacity, this.startResult = FactHandleIndexHashTable.PRIME; for ( int i = 0, length = index.length; i < length; i++ ) { - this.startResult += FactHandleIndexHashTable.PRIME * this.startResult + index[i].getExtractor().getIndex(); + this.startResult = FactHandleIndexHashTable.PRIME * this.startResult + index[i].getExtractor().getIndex(); } switch ( index.length ) { @@ -45,18 +45,15 @@ public FactHandleIndexHashTable(final int capacity, throw new IllegalArgumentException( "FieldIndexHashTable cannot use an index[] of length 0" ); case 1 : this.index = new SingleIndex( index, - this.startResult, - this.comparator ); + this.startResult); break; case 2 : this.index = new DoubleCompositeIndex( index, - this.startResult, - this.comparator ); + this.startResult ); break; case 3 : this.index = new TripleCompositeIndex( index, - this.startResult, - this.comparator ); + this.startResult ); break; default : throw new IllegalArgumentException( "FieldIndexHashTable cannot use an index[] of length great than 3" ); @@ -250,6 +247,8 @@ public int size() { public static class FieldIndexEntry implements Entry { + + private static final long serialVersionUID = -577270475161063671L; private Entry next; private FactEntry first; private final int hashCode; diff --git a/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java b/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java index 79353043490..c78960acaf1 100644 --- a/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java +++ b/drools-core/src/main/java/org/drools/util/TupleIndexHashTable.java @@ -4,17 +4,15 @@ package org.drools.util; import org.drools.common.InternalFactHandle; -import org.drools.reteoo.FactHandleMemory; import org.drools.reteoo.ReteTuple; import org.drools.reteoo.TupleMemory; -import org.drools.rule.Column; -import org.drools.rule.Declaration; -import org.drools.spi.FieldExtractor; -import org.drools.util.ObjectHashMap.ObjectEntry; public class TupleIndexHashTable extends AbstractHashTable implements TupleMemory { + + private static final long serialVersionUID = -6214772340195061306L; + public static final int PRIME = 31; private int startResult; @@ -47,18 +45,15 @@ public TupleIndexHashTable(final int capacity, throw new IllegalArgumentException( "FieldIndexHashTable cannot use an index[] of length 0" ); case 1 : this.index = new SingleIndex( index, - this.startResult, - this.comparator ); + this.startResult); break; case 2 : this.index = new DoubleCompositeIndex( index, - this.startResult, - this.comparator ); + this.startResult); break; case 3 : this.index = new TripleCompositeIndex( index, - this.startResult, - this.comparator ); + this.startResult); break; default : throw new IllegalArgumentException( "FieldIndexHashTable cannot use an index[] of length great than 3" ); @@ -243,6 +238,8 @@ public int size() { public static class FieldIndexEntry implements Entry { + + private static final long serialVersionUID = 8160842495541574574L; private Entry next; private ReteTuple first; private final int hashCode;
a00785136b533e563a9ca408aeaed500f7ad2295
hbase
HBASE-8351 Minor typo in Bytes- IllegalArgumentException throw (Raymond Liu)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1468291 13f79535-47bb-0310-9956-ffa450edef68-
c
https://github.com/apache/hbase
diff --git a/hbase-common/src/main/java/org/apache/hadoop/hbase/util/Bytes.java b/hbase-common/src/main/java/org/apache/hadoop/hbase/util/Bytes.java index 30fa08bb6040..edd75a903883 100644 --- a/hbase-common/src/main/java/org/apache/hadoop/hbase/util/Bytes.java +++ b/hbase-common/src/main/java/org/apache/hadoop/hbase/util/Bytes.java @@ -1404,7 +1404,7 @@ public static Iterable<byte[]> iterateOnSplits( throw new IllegalArgumentException("b <= a"); } if (num <= 0) { - throw new IllegalArgumentException("num cannot be < 0"); + throw new IllegalArgumentException("num cannot be <= 0"); } byte [] prependHeader = {1, 0}; final BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
5dbaebf86e6584b403f75e3502d68a45abc82544
Valadoc
libvaladoc/html: Sort subnamespaces in navis
a
https://github.com/GNOME/vala/
diff --git a/src/libvaladoc/html/basicdoclet.vala b/src/libvaladoc/html/basicdoclet.vala index d2ab882ee9..75a52cfef4 100755 --- a/src/libvaladoc/html/basicdoclet.vala +++ b/src/libvaladoc/html/basicdoclet.vala @@ -257,7 +257,11 @@ public abstract class Valadoc.Html.BasicDoclet : Api.Visitor, Doclet { } protected void fetch_subnamespace_names (Api.Node node, Gee.ArrayList<Namespace> namespaces) { - foreach (Api.Node child in node.get_children_by_type (Api.NodeType.NAMESPACE)) { + Gee.ArrayList<Api.Node> sorted_list = new Gee.ArrayList<Api.Node> (); + sorted_list.add_all (node.get_children_by_type (Api.NodeType.NAMESPACE)); + sorted_list.sort (); + + foreach (Api.Node child in sorted_list) { namespaces.add ((Namespace) child); this.fetch_subnamespace_names (child, namespaces); }
e24b71e70035f9a9baf7ec19c279311eceec31a9
spring-framework
Shutdown Reactor env when relay handler is- stopped--The Reactor Environment (that's used by the TcpClient) manages a-number of threads. To ensure that these threads are cleaned up-Environment.shutdown() must be called when the Environment is no-longer needed.-
c
https://github.com/spring-projects/spring-framework
diff --git a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java index 2e1d31d42947..ef2d9eaaea48 100644 --- a/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java +++ b/spring-websocket/src/main/java/org/springframework/web/messaging/stomp/support/StompRelayPubSubMessageHandler.java @@ -73,6 +73,8 @@ public class StompRelayPubSubMessageHandler extends AbstractPubSubMessageHandler private MessageConverter payloadConverter; + private Environment environment; + private TcpClient<String, String> tcpClient; private final Map<String, RelaySession> relaySessions = new ConcurrentHashMap<String, RelaySession>(); @@ -181,9 +183,9 @@ public boolean isRunning() { @Override public void start() { synchronized (this.lifecycleMonitor) { - + this.environment = new Environment(); this.tcpClient = new TcpClient.Spec<String, String>(NettyTcpClient.class) - .using(new Environment()) + .using(this.environment) .codec(new DelimitedCodec<String, String>((byte) 0, true, StandardCodecs.STRING_CODEC)) .connect(this.relayHost, this.relayPort) .get(); @@ -214,6 +216,7 @@ public void stop() { this.running = false; try { this.tcpClient.close().await(5000, TimeUnit.MILLISECONDS); + this.environment.shutdown(); } catch (InterruptedException e) { // ignore
9cbf3e289bfad5b7aa2d235b6e696ccee56f299b
restlet-framework-java
- Fixed HTTPS issues in internal connector.--
c
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.ext.ssl/src/org/restlet/ext/ssl/internal/SslConnection.java b/modules/org.restlet.ext.ssl/src/org/restlet/ext/ssl/internal/SslConnection.java index 5ea1accecf..4746a2c5fb 100644 --- a/modules/org.restlet.ext.ssl/src/org/restlet/ext/ssl/internal/SslConnection.java +++ b/modules/org.restlet.ext.ssl/src/org/restlet/ext/ssl/internal/SslConnection.java @@ -269,6 +269,10 @@ public SSLSession getSslSession() { private void handleSslHandshake() throws IOException { HandshakeStatus hs = getSslHandshakeStatus(); + if (getLogger().isLoggable(Level.FINER)) { + getLogger().log(Level.FINER, "Handling SSL handshake: " + hs); + } + if (hs != HandshakeStatus.NOT_HANDSHAKING) { switch (getSslHandshakeStatus()) { case FINISHED: @@ -300,6 +304,11 @@ private void handleSslHandshake() throws IOException { * @throws IOException */ public synchronized void handleSslResult() throws IOException { + if (getLogger().isLoggable(Level.FINER)) { + getLogger().log(Level.FINER, + "Handling SSL result: " + getSslEngineStatus()); + } + switch (getSslEngineStatus()) { case BUFFER_OVERFLOW: if (getLogger().isLoggable(Level.FINER)) { @@ -398,10 +407,8 @@ public void run() { } if (getLogger().isLoggable(Level.FINER)) { - getLogger().log( - Level.FINER, - "Done running delegated tasks. " - + SslConnection.this.toString()); + getLogger().log(Level.FINER, + "Done running delegated tasks"); } try { @@ -410,6 +417,8 @@ public void run() { getLogger().log(Level.INFO, "Unable to handle SSL handshake", e); } + + getHelper().getController().wakeup(); } }); }
93ab055d17bf4663c439424a40a053d7b0255aa7
kotlin
Change Signature: Do not fail on unresolved- PsiMethod -KT-9535 Fixed--
c
https://github.com/JetBrains/kotlin
diff --git a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeSignatureUsageProcessor.java b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeSignatureUsageProcessor.java index c566ef20f2a96..f6b990ffd6901 100644 --- a/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeSignatureUsageProcessor.java +++ b/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/JetChangeSignatureUsageProcessor.java @@ -442,7 +442,7 @@ private static void findSAMUsages(ChangeInfo changeInfo, Set<UsageInfo> result) if (((PsiMethod) method).getContainingClass() == null) return; FunctionDescriptor methodDescriptor = JavaResolutionUtils.getJavaMethodDescriptor((PsiMethod) method); - assert methodDescriptor != null; + if (methodDescriptor == null) return; DeclarationDescriptor containingDescriptor = methodDescriptor.getContainingDeclaration(); if (!(containingDescriptor instanceof JavaClassDescriptor)) return;
5ffdaf3dd274a6c08216151965c72073a1031e21
barchart$barchart-feed-ddf
ServiceDatabaseDDF added functionality
p
https://github.com/barchart/barchart-feed-ddf
diff --git a/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/LocalInstDefDB.java b/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/LocalInstDefDB.java deleted file mode 100644 index 11206be17..000000000 --- a/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/LocalInstDefDB.java +++ /dev/null @@ -1,317 +0,0 @@ -package com.barchart.feed.ddf.instrument.provider; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.zip.ZipException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -import com.barchart.proto.buf.inst.InstrumentDefinition; - -public class LocalInstDefDB { - - private static final Logger log = LoggerFactory.getLogger(LocalInstDefDB.class); - - //private static final String INST_DEF = "instrumentDef.zip"; - private static final String URL = "https://s3.amazonaws.com/instrument-def/active/instrumentDef.zip"; - private static final String S3_URL = "https://s3.amazonaws.com/instrument-def/"; - - private static final String DB_DIR = "persist"; - - private static final DateTimeFormatter TIMESTAMP_FORMATTER = - DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"); - - private final LocalInstrumentDBMap map; - - public LocalInstDefDB(final String resourceRoot) throws ZipException, IOException { - - if(resourceRoot == null || resourceRoot.length() == 0) { - throw new IllegalArgumentException("Resource root is empty"); - } - - final File resourceFolder = new File(resourceRoot); - if(!resourceFolder.isDirectory()) { - throw new IllegalArgumentException("Resource root must be a directory"); - } - - final File dbFolder = getDBFolder(resourceFolder); - - DB_STATUS dbStatus = DB_STATUS.getStatus(dbFolder); - INST_DEF_STATUS instDefStatus = INST_DEF_STATUS.getStatus(resourceFolder); - - switch(instDefStatus) { - - case NONE: - default: - log.error("No local instrument def file and unable to reach remote"); - throw new IllegalStateException("No local instrument def file and unable to reach remote"); - - case NO_LOCAL_HAS_REMOTE: - log.warn("No local insttrument def file, pulling from remote"); - case NEED_UPDATE: - log.debug("Populating local instrument def file from remote"); - populateLocalInstDef(resourceRoot); - case HAS_LOCAL_NO_REMOTE: - case GOOD: - - if(dbStatus == DB_STATUS.GOOD) { - log.debug(""); - map = new LocalInstrumentDBMap(dbFolder); - } else { - map = new LocalInstrumentDBMap(dbFolder, getLocalInstDef(resourceFolder)); - } - - break; - - } - - } - - /** - * - * @param key - * @return - */ - public boolean containsKey(final String key) { - return map.containsKey(key); - } - - /** - * - * @param key - * @return - */ - public InstrumentDefinition getValue(final String key) { - return map.get(key); - } - - /** - * - * @param key - * @param value - */ - public void put(final String key, final InstrumentDefinition value) { - map.put(key, value); - } - - /** - * - * @return - */ - public int size() { - return map.size(); - } - - static String getLatestS3InstDefVersion() { - - try { - - DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - - Element element = db.parse(S3_URL).getDocumentElement(); - NodeList nodeList = element.getChildNodes(); - - List<DateTime> versionTimes = new ArrayList<DateTime>(); - - for(int i = 0; i < nodeList.getLength(); i++) { - - if(nodeList.item(i).getNodeName().equals("Contents")) { - - NodeList contentNodes = nodeList.item(i).getChildNodes(); - for(int n = 0; n < contentNodes.getLength(); n++) { - - if(contentNodes.item(n).getNodeName().equals("LastModified")) { - versionTimes.add(TIMESTAMP_FORMATTER.parseDateTime( - contentNodes.item(n).getTextContent().split("\\.")[0])); - } - - } - - } - } - - Collections.sort(versionTimes); - - return TIMESTAMP_FORMATTER.print(versionTimes.get(versionTimes.size() - 1)); - - } catch (Exception e) { - - log.error("Exception getting latest s3 version {}" + e.getMessage()); - - return null; - } - - } - - /* Returns null if none found at resource location */ - static String getLocalInstDefVersion(final File resourceFolder) { - - String version = null; - final File[] files = resourceFolder.listFiles(new ZipFilter()); - final List<DateTime> versions = new ArrayList<DateTime>(); - for(final File file : files) { - - try { - - versions.add(TIMESTAMP_FORMATTER.parseDateTime(file.getName().split("\\.")[0])); - - } catch (Exception e) { - // ignore failed parses - } - - } - - if(!versions.isEmpty()) { - Collections.sort(versions); - version = versions.get(versions.size() - 1).toString(TIMESTAMP_FORMATTER); - } - - return version; - - } - - File getLocalInstDef(final File resourceFolder) { - - File version = null; - final File[] files = resourceFolder.listFiles(new ZipFilter()); - final List<File> versions = new ArrayList<File>(); - for(final File file : files) { - - try { - - TIMESTAMP_FORMATTER.parseDateTime(file.getName().split("\\.")[0]); - versions.add(file); - - } catch (Exception e) { - // ignore failed parses - } - - } - - if(!versions.isEmpty()) { - Collections.sort(versions); - version = versions.get(versions.size() - 1); - } - - return version; - - } - - static void populateLocalInstDef(final String resourceRoot) throws IOException { - - final URL instDefURL = new URL(URL); - URLConnection conn = instDefURL.openConnection(); - - InputStream in = conn.getInputStream(); - - final String latestVersionName = getLatestS3InstDefVersion(); - File outFile = new File(resourceRoot + "/" + latestVersionName + ".zip"); - FileOutputStream out = new FileOutputStream(outFile); - - byte[] b = new byte[1024]; - int count; - while ((count = in.read(b)) >= 0) { - out.write(b, 0, count); - } - out.flush(); out.close(); in.close(); - - } - - static boolean hasDB(final File dbFolder) { - - for(final String file : dbFolder.list()) { - if(file.toLowerCase().endsWith(".jdb")) { - return true; - } - } - - return false; - } - - private File getDBFolder(final File resourceFolder) { - - final File db = new File(resourceFolder, DB_DIR); - - if(!db.exists()) { - db.mkdir(); - } - - return db; - } - - private static class ZipFilter implements FileFilter { - - @Override - public boolean accept(final File pathname) { - return pathname.getName().toLowerCase().endsWith(".zip"); - } - - } - - private enum DB_STATUS { - - NONE, GOOD; - - public static DB_STATUS getStatus(final File dbFolder) { - - if(hasDB(dbFolder)) { - return GOOD; - } - - return NONE; - } - - } - - private enum INST_DEF_STATUS { - - NONE, - NO_LOCAL_HAS_REMOTE, - HAS_LOCAL_NO_REMOTE, - NEED_UPDATE, GOOD; - - public static INST_DEF_STATUS getStatus(final File resourceFolder) { - - final String localInstDefVersion = getLocalInstDefVersion(resourceFolder); - final String latestRemoteInstDefVersion = getLatestS3InstDefVersion(); - - if(localInstDefVersion == null && latestRemoteInstDefVersion == null) { - return NONE; - } - - if(localInstDefVersion == null) { - return NO_LOCAL_HAS_REMOTE; - } - - if(latestRemoteInstDefVersion == null) { - return HAS_LOCAL_NO_REMOTE; - } - - if(localInstDefVersion.equals(latestRemoteInstDefVersion)) { - return GOOD; - } else { - return NEED_UPDATE; - } - - } - - } - -} diff --git a/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/ServiceDatabaseDDF.java b/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/ServiceDatabaseDDF.java index 9274180fb..39ed64897 100644 --- a/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/ServiceDatabaseDDF.java +++ b/barchart-feed-ddf-instrument/src/main/java/com/barchart/feed/ddf/instrument/provider/ServiceDatabaseDDF.java @@ -1,10 +1,13 @@ package com.barchart.feed.ddf.instrument.provider; import java.util.Collection; +import java.util.HashMap; import java.util.Map; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Future; +import java.util.concurrent.FutureTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,7 +31,47 @@ public ServiceDatabaseDDF(final LocalInstrumentDBMap map) { } @Override - public Instrument lookup(CharSequence symbol) { + public Instrument lookup(final CharSequence symbol) { + + return lookupBase(symbol); + + } + + @Override + public Future<Instrument> lookupAsync(final CharSequence symbol) { + return new FutureTask<Instrument>(new SymbolLookup(symbol)); + } + + @Override + public Map<CharSequence, Instrument> lookup( + final Collection<? extends CharSequence> symbols) { + + final Map<CharSequence, Instrument> result = + new HashMap<CharSequence, Instrument>(); + + // Currently just doing serial lookup + for(final CharSequence symbol : symbols) { + result.put(symbol, lookupBase(symbol)); + } + + return result; + } + + @Override + public Map<CharSequence, Future<Instrument>> lookupAsync( + final Collection<? extends CharSequence> symbols) { + + final Map<CharSequence, Future<Instrument>> result = + new HashMap<CharSequence, Future<Instrument>>(); + + for(final CharSequence symbol : symbols) { + result.put(symbol, new FutureTask<Instrument>(new SymbolLookup(symbol))); + } + + return result; + } + + private Instrument lookupBase(final CharSequence symbol) { if(symbol == null || symbol.length() == 0) { return Instrument.NULL_INSTRUMENT; @@ -50,27 +93,23 @@ public Instrument lookup(CharSequence symbol) { cache.put(symbol, instrument); return instrument; } - - } - - @Override - public Future<Instrument> lookupAsync(CharSequence symbol) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map<CharSequence, Instrument> lookup( - Collection<? extends CharSequence> symbols) { - // TODO Auto-generated method stub - return null; } + + private class SymbolLookup implements Callable<Instrument> { - @Override - public Map<CharSequence, Future<Instrument>> lookupAsync( - Collection<? extends CharSequence> symbols) { - // TODO Auto-generated method stub - return null; + private final CharSequence symbol; + + public SymbolLookup(final CharSequence symbol) { + this.symbol = symbol; + } + + @Override + public Instrument call() throws Exception { + + return lookupBase(symbol); + + } + } }
c0425336ce948f9cedf3915bc0336fbd726cf070
cyberfox$jbidwatcher
Split out the bidding and buying related functionality. Still need to update the Snipe class to refer to the bidder, not the core server. git-svn-id: svn://svn.jbidwatcher.com/jbidwatcher/trunk@60 b1acfa68-eb39-11db-b167-a3a8cd6b847e
p
https://github.com/cyberfox/jbidwatcher
diff --git a/src/com/jbidwatcher/auction/server/AuctionServer.java b/src/com/jbidwatcher/auction/server/AuctionServer.java index 70fd1c74..dab8861b 100644 --- a/src/com/jbidwatcher/auction/server/AuctionServer.java +++ b/src/com/jbidwatcher/auction/server/AuctionServer.java @@ -151,7 +151,7 @@ public enum ParseErrors { * * @return - The full text of the auction from the server, or null if it wasn't found. */ - protected abstract StringBuffer getAuction(AuctionEntry ae, String id); + public abstract StringBuffer getAuction(AuctionEntry ae, String id); /** * @brief Get the current time inline with the current thread. This will diff --git a/src/com/jbidwatcher/auction/server/ebay/ebayBidder.java b/src/com/jbidwatcher/auction/server/ebay/ebayBidder.java new file mode 100644 index 00000000..4e89f26e --- /dev/null +++ b/src/com/jbidwatcher/auction/server/ebay/ebayBidder.java @@ -0,0 +1,389 @@ +package com.jbidwatcher.auction.server.ebay; + +import com.jbidwatcher.auction.server.LoginManager; +import com.jbidwatcher.auction.server.BadBidException; +import com.jbidwatcher.auction.server.AuctionServerInterface; +import com.jbidwatcher.auction.server.AuctionServer; +import com.jbidwatcher.auction.AuctionEntry; +import com.jbidwatcher.auction.Auctions; +import com.jbidwatcher.util.html.JHTML; +import com.jbidwatcher.util.http.CookieJar; +import com.jbidwatcher.util.http.Http; +import com.jbidwatcher.util.Externalized; +import com.jbidwatcher.util.ErrorManagement; +import com.jbidwatcher.config.JConfig; +import com.jbidwatcher.config.JBConfig; +import com.jbidwatcher.queue.MQFactory; +import com.jbidwatcher.Constants; + +import java.net.URLConnection; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.List; +import java.util.HashMap; +import java.util.Iterator; + +/** + * Created by IntelliJ IDEA. +* User: mrs +* Date: Feb 26, 2007 +* Time: 1:38:12 AM +* To change this template use File | Settings | File Templates. +*/ +public class ebayBidder { + private static final String srcMatch = "(?i)src=\"([^\"]*?)\""; + private static Pattern srcPat = Pattern.compile(srcMatch); + + private LoginManager mLogin; + private HashMap<String, Integer> mResultHash = null; + private String mBidResultRegex = null; + + private Pattern mFindBidResult; + + public ebayBidder(LoginManager login) { + mLogin = login; + /** + * Build a simple hashtable of results that bidding might get. + * Not the greatest solution, but it's working okay. A better one + * would be great. + */ + if(mResultHash == null) { + mResultHash = new HashMap<String, Integer>(); + mResultHash.put("you are not permitted to bid on their listings.", AuctionServer.BID_ERROR_BANNED); + mResultHash.put("the item is no longer available because the auction has ended.", AuctionServer.BID_ERROR_ENDED); + mResultHash.put("cannot proceed", AuctionServer.BID_ERROR_CANNOT); + mResultHash.put("problem with bid amount", AuctionServer.BID_ERROR_AMOUNT); + mResultHash.put("your bid must be at least ", AuctionServer.BID_ERROR_TOO_LOW); + mResultHash.put("you have been outbid by another bidder", AuctionServer.BID_ERROR_OUTBID); + mResultHash.put("your bid is confirmed!", AuctionServer.BID_DUTCH_CONFIRMED); + mResultHash.put("you are bidding on this multiple item auction", AuctionServer.BID_DUTCH_CONFIRMED); + mResultHash.put("you are the high bidder on all items you bid on", AuctionServer.BID_DUTCH_CONFIRMED); + mResultHash.put("you are the current high bidder", AuctionServer.BID_WINNING); + mResultHash.put("you purchased the item", AuctionServer.BID_WINNING); + mResultHash.put("the reserve price has not been met", AuctionServer.BID_ERROR_RESERVE_NOT_MET); + mResultHash.put("your new total must be higher than your current total", AuctionServer.BID_ERROR_TOO_LOW_SELF); + mResultHash.put("this exceeds or is equal to your current bid", AuctionServer.BID_ERROR_TOO_LOW_SELF); + mResultHash.put("you bought this item", AuctionServer.BID_BOUGHT_ITEM); + mResultHash.put("you committed to buy", AuctionServer.BID_BOUGHT_ITEM); + mResultHash.put("congratulations! you won!", AuctionServer.BID_BOUGHT_ITEM); + mResultHash.put("account suspended", AuctionServer.BID_ERROR_ACCOUNT_SUSPENDED); + mResultHash.put("to enter a higher maximum bid, please enter", AuctionServer.BID_ERROR_TOO_LOW_SELF); + mResultHash.put("you are registered in a country to which the seller doesn.t ship.", AuctionServer.BID_ERROR_WONT_SHIP); + mResultHash.put("this seller has set buyer requirements for this item and only sells to buyers who meet those requirements.", AuctionServer.BID_ERROR_REQUIREMENTS_NOT_MET); + // mResultHash.put("You are the current high bidder", new Integer(BID_SELFWIN)); + } + + //"If you want to submit another bid, your new total must be higher than your current total"; + StringBuffer superRegex = new StringBuffer("("); + Iterator<String> it = mResultHash.keySet().iterator(); + while (it.hasNext()) { + String key = it.next(); + superRegex.append(key); + if(it.hasNext()) { + superRegex.append('|'); + } else { + superRegex.append(')'); + } + } + mBidResultRegex = new StringBuilder().append("(?i)").append(superRegex).toString(); + mFindBidResult = Pattern.compile(mBidResultRegex); + mResultHash.put("sign in", AuctionServer.BID_ERROR_CANT_SIGN_IN); + } + + public JHTML.Form getBidForm(CookieJar cj, AuctionEntry inEntry, com.jbidwatcher.util.Currency inCurr, int inQuant) throws BadBidException { + String bidRequest = Externalized.getString("ebayServer.protocol") + Externalized.getString("ebayServer.bidHost") + Externalized.getString("ebayServer.V3file"); + String bidInfo; + if(inEntry.isDutch()) { + bidInfo = Externalized.getString("ebayServer.bidCmd") + "&co_partnerid=" + Externalized.getString("ebayServer.itemCGI") + inEntry.getIdentifier() + + "&fb=2" + Externalized.getString("ebayServer.quantCGI") + inQuant + + Externalized.getString("ebayServer.bidCGI") + inCurr.getValue(); + } else { + bidInfo = Externalized.getString("ebayServer.bidCmd") + "&co_partnerid=" + Externalized.getString("ebayServer.itemCGI") + inEntry.getIdentifier() + "&fb=2" + + Externalized.getString("ebayServer.bidCGI") + inCurr.getValue(); + } + StringBuffer loadedPage = null; + JHTML htmlDocument = null; + + try { + String pageName = bidRequest + '?' + bidInfo; + boolean checked_signon = false; + boolean checked_reminder = false; + boolean done = false; + boolean post = false; + while (!done) { + done = true; + + if(JConfig.debugging) inEntry.setLastStatus("Loading bid request..."); + URLConnection huc = cj.getAllCookiesFromPage(pageName, null, post); + post = false; + // We failed to load, entirely. Punt. + if (huc == null) return null; + + loadedPage = Http.receivePage(huc); + // We failed to load. Punt. + if (loadedPage == null) return null; + + htmlDocument = new JHTML(loadedPage); + JHTML.Form bidForm = htmlDocument.getFormWithInput("key"); + if(bidForm != null) { + if(JConfig.debugging) inEntry.setLastStatus("Done loading bid request, got form..."); + return bidForm; + } + + if(!checked_signon) { + checked_signon = true; + String signOn = htmlDocument.getFirstContent(); + if (signOn != null) { + ErrorManagement.logDebug("Checking sign in as bid key load failed!"); + if (signOn.equalsIgnoreCase("Sign In")) { + // This means we somehow failed to keep the login in place. Bad news, in the middle of a snipe. + ErrorManagement.logDebug("Being prompted again for sign in, retrying."); + if(JConfig.debugging) inEntry.setLastStatus("Not done loading bid request, got re-login request..."); + mLogin.resetCookie(); + mLogin.getNecessaryCookie(true); + if(JConfig.debugging) inEntry.setLastStatus("Done re-logging in, retrying load bid request."); + done = false; + } + } + } + + if(!checked_reminder) { + if(htmlDocument.grep("Buying.Reminder") != null) { + JHTML.Form continueForm = htmlDocument.getFormWithInput("firedFilterId"); + if(continueForm != null) { + inEntry.setLastStatus("Trying to 'continue' for the actual bid."); + pageName = continueForm.getCGI(); + pageName = pageName.replaceFirst("%[A-F][A-F0-9]%A0", "%A0"); + post = false; + } + checked_reminder = true; + } + } + } + } catch (IOException e) { + ErrorManagement.handleException("Failure to get the bid key! BID FAILURE!", e); + } + + if(htmlDocument != null) { + String signOn = htmlDocument.getFirstContent(); + if(signOn != null && signOn.equalsIgnoreCase("Sign In")) throw new BadBidException("sign in", AuctionServerInterface.BID_ERROR_CANT_SIGN_IN); + String errMsg = htmlDocument.grep(mBidResultRegex); + if(errMsg != null) { + Matcher bidMatch = mFindBidResult.matcher(errMsg); + bidMatch.find(); + String matched_error = bidMatch.group().toLowerCase(); + throw new BadBidException(matched_error, mResultHash.get(matched_error)); + } + } + + if(JConfig.debugging) inEntry.setLastStatus("Failed to bid. 'Show Last Error' from context menu to see the failure page from the bid attempt."); + inEntry.setErrorPage(loadedPage); + + // We don't recognize this error. Damn. Log it and freak. + ErrorManagement.logFile(bidInfo, loadedPage); + return null; + } + + public int buy(AuctionEntry ae, int quantity) { + String buyRequest = "http://offer.ebay.com/ws/eBayISAPI.dll?MfcISAPICommand=BinConfirm&fb=1&co_partnerid=&item=" + ae.getIdentifier() + "&quantity=" + quantity; + + // This updates the cookies with the affiliate information, if it's not a test auction. + if(ae.getTitle().toLowerCase().indexOf("test") == -1) { + if(JBConfig.doAffiliate(ae.getEndDate().getTime())) { + // Ignoring the result as it's just called to trigger affiliate mode. + ae.getServer().getAuction(ae, ae.getIdentifier()); + } + } + + StringBuffer sb; + + try { + sb = mLogin.getNecessaryCookie(false).getAllCookiesAndPage(buyRequest, null, false); + JHTML doBuy = new JHTML(sb); + JHTML.Form buyForm = doBuy.getFormWithInput("uiid"); + + if (buyForm != null) { + buyForm.delInput("BIN_button"); + CookieJar cj = mLogin.getNecessaryCookie(false); + StringBuffer loadedPage = cj.getAllCookiesAndPage(buyForm.getCGI(), buyRequest, false); + if (loadedPage == null) return AuctionServerInterface.BID_ERROR_CONNECTION; + return handlePostBidBuyPage(cj, loadedPage, buyForm, ae); + } + } catch (CookieJar.CookieException ignored) { + return AuctionServerInterface.BID_ERROR_CONNECTION; + } catch (UnsupportedEncodingException uee) { + ErrorManagement.handleException("UTF-8 not supported locally, can't URLEncode buy form.", uee); + return AuctionServerInterface.BID_ERROR_CONNECTION; + } + + ae.setErrorPage(sb); + return AuctionServerInterface.BID_ERROR_UNKNOWN; + } + + /** + * @brief Perform the entire bidding process on an item. + * + * @param inEntry - The item to bid on. + * @param inBid - The amount to bid. + * @param inQuantity - The number of items to bid on. + * + * @return - A bid response code, or BID_ERROR_UNKNOWN if we can't + * figure out what happened. + */ + public int bid(AuctionEntry inEntry, com.jbidwatcher.util.Currency inBid, int inQuantity) { + Auctions.startBlocking(); + if(JConfig.queryConfiguration("sound.enable", "false").equals("true")) MQFactory.getConcrete("sfx").enqueue("/audio/bid.mp3"); + + try { + // If it's not closing within the next minute, then go ahead and try for the affiliate mode. + if(inEntry.getEndDate().getTime() > (System.currentTimeMillis() + Constants.ONE_MINUTE)) { + safeGetAffiliate(mLogin.getNecessaryCookie(false), inEntry); + } + } catch (CookieJar.CookieException ignore) { + // We don't care that much about connection refused in this case. + } + JHTML.Form bidForm; + + try { + bidForm = getBidForm(mLogin.getNecessaryCookie(false), inEntry, inBid, inQuantity); + } catch(BadBidException bbe) { + Auctions.endBlocking(); + return bbe.getResult(); + } + + if (bidForm != null) { + int rval = placeFinalBid(mLogin.getNecessaryCookie(false), bidForm, inEntry, inBid, inQuantity); + Auctions.endBlocking(); + return rval; + } + ErrorManagement.logMessage("Bad/nonexistent key read in bid, or connection failure!"); + + Auctions.endBlocking(); + return AuctionServerInterface.BID_ERROR_UNKNOWN; + } + + public int placeFinalBid(CookieJar cj, JHTML.Form bidForm, AuctionEntry inEntry, com.jbidwatcher.util.Currency inBid, int inQuantity) { + String bidRequest = Externalized.getString("ebayServer.protocol") + Externalized.getString("ebayServer.bidHost") + Externalized.getString("ebayServer.V3file"); + String bidInfo = Externalized.getString("ebayServer.bidCmd") + Externalized.getString("ebayServer.itemCGI") + inEntry.getIdentifier() + + Externalized.getString("ebayServer.quantCGI") + inQuantity + + Externalized.getString("ebayServer.bidCGI") + inBid.getValue(); + String bidURL = bidRequest + '?' + bidInfo; + + bidForm.delInput("BIN_button"); + StringBuffer loadedPage = null; + + // This SHOULD be POSTed, but only works if sent with GET. + try { + if (JConfig.debugging) inEntry.setLastStatus("Submitting bid form."); + loadedPage = cj.getAllCookiesAndPage(bidForm.getCGI(), bidURL, false); + if (JConfig.debugging) inEntry.setLastStatus("Done submitting bid form."); + } catch (UnsupportedEncodingException uee) { + ErrorManagement.handleException("UTF-8 not supported locally, can't URLEncode bid form.", uee); + } catch (CookieJar.CookieException ignored) { + return AuctionServerInterface.BID_ERROR_CONNECTION; + } + + if (loadedPage == null) { + return AuctionServerInterface.BID_ERROR_CONNECTION; + } + return handlePostBidBuyPage(cj, loadedPage, bidForm, inEntry); + } + + public void safeGetAffiliate(CookieJar cj, AuctionEntry inEntry) throws CookieJar.CookieException { + // This updates the cookies with the affiliate information, if it's not a test auction. + if(inEntry.getTitle().toLowerCase().indexOf("test") == -1) { + if(JBConfig.doAffiliate(inEntry.getEndDate().getTime())) { + if(JConfig.debugging) inEntry.setLastStatus("Loading item..."); + inEntry.getServer().getAuction(inEntry, inEntry.getIdentifier()); + if(JConfig.debugging) inEntry.setLastStatus("Done loading item..."); + } + } + } + + private int handlePostBidBuyPage(CookieJar cj, StringBuffer loadedPage, JHTML.Form bidForm, AuctionEntry inEntry) { + if(JConfig.debugging) inEntry.setLastStatus("Loading post-bid data."); + JHTML htmlDocument = new JHTML(loadedPage); + + if(htmlDocument.grep("Buying.Reminder") != null) { + JHTML.Form continueForm = htmlDocument.getFormWithInput("firedFilterId"); + if(continueForm != null) { + try { + inEntry.setLastStatus("Trying to 'continue' to the bid result page."); + String cgi = continueForm.getCGI(); + // For some reason, the continue page represents the currency as + // separated from the amount with a '0xA0' character. When encoding, + // this becomes...broken somehow, and adds an extra character, which + // does not work when bidding. + cgi = cgi.replaceFirst("%[A-F][A-F0-9]%A0", "%A0"); + URLConnection huc = cj.getAllCookiesFromPage(cgi, null, false); + // We failed to load, entirely. Punt. + if (huc == null) return AuctionServerInterface.BID_ERROR_CONNECTION; + + loadedPage = Http.receivePage(huc); + // We failed to load. Punt. + if (loadedPage == null) return AuctionServerInterface.BID_ERROR_CONNECTION; + + htmlDocument = new JHTML(loadedPage); + } catch(Exception ignored) { + return AuctionServerInterface.BID_ERROR_CONNECTION; + } + } + } + + String errMsg = htmlDocument.grep(mBidResultRegex); + if (errMsg != null) { + Matcher bidMatch = mFindBidResult.matcher(errMsg); + bidMatch.find(); + String matched_error = bidMatch.group().toLowerCase(); + Integer bidResult = mResultHash.get(matched_error); + + if(inEntry.getTitle().toLowerCase().indexOf("test") == -1) { + if(JBConfig.doAffiliate(inEntry.getEndDate().getTime())) { + List<String> images = htmlDocument.getAllImages(); + for (String tag : images) { + Matcher tagMatch = srcPat.matcher(tag); + if (tagMatch.find()) { + int retry = 2; + do { + StringBuffer result = null; + try { + result = mLogin.getNecessaryCookie(false).getAllCookiesAndPage(tagMatch.group(1), "http://offer.ebay.com/ws/eBayISAPI.dll", false); + } catch (CookieJar.CookieException ignored) { + // Ignore connection refused errors. + } + if (result == null) { + retry--; + } else { + retry = 0; + } + } while (retry != 0); + } + } + } + } + + if(JConfig.debugging) inEntry.setLastStatus("Done loading post-bid data."); + + if(bidResult != null) return bidResult; + } + + // Skipping the userID and Password, so this can be submitted as + // debugging info. + bidForm.setText("user", "HIDDEN"); + bidForm.setText("pass", "HIDDEN"); + String safeBidInfo = ""; + try { + safeBidInfo = bidForm.getCGI(); + } catch(UnsupportedEncodingException uee) { + ErrorManagement.handleException("UTF-8 not supported locally, can't URLEncode CGI for debugging.", uee); + } + + if(JConfig.debugging) inEntry.setLastStatus("Failed to load post-bid data. 'Show Last Error' from context menu to see the failure page from the post-bid page."); + inEntry.setErrorPage(loadedPage); + + ErrorManagement.logFile(safeBidInfo, loadedPage); + return AuctionServerInterface.BID_ERROR_UNKNOWN; + } +} diff --git a/src/com/jbidwatcher/auction/server/ebay/ebayServer.java b/src/com/jbidwatcher/auction/server/ebay/ebayServer.java index 0ba7ba45..83cb875c 100644 --- a/src/com/jbidwatcher/auction/server/ebay/ebayServer.java +++ b/src/com/jbidwatcher/auction/server/ebay/ebayServer.java @@ -19,8 +19,8 @@ import com.jbidwatcher.queue.*; import com.jbidwatcher.util.html.JHTML; import com.jbidwatcher.util.http.CookieJar; -import com.jbidwatcher.util.http.Http; import com.jbidwatcher.util.*; +import com.jbidwatcher.util.Currency; import com.jbidwatcher.search.Searcher; import com.jbidwatcher.search.SearchManager; import com.jbidwatcher.search.SearchManagerInterface; @@ -32,11 +32,8 @@ import com.jbidwatcher.xml.XMLElement; import javax.swing.*; -import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.io.FileNotFoundException; import java.net.URL; -import java.net.URLConnection; import java.util.*; import java.util.List; import java.util.regex.Matcher; @@ -56,10 +53,6 @@ public final class ebayServer extends AuctionServer implements MessageQueue.List private String userCfgString = null; private String passCfgString = null; - private HashMap<String, Integer> mResultHash = null; - private String mBidResultRegex = null; - private Pattern mFindBidResult; - /** @noinspection FieldAccessedSynchronizedAndUnsynchronized*/ private eBayTimeQueueManager _etqm; private Searcher mMyeBay = null; @@ -86,6 +79,7 @@ public final class ebayServer extends AuctionServer implements MessageQueue.List private GregorianCalendar mCal; private final static ebayCurrencyTables sCurrencies = new ebayCurrencyTables(); private final ebayCleaner mCleaner; + private ebayBidder mBidder; public boolean equals(Object o) { if (this == o) return true; @@ -431,56 +425,11 @@ public void messageAction(Object deQ) { public ebayServer() { userCfgString = getName() + ".user"; passCfgString = getName() + ".password"; - /** - * Build a simple hashtable of results that bidding might get. - * Not the greatest solution, but it's working okay. A better one - * would be great. - */ - if(mResultHash == null) { - mResultHash = new HashMap<String, Integer>(); - mResultHash.put("you are not permitted to bid on their listings.", BID_ERROR_BANNED); - mResultHash.put("the item is no longer available because the auction has ended.", BID_ERROR_ENDED); - mResultHash.put("cannot proceed", BID_ERROR_CANNOT); - mResultHash.put("problem with bid amount", BID_ERROR_AMOUNT); - mResultHash.put("your bid must be at least ", BID_ERROR_TOO_LOW); - mResultHash.put("you have been outbid by another bidder", BID_ERROR_OUTBID); - mResultHash.put("your bid is confirmed!", BID_DUTCH_CONFIRMED); - mResultHash.put("you are bidding on this multiple item auction", BID_DUTCH_CONFIRMED); - mResultHash.put("you are the high bidder on all items you bid on", BID_DUTCH_CONFIRMED); - mResultHash.put("you are the current high bidder", BID_WINNING); - mResultHash.put("you purchased the item", BID_WINNING); - mResultHash.put("the reserve price has not been met", BID_ERROR_RESERVE_NOT_MET); - mResultHash.put("your new total must be higher than your current total", BID_ERROR_TOO_LOW_SELF); - mResultHash.put("this exceeds or is equal to your current bid", BID_ERROR_TOO_LOW_SELF); - mResultHash.put("you bought this item", BID_BOUGHT_ITEM); - mResultHash.put("you committed to buy", BID_BOUGHT_ITEM); - mResultHash.put("congratulations! you won!", BID_BOUGHT_ITEM); - mResultHash.put("account suspended", BID_ERROR_ACCOUNT_SUSPENDED); - mResultHash.put("to enter a higher maximum bid, please enter", BID_ERROR_TOO_LOW_SELF); - mResultHash.put("you are registered in a country to which the seller doesn.t ship.", BID_ERROR_WONT_SHIP); - mResultHash.put("this seller has set buyer requirements for this item and only sells to buyers who meet those requirements.", BID_ERROR_REQUIREMENTS_NOT_MET); - // mResultHash.put("You are the current high bidder", new Integer(BID_SELFWIN)); - } - - //"If you want to submit another bid, your new total must be higher than your current total"; - StringBuffer superRegex = new StringBuffer("("); - Iterator<String> it = mResultHash.keySet().iterator(); - while (it.hasNext()) { - String key = it.next(); - superRegex.append(key); - if(it.hasNext()) { - superRegex.append('|'); - } else { - superRegex.append(')'); - } - } - mBidResultRegex = new StringBuilder().append("(?i)").append(superRegex).toString(); - mFindBidResult = Pattern.compile(mBidResultRegex); - mResultHash.put("sign in", BID_ERROR_CANT_SIGN_IN); mCleaner = new ebayCleaner(); mLogin = new ebayLoginManager(eBayServerName, getPassword(), getUserId()); mSearcher = new ebaySearches(mCleaner, mLogin); + mBidder = new ebayBidder(mLogin); _etqm = new eBayTimeQueueManager(); eQueue = new TimerHandler(_etqm); @@ -494,8 +443,9 @@ public ebayServer() { JConfig.registerListener(this); } - private static final String srcMatch = "(?i)src=\"([^\"]*?)\""; - private static Pattern srcPat = Pattern.compile(srcMatch); + public int buy(AuctionEntry ae, int quantity) { + return mBidder.buy(ae, quantity); + } /** * @brief Given a standard URL, strip it apart, and find the items @@ -539,6 +489,10 @@ public String extractIdentifierFromURLString(String urlStyle) { return null; } + public int bid(AuctionEntry inEntry, Currency inBid, int inQuantity) { + return mBidder.bid(inEntry, inBid, inQuantity); + } + /** * @brief Given a site-dependant item ID, get the string-form URL for that item. * @@ -635,303 +589,17 @@ private boolean allowAffiliate() { return false; } - public JHTML.Form getBidForm(CookieJar cj, AuctionEntry inEntry, com.jbidwatcher.util.Currency inCurr, int inQuant) throws BadBidException { - String bidRequest = Externalized.getString("ebayServer.protocol") + Externalized.getString("ebayServer.bidHost") + Externalized.getString("ebayServer.V3file"); - String bidInfo; - if(inEntry.isDutch()) { - bidInfo = Externalized.getString("ebayServer.bidCmd") + "&co_partnerid=" + Externalized.getString("ebayServer.itemCGI") + inEntry.getIdentifier() + - "&fb=2" + Externalized.getString("ebayServer.quantCGI") + inQuant + - Externalized.getString("ebayServer.bidCGI") + inCurr.getValue(); - } else { - bidInfo = Externalized.getString("ebayServer.bidCmd") + "&co_partnerid=" + Externalized.getString("ebayServer.itemCGI") + inEntry.getIdentifier() + "&fb=2" + - Externalized.getString("ebayServer.bidCGI") + inCurr.getValue(); - } - StringBuffer loadedPage = null; - JHTML htmlDocument = null; - - try { - String pageName = bidRequest + '?' + bidInfo; - boolean checked_signon = false; - boolean checked_reminder = false; - boolean done = false; - boolean post = false; - while (!done) { - done = true; - - if(JConfig.debugging) inEntry.setLastStatus("Loading bid request..."); - URLConnection huc = cj.getAllCookiesFromPage(pageName, null, post); - post = false; - // We failed to load, entirely. Punt. - if (huc == null) return null; - - loadedPage = Http.receivePage(huc); - // We failed to load. Punt. - if (loadedPage == null) return null; - - htmlDocument = new JHTML(loadedPage); - JHTML.Form bidForm = htmlDocument.getFormWithInput("key"); - if(bidForm != null) { - if(JConfig.debugging) inEntry.setLastStatus("Done loading bid request, got form..."); - return bidForm; - } - - if(!checked_signon) { - checked_signon = true; - String signOn = htmlDocument.getFirstContent(); - if (signOn != null) { - ErrorManagement.logDebug("Checking sign in as bid key load failed!"); - if (signOn.equalsIgnoreCase("Sign In")) { - // This means we somehow failed to keep the login in place. Bad news, in the middle of a snipe. - ErrorManagement.logDebug("Being prompted again for sign in, retrying."); - if(JConfig.debugging) inEntry.setLastStatus("Not done loading bid request, got re-login request..."); - mLogin.resetCookie(); - mLogin.getNecessaryCookie(true); - if(JConfig.debugging) inEntry.setLastStatus("Done re-logging in, retrying load bid request."); - done = false; - } - } - } - - if(!checked_reminder) { - if(htmlDocument.grep("Buying.Reminder") != null) { - JHTML.Form continueForm = htmlDocument.getFormWithInput("firedFilterId"); - if(continueForm != null) { - inEntry.setLastStatus("Trying to 'continue' for the actual bid."); - pageName = continueForm.getCGI(); - pageName = pageName.replaceFirst("%[A-F][A-F0-9]%A0", "%A0"); - post = false; - } - checked_reminder = true; - } - } - } - } catch (IOException e) { - ErrorManagement.handleException("Failure to get the bid key! BID FAILURE!", e); - } - - if(htmlDocument != null) { - String signOn = htmlDocument.getFirstContent(); - if(signOn != null && signOn.equalsIgnoreCase("Sign In")) throw new BadBidException("sign in", BID_ERROR_CANT_SIGN_IN); - String errMsg = htmlDocument.grep(mBidResultRegex); - if(errMsg != null) { - Matcher bidMatch = mFindBidResult.matcher(errMsg); - bidMatch.find(); - String matched_error = bidMatch.group().toLowerCase(); - throw new BadBidException(matched_error, mResultHash.get(matched_error)); - } - } - - if(JConfig.debugging) inEntry.setLastStatus("Failed to bid. 'Show Last Error' from context menu to see the failure page from the bid attempt."); - inEntry.setErrorPage(loadedPage); - - // We don't recognize this error. Damn. Log it and freak. - ErrorManagement.logFile(bidInfo, loadedPage); - return null; - } - - public int buy(AuctionEntry ae, int quantity) { - String buyRequest = "http://offer.ebay.com/ws/eBayISAPI.dll?MfcISAPICommand=BinConfirm&fb=1&co_partnerid=&item=" + ae.getIdentifier() + "&quantity=" + quantity; - - // This updates the cookies with the affiliate information, if it's not a test auction. - if(ae.getTitle().toLowerCase().indexOf("test") == -1) { - if(JBConfig.doAffiliate(ae.getEndDate().getTime())) { - // Ignoring the result as it's just called to trigger affiliate mode. - getAuction(ae, ae.getIdentifier()); - } - } - - StringBuffer sb; - - try { - sb = mLogin.getNecessaryCookie(false).getAllCookiesAndPage(buyRequest, null, false); - JHTML doBuy = new JHTML(sb); - JHTML.Form buyForm = doBuy.getFormWithInput("uiid"); - - if (buyForm != null) { - buyForm.delInput("BIN_button"); - CookieJar cj = mLogin.getNecessaryCookie(false); - StringBuffer loadedPage = cj.getAllCookiesAndPage(buyForm.getCGI(), buyRequest, false); - if (loadedPage == null) return BID_ERROR_CONNECTION; - return handlePostBidBuyPage(cj, loadedPage, buyForm, ae); - } - } catch (CookieJar.CookieException ignored) { - return BID_ERROR_CONNECTION; - } catch (UnsupportedEncodingException uee) { - ErrorManagement.handleException("UTF-8 not supported locally, can't URLEncode buy form.", uee); - return BID_ERROR_CONNECTION; - } - - ae.setErrorPage(sb); - return BID_ERROR_UNKNOWN; - } - - /** - * @brief Perform the entire bidding process on an item. - * - * @param inEntry - The item to bid on. - * @param inBid - The amount to bid. - * @param inQuantity - The number of items to bid on. - * - * @return - A bid response code, or BID_ERROR_UNKNOWN if we can't - * figure out what happened. - */ - public int bid(AuctionEntry inEntry, com.jbidwatcher.util.Currency inBid, int inQuantity) { - Auctions.startBlocking(); - if(JConfig.queryConfiguration("sound.enable", "false").equals("true")) MQFactory.getConcrete("sfx").enqueue("/audio/bid.mp3"); - - try { - // If it's not closing within the next minute, then go ahead and try for the affiliate mode. - if(inEntry.getEndDate().getTime() > (System.currentTimeMillis() + Constants.ONE_MINUTE)) { - safeGetAffiliate(mLogin.getNecessaryCookie(false), inEntry); - } - } catch (CookieJar.CookieException ignore) { - // We don't care that much about connection refused in this case. - } - JHTML.Form bidForm; - - try { - bidForm = getBidForm(mLogin.getNecessaryCookie(false), inEntry, inBid, inQuantity); - } catch(BadBidException bbe) { - Auctions.endBlocking(); - return bbe.getResult(); - } - - if (bidForm != null) { - int rval = placeFinalBid(mLogin.getNecessaryCookie(false), bidForm, inEntry, inBid, inQuantity); - Auctions.endBlocking(); - return rval; - } - ErrorManagement.logMessage("Bad/nonexistent key read in bid, or connection failure!"); - - Auctions.endBlocking(); - return BID_ERROR_UNKNOWN; - } - - public int placeFinalBid(CookieJar cj, JHTML.Form bidForm, AuctionEntry inEntry, com.jbidwatcher.util.Currency inBid, int inQuantity) { - String bidRequest = Externalized.getString("ebayServer.protocol") + Externalized.getString("ebayServer.bidHost") + Externalized.getString("ebayServer.V3file"); - String bidInfo = Externalized.getString("ebayServer.bidCmd") + Externalized.getString("ebayServer.itemCGI") + inEntry.getIdentifier() + - Externalized.getString("ebayServer.quantCGI") + inQuantity + - Externalized.getString("ebayServer.bidCGI") + inBid.getValue(); - String bidURL = bidRequest + '?' + bidInfo; - - bidForm.delInput("BIN_button"); - StringBuffer loadedPage = null; - - // This SHOULD be POSTed, but only works if sent with GET. - try { - if (JConfig.debugging) inEntry.setLastStatus("Submitting bid form."); - loadedPage = cj.getAllCookiesAndPage(bidForm.getCGI(), bidURL, false); - if (JConfig.debugging) inEntry.setLastStatus("Done submitting bid form."); - } catch (UnsupportedEncodingException uee) { - ErrorManagement.handleException("UTF-8 not supported locally, can't URLEncode bid form.", uee); - } catch (CookieJar.CookieException ignored) { - return BID_ERROR_CONNECTION; - } - - if (loadedPage == null) { - return BID_ERROR_CONNECTION; - } - return handlePostBidBuyPage(cj, loadedPage, bidForm, inEntry); - } - - public void safeGetAffiliate(CookieJar cj, AuctionEntry inEntry) throws CookieJar.CookieException { - // This updates the cookies with the affiliate information, if it's not a test auction. - if(inEntry.getTitle().toLowerCase().indexOf("test") == -1) { - if(JBConfig.doAffiliate(inEntry.getEndDate().getTime())) { - if(JConfig.debugging) inEntry.setLastStatus("Loading item..."); - getAuction(inEntry, inEntry.getIdentifier()); - if(JConfig.debugging) inEntry.setLastStatus("Done loading item..."); - } - } + public synchronized CookieJar getNecessaryCookie(boolean force) { + return mLogin.getNecessaryCookie(force); } - private int handlePostBidBuyPage(CookieJar cj, StringBuffer loadedPage, JHTML.Form bidForm, AuctionEntry inEntry) { - if(JConfig.debugging) inEntry.setLastStatus("Loading post-bid data."); - JHTML htmlDocument = new JHTML(loadedPage); - - if(htmlDocument.grep("Buying.Reminder") != null) { - JHTML.Form continueForm = htmlDocument.getFormWithInput("firedFilterId"); - if(continueForm != null) { - try { - inEntry.setLastStatus("Trying to 'continue' to the bid result page."); - String cgi = continueForm.getCGI(); - // For some reason, the continue page represents the currency as - // separated from the amount with a '0xA0' character. When encoding, - // this becomes...broken somehow, and adds an extra character, which - // does not work when bidding. - cgi = cgi.replaceFirst("%[A-F][A-F0-9]%A0", "%A0"); - URLConnection huc = cj.getAllCookiesFromPage(cgi, null, false); - // We failed to load, entirely. Punt. - if (huc == null) return BID_ERROR_CONNECTION; - - loadedPage = Http.receivePage(huc); - // We failed to load. Punt. - if (loadedPage == null) return BID_ERROR_CONNECTION; - - htmlDocument = new JHTML(loadedPage); - } catch(Exception ignored) { - return BID_ERROR_CONNECTION; - } - } - } - - String errMsg = htmlDocument.grep(mBidResultRegex); - if (errMsg != null) { - Matcher bidMatch = mFindBidResult.matcher(errMsg); - bidMatch.find(); - String matched_error = bidMatch.group().toLowerCase(); - Integer bidResult = mResultHash.get(matched_error); - - if(inEntry.getTitle().toLowerCase().indexOf("test") == -1) { - if(JBConfig.doAffiliate(inEntry.getEndDate().getTime())) { - List<String> images = htmlDocument.getAllImages(); - for (String tag : images) { - Matcher tagMatch = srcPat.matcher(tag); - if (tagMatch.find()) { - int retry = 2; - do { - StringBuffer result = null; - try { - result = mLogin.getNecessaryCookie(false).getAllCookiesAndPage(tagMatch.group(1), "http://offer.ebay.com/ws/eBayISAPI.dll", false); - } catch (CookieJar.CookieException ignored) { - // Ignore connection refused errors. - } - if (result == null) { - retry--; - } else { - retry = 0; - } - } while (retry != 0); - } - } - } - } - - if(JConfig.debugging) inEntry.setLastStatus("Done loading post-bid data."); - - if(bidResult != null) return bidResult; - } - - // Skipping the userID and Password, so this can be submitted as - // debugging info. - bidForm.setText("user", "HIDDEN"); - bidForm.setText("pass", "HIDDEN"); - String safeBidInfo = ""; - try { - safeBidInfo = bidForm.getCGI(); - } catch(UnsupportedEncodingException uee) { - ErrorManagement.handleException("UTF-8 not supported locally, can't URLEncode CGI for debugging.", uee); - } - - if(JConfig.debugging) inEntry.setLastStatus("Failed to load post-bid data. 'Show Last Error' from context menu to see the failure page from the post-bid page."); - inEntry.setErrorPage(loadedPage); - - ErrorManagement.logFile(safeBidInfo, loadedPage); - return BID_ERROR_UNKNOWN; + // TODO - The following are exposed to and used by the Snipe class only. Is there another way? + public JHTML.Form getBidForm(CookieJar cj, AuctionEntry inEntry, Currency inCurr, int inQuant) throws BadBidException { + return mBidder.getBidForm(cj, inEntry, inCurr, inQuant); } - public synchronized CookieJar getNecessaryCookie(boolean force) { - return mLogin.getNecessaryCookie(force); + public int placeFinalBid(CookieJar cj, JHTML.Form bidForm, AuctionEntry inEntry, Currency inBid, int inQuantity) { + return mBidder.placeFinalBid(cj, bidForm, inEntry, inBid, inQuantity); } public void loadAuthorization(XMLElement auth) {
fc281e6694468fd90363a06cfb809e7368799908
restlet-framework-java
- Moved SIP test cases to test module--
p
https://github.com/restlet/restlet-framework-java
diff --git a/modules/org.restlet.test/META-INF/MANIFEST.MF b/modules/org.restlet.test/META-INF/MANIFEST.MF index 12a2255a80..e1db49e7c5 100644 --- a/modules/org.restlet.test/META-INF/MANIFEST.MF +++ b/modules/org.restlet.test/META-INF/MANIFEST.MF @@ -37,7 +37,8 @@ Require-Bundle: org.restlet, org.junit4, org.springframework, org.apache.tika, - org.restlet.ext.odata;bundle-version="2.0.0" + org.restlet.ext.odata;bundle-version="2.0.0", + org.restlet.ext.sip;bundle-version="2.1.0" Export-Package: org.restlet.test, org.restlet.test.bench, org.restlet.test.component, diff --git a/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java b/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java index 638850e0d1..4a6303a718 100644 --- a/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java +++ b/modules/org.restlet.test/src/org/restlet/test/RestletTestSuite.java @@ -59,6 +59,7 @@ import org.restlet.test.ext.jaxb.JaxbBasicConverterTestCase; import org.restlet.test.ext.jaxb.JaxbIntegrationConverterTestCase; import org.restlet.test.ext.odata.ODataTestSuite; +import org.restlet.test.ext.sip.AllSipTests; import org.restlet.test.ext.spring.AllSpringTests; import org.restlet.test.ext.velocity.VelocityTestCase; import org.restlet.test.ext.wadl.WadlTestCase; @@ -161,6 +162,7 @@ public RestletTestSuite() { addTest(EngineTestSuite.suite()); addTest(AllJaxRsTests.suite()); + addTest(AllSipTests.suite()); addTest(AllSpringTests.suite()); // [enddef] } diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AddressTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AddressTestCase.java similarity index 99% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AddressTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/AddressTestCase.java index 5bd3330c87..ba14943a33 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AddressTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AddressTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase; diff --git a/modules/org.restlet.test/src/org/restlet/test/ext/sip/AllSipTests.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AllSipTests.java new file mode 100644 index 0000000000..7340ecb08f --- /dev/null +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AllSipTests.java @@ -0,0 +1,54 @@ +/** + * Copyright 2005-2010 Noelios Technologies. + * + * The contents of this file are subject to the terms of one of the following + * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the + * "Licenses"). You can select the license that you prefer but you may not use + * this file except in compliance with one of these Licenses. + * + * You can obtain a copy of the LGPL 3.0 license at + * http://www.opensource.org/licenses/lgpl-3.0.html + * + * You can obtain a copy of the LGPL 2.1 license at + * http://www.opensource.org/licenses/lgpl-2.1.php + * + * You can obtain a copy of the CDDL 1.0 license at + * http://www.opensource.org/licenses/cddl1.php + * + * You can obtain a copy of the EPL 1.0 license at + * http://www.opensource.org/licenses/eclipse-1.0.php + * + * See the Licenses for the specific language governing permissions and + * limitations under the Licenses. + * + * Alternatively, you can obtain a royalty free commercial license with less + * limitations, transferable or non-transferable, directly at + * http://www.noelios.com/products/restlet-engine + * + * Restlet is a registered trademark of Noelios Technologies. + */ + +package org.restlet.test.ext.sip; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Suite with all SIP unit tests. + * + * @author Jerome Louvel + */ +public class AllSipTests extends TestCase { + + public static Test suite() { + final TestSuite suite = new TestSuite(); + suite.setName("all spring-ext tests"); + suite.addTestSuite(AddressTestCase.class); + suite.addTestSuite(AvailabilityTestCase.class); + suite.addTestSuite(EventTypeTestCase.class); + suite.addTestSuite(SipRecipientInfoTestCase.class); + return suite; + } + +} diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AvailabilityTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AvailabilityTestCase.java similarity index 98% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AvailabilityTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/AvailabilityTestCase.java index 6138ab301a..b2140da6cb 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/AvailabilityTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/AvailabilityTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase; diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/EventTypeTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/EventTypeTestCase.java similarity index 98% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/EventTypeTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/EventTypeTestCase.java index 6624a87b6d..cdad3bc4d3 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/EventTypeTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/EventTypeTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase; diff --git a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/SipRecipientInfoTestCase.java b/modules/org.restlet.test/src/org/restlet/test/ext/sip/SipRecipientInfoTestCase.java similarity index 99% rename from modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/SipRecipientInfoTestCase.java rename to modules/org.restlet.test/src/org/restlet/test/ext/sip/SipRecipientInfoTestCase.java index 9e23da89a9..01bfaa4714 100644 --- a/modules/org.restlet.ext.sip/src/org/restlet/ext/sip/test/SipRecipientInfoTestCase.java +++ b/modules/org.restlet.test/src/org/restlet/test/ext/sip/SipRecipientInfoTestCase.java @@ -28,7 +28,7 @@ * Restlet is a registered trademark of Noelios Technologies. */ -package org.restlet.ext.sip.test; +package org.restlet.test.ext.sip; import junit.framework.TestCase;
9eb8ef961e7ea615784bf60221ff8232b0b6c108
intellij-community
remember committed changes splitter proportions- (IDEADEV-16784)--
a
https://github.com/JetBrains/intellij-community
diff --git a/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesPanel.java b/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesPanel.java index a765e07a0b57b..3bd7bb849c276 100644 --- a/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesPanel.java +++ b/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesPanel.java @@ -25,6 +25,7 @@ import com.intellij.openapi.vcs.changes.ChangeList; import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; +import com.intellij.openapi.Disposable; import com.intellij.ui.FilterComponent; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; @@ -35,7 +36,7 @@ import java.util.Collection; import java.util.List; -public class CommittedChangesPanel extends JPanel implements TypeSafeDataProvider { +public class CommittedChangesPanel extends JPanel implements TypeSafeDataProvider, Disposable { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.changes.committed.CommittedChangesPanel"); private CommittedChangesTreeBrowser myBrowser; @@ -193,6 +194,10 @@ else if (key.equals(DataKeys.CHANGE_LISTS)) { } } + public void dispose() { + myBrowser.dispose(); + } + private class MyFilterComponent extends FilterComponent { public MyFilterComponent() { super("COMMITTED_CHANGES_FILTER_HISTORY", 20); diff --git a/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesTreeBrowser.java b/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesTreeBrowser.java index 6c68c522d68d7..823cae3268c52 100644 --- a/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesTreeBrowser.java +++ b/source/com/intellij/openapi/vcs/changes/committed/CommittedChangesTreeBrowser.java @@ -14,11 +14,14 @@ import com.intellij.openapi.vcs.changes.ui.ChangesBrowser; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.openapi.ui.Splitter; +import com.intellij.openapi.ui.SplitterProportionsData; +import com.intellij.openapi.Disposable; import com.intellij.ui.ColoredTreeCellRenderer; import com.intellij.ui.PopupHandler; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.ui.Tree; import com.intellij.util.ui.tree.TreeUtil; +import com.intellij.peer.PeerFactory; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; @@ -41,7 +44,7 @@ /** * @author yole */ -public class CommittedChangesTreeBrowser extends JPanel implements TypeSafeDataProvider { +public class CommittedChangesTreeBrowser extends JPanel implements TypeSafeDataProvider, Disposable { private final Tree myChangesTree; private final ChangesBrowser myChangesView; private List<CommittedChangeList> myChangeLists; @@ -51,10 +54,9 @@ public class CommittedChangesTreeBrowser extends JPanel implements TypeSafeDataP private Splitter myFilterSplitter; private JPanel myLeftPanel; private CommittedChangeListRenderer myCellRenderer; - private JScrollPane myChangesTreeScrollPane; - private Splitter mySplitter; private FilterChangeListener myFilterChangeListener = new FilterChangeListener(); private List<CommittedChangeList> myFilteredChangeLists; + private final SplitterProportionsData mySplitterProportionsData = PeerFactory.getInstance().getUIHelper().createSplitterProportionsData(); public CommittedChangesTreeBrowser(final Project project, final List<CommittedChangeList> changeLists) { super(new BorderLayout()); @@ -95,15 +97,17 @@ public void mouseClicked(final MouseEvent e) { }); myLeftPanel = new JPanel(new BorderLayout()); - myChangesTreeScrollPane = new JScrollPane(myChangesTree); myFilterSplitter = new Splitter(false, 0.5f); - myFilterSplitter.setSecondComponent(myChangesTreeScrollPane); + myFilterSplitter.setSecondComponent(new JScrollPane(myChangesTree)); myLeftPanel.add(myFilterSplitter, BorderLayout.CENTER); - mySplitter = new Splitter(false, 0.7f); - mySplitter.setFirstComponent(myLeftPanel); - mySplitter.setSecondComponent(myChangesView); + final Splitter splitter = new Splitter(false, 0.7f); + splitter.setFirstComponent(myLeftPanel); + splitter.setSecondComponent(myChangesView); - add(mySplitter, BorderLayout.CENTER); + add(splitter, BorderLayout.CENTER); + + mySplitterProportionsData.externalizeFromDimensionService("CommittedChanges.SplitterProportions"); + mySplitterProportionsData.restoreSplitterProportions(this); updateBySelectionChange(); @@ -137,6 +141,8 @@ public void addToolBar(JComponent toolBar) { } public void dispose() { + mySplitterProportionsData.saveSplitterProportions(this); + mySplitterProportionsData.externalizeToDimensionService("CommittedChanges.SplitterProportions"); myChangesView.dispose(); } diff --git a/source/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.java b/source/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.java index 99ec1f66a9b16..c3eb37981076e 100644 --- a/source/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.java +++ b/source/com/intellij/openapi/vcs/changes/ui/ChangesViewContentManager.java @@ -23,6 +23,7 @@ import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ToolWindowManager; +import com.intellij.openapi.Disposable; import com.intellij.peer.PeerFactory; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; @@ -237,7 +238,11 @@ public void selectionChanged(final ContentManagerEvent event) { if (event.getContent().getComponent() instanceof ContentStub) { ChangesViewContentEP ep = ((ContentStub) event.getContent().getComponent()).getEP(); ChangesViewContentProvider provider = ep.getInstance(myProject); - event.getContent().setComponent(provider.initContent()); + final JComponent contentComponent = provider.initContent(); + event.getContent().setComponent(contentComponent); + if (contentComponent instanceof Disposable) { + event.getContent().setDisposer((Disposable) contentComponent); + } } } } diff --git a/ui/openapi/com/intellij/openapi/ui/SplitterProportionsData.java b/ui/openapi/com/intellij/openapi/ui/SplitterProportionsData.java index d095e1ecaa7c5..a8b1249d43927 100644 --- a/ui/openapi/com/intellij/openapi/ui/SplitterProportionsData.java +++ b/ui/openapi/com/intellij/openapi/ui/SplitterProportionsData.java @@ -23,6 +23,7 @@ package com.intellij.openapi.ui; import com.intellij.openapi.util.JDOMExternalizable; +import org.jetbrains.annotations.NonNls; import java.awt.*; @@ -32,7 +33,7 @@ public interface SplitterProportionsData extends JDOMExternalizable { void restoreSplitterProportions(Component root); - void externalizeToDimensionService(String key); + void externalizeToDimensionService(@NonNls String key); - void externalizeFromDimensionService(String key); + void externalizeFromDimensionService(@NonNls String key); } \ No newline at end of file
cbde1cfa6eec6cc37025fea406deb33eb82c3509
intellij-community
don't suggest 'convert to groovy-style property- access' inside closure--
c
https://github.com/JetBrains/intellij-community
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/JavaStylePropertiesInvocationIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/JavaStylePropertiesInvocationIntention.java index 0327535993267..22ed9c42e5349 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/JavaStylePropertiesInvocationIntention.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/style/JavaStylePropertiesInvocationIntention.java @@ -22,16 +22,24 @@ import org.jetbrains.plugins.groovy.intentions.base.Intention; import org.jetbrains.plugins.groovy.intentions.base.IntentionUtils; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import static org.jetbrains.plugins.groovy.lang.psi.util.PsiElementUtil.*; /** * @author ilyas */ public class JavaStylePropertiesInvocationIntention extends Intention { + @Override + protected boolean isStopElement(PsiElement element) { + return super.isStopElement(element) || element instanceof GrClosableBlock; + } protected void processIntention(@NotNull PsiElement element) throws IncorrectOperationException { assert element instanceof GrMethodCallExpression || element instanceof GrApplicationStatement; diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyFixesTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyFixesTest.groovy index aa2674d0ea9b0..7224f84e78fce 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyFixesTest.groovy +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyFixesTest.groovy @@ -6,7 +6,8 @@ package org.jetbrains.plugins.groovy.lang; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import org.jetbrains.plugins.groovy.codeInspection.control.GroovyConstantIfStatementInspection.ConstantIfStatementVisitor -import org.jetbrains.plugins.groovy.codeInspection.control.GroovyConstantIfStatementInspection; +import org.jetbrains.plugins.groovy.codeInspection.control.GroovyConstantIfStatementInspection +import org.jetbrains.plugins.groovy.codeInspection.gpath.GroovySetterCallCanBePropertyAccessInspection; /** * @author peter @@ -27,4 +28,19 @@ if (true) { }""" } + public void testShallowChangeToGroovyStylePropertyAccess() throws Throwable { + myFixture.enableInspections new GroovySetterCallCanBePropertyAccessInspection() + myFixture.configureByText "a.groovy", """class GroovyClasss { + def initializer + def foo() { + setInitializer({ + <caret>println "hello" + }) + } +} + +""" + assertEmpty myFixture.filterAvailableIntentions("Change to Groovy-style property reference") + } + } \ No newline at end of file
8f4cb0486b6e6ab48e6df6b2e3e44a7eca27c911
camel
CAMEL-1789 Let the Camel Route support to lookup- the service which is exported from the OSGi bundle--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@792398 13f79535-47bb-0310-9956-ffa450edef68-
a
https://github.com/apache/camel
diff --git a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java index dea39dfd4af93..35f9348bf6ff2 100644 --- a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java +++ b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactory.java @@ -18,10 +18,13 @@ import java.util.List; +import org.apache.camel.CamelContext; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.converter.AnnotationTypeConverterLoader; import org.apache.camel.impl.converter.DefaultTypeConverter; import org.apache.camel.impl.converter.TypeConverterLoader; +import org.apache.camel.spring.SpringCamelContext; +import org.apache.camel.util.ObjectHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -54,6 +57,7 @@ public DefaultCamelContext createContext() { if (LOG.isDebugEnabled()) { LOG.debug("Using OSGI resolvers"); } + updateRegistry(context); LOG.debug("Using OsgiFactoryFinderResolver"); context.setFactoryFinderResolver(new OsgiFactoryFinderResolver()); LOG.debug("Using OsgiPackageScanClassResolver"); @@ -64,13 +68,23 @@ public DefaultCamelContext createContext() { context.setLanguageResolver(new OsgiLanguageResolver()); addOsgiAnnotationTypeConverterLoader(context, bundleContext); } else { - // TODO: should we not thrown an excpetion to not allow it to startup + // TODO: should we not thrown an exception to not allow it to startup LOG.warn("BundleContext not set, cannot run in OSGI container"); } return context; } + protected void updateRegistry(DefaultCamelContext context) { + ObjectHelper.notNull(bundleContext, "BundleContext"); + LOG.debug("Setting the OSGi ServiceRegistry"); + OsgiServiceRegistry osgiServiceRegistry = new OsgiServiceRegistry(bundleContext); + CompositeRegistry compositeRegistry = new CompositeRegistry(); + compositeRegistry.addRegistry(osgiServiceRegistry); + compositeRegistry.addRegistry(context.getRegistry()); + context.setRegistry(compositeRegistry); + } + protected void addOsgiAnnotationTypeConverterLoader(DefaultCamelContext context, BundleContext bundleContext) { LOG.debug("Using OsgiAnnotationTypeConverterLoader"); DefaultTypeConverter typeConverter = (DefaultTypeConverter) context.getTypeConverter(); diff --git a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java index e0dcdeed485e7..4a2f20842a115 100644 --- a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java +++ b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CamelContextFactoryBean.java @@ -22,10 +22,13 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; +import org.apache.camel.CamelContext; +import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.converter.AnnotationTypeConverterLoader; import org.apache.camel.impl.converter.DefaultTypeConverter; import org.apache.camel.impl.converter.TypeConverterLoader; import org.apache.camel.spring.SpringCamelContext; +import org.apache.camel.util.ObjectHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.framework.BundleContext; @@ -56,6 +59,7 @@ protected SpringCamelContext createContext() { if (LOG.isDebugEnabled()) { LOG.debug("Using OSGI resolvers"); } + updateRegistry(context); LOG.debug("Using OsgiFactoryFinderResolver"); context.setFactoryFinderResolver(new OsgiFactoryFinderResolver()); LOG.debug("Using OsgiPackageScanClassResolver"); @@ -73,6 +77,16 @@ protected SpringCamelContext createContext() { return context; } + protected void updateRegistry(DefaultCamelContext context) { + ObjectHelper.notNull(bundleContext, "BundleContext"); + LOG.debug("Setting the OSGi ServiceRegistry"); + OsgiServiceRegistry osgiServiceRegistry = new OsgiServiceRegistry(bundleContext); + CompositeRegistry compositeRegistry = new CompositeRegistry(); + compositeRegistry.addRegistry(osgiServiceRegistry); + compositeRegistry.addRegistry(context.getRegistry()); + context.setRegistry(compositeRegistry); + } + protected void addOsgiAnnotationTypeConverterLoader(SpringCamelContext context) { LOG.debug("Using OsgiAnnotationTypeConverterLoader"); diff --git a/components/camel-osgi/src/main/java/org/apache/camel/osgi/CompositeRegistry.java b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CompositeRegistry.java new file mode 100644 index 0000000000000..8f2f8dcdcd992 --- /dev/null +++ b/components/camel-osgi/src/main/java/org/apache/camel/osgi/CompositeRegistry.java @@ -0,0 +1,79 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.osgi; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.camel.spi.Registry; + +/** + * This registry will look up the object with the sequence of the registry list untill it find the Object. + */ +public class CompositeRegistry implements Registry { + private List<Registry> registryList; + + public CompositeRegistry() { + registryList = new ArrayList<Registry>(); + } + + public CompositeRegistry(List<Registry> registries) { + registryList = registries; + } + + public void addRegistry(Registry registry) { + registryList.add(registry); + } + + public <T> T lookup(String name, Class<T> type) { + T answer = null; + for (Registry registry : registryList) { + answer = registry.lookup(name, type); + if (answer != null) { + break; + } + } + return answer; + } + + public Object lookup(String name) { + Object answer = null; + for (Registry registry : registryList) { + answer = registry.lookup(name); + if (answer != null) { + break; + } + } + return answer; + } + + @SuppressWarnings("unchecked") + public <T> Map<String, T> lookupByType(Class<T> type) { + Map<String, T> answer = Collections.EMPTY_MAP; + for (Registry registry : registryList) { + answer = registry.lookupByType(type); + if (answer != Collections.EMPTY_MAP) { + break; + } + } + return answer; + } + +} diff --git a/components/camel-osgi/src/main/java/org/apache/camel/osgi/OsgiServiceRegistry.java b/components/camel-osgi/src/main/java/org/apache/camel/osgi/OsgiServiceRegistry.java new file mode 100644 index 0000000000000..09ff58c19aa61 --- /dev/null +++ b/components/camel-osgi/src/main/java/org/apache/camel/osgi/OsgiServiceRegistry.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.osgi; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.camel.spi.Registry; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.springframework.osgi.context.BundleContextAware; + +/** + * The OsgiServiceRegistry support to get the service object from the bundle context + */ +public class OsgiServiceRegistry implements Registry { + private BundleContext bundleContext; + private Map<String, Object> serviceCacheMap = new ConcurrentHashMap<String, Object>(); + + public OsgiServiceRegistry(BundleContext bc) { + bundleContext = bc; + } + + public <T> T lookup(String name, Class<T> type) { + Object service = lookup(name); + return type.cast(service); + } + + public Object lookup(String name) { + Object service = serviceCacheMap.get(name); + if (service == null) { + ServiceReference sr = bundleContext.getServiceReference(name); + if (sr != null) { + // TODO need to keep the track of Service + // and call ungetService when the camel context is closed + service = bundleContext.getService(sr); + if (service != null) { + serviceCacheMap.put(name, service); + } + } + } + return service; + } + + @SuppressWarnings("unchecked") + public <T> Map<String, T> lookupByType(Class<T> type) { + // not implemented so we return an empty map + return Collections.EMPTY_MAP; + } + +} diff --git a/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelContextFactoryTest.java b/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelContextFactoryTest.java new file mode 100644 index 0000000000000..26c4b0db28ea5 --- /dev/null +++ b/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelContextFactoryTest.java @@ -0,0 +1,34 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.osgi; + +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.osgi.test.MyService; +import org.junit.Test; + +public class CamelContextFactoryTest extends CamelOsgiTestSupport { + @Test + public void osigServiceRegistryTest() { + CamelContextFactory factory = new CamelContextFactory(); + factory.setBundleContext(getBundleContext()); + DefaultCamelContext context = factory.createContext(); + MyService myService = context.getRegistry().lookup(MyService.class.getName(), MyService.class); + assertNotNull("MyService should not be null", myService); + } + +} diff --git a/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelMockBundleContext.java b/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelMockBundleContext.java new file mode 100644 index 0000000000000..3afd9b413ef4e --- /dev/null +++ b/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelMockBundleContext.java @@ -0,0 +1,40 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.osgi; + +import org.apache.camel.osgi.test.MyService; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.springframework.osgi.mock.MockBundleContext; + +/** + * + */ +public class CamelMockBundleContext extends MockBundleContext { + + public Object getService(ServiceReference reference) { + String[] classNames = (String[]) reference.getProperty(Constants.OBJECTCLASS); + System.out.println("The class name is " + classNames[0]); + if (classNames[0].equals("org.apache.camel.osgi.test.MyService")) { + return new MyService(); + } else { + return null; + } + } + +} diff --git a/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelOsgiTestSupport.java b/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelOsgiTestSupport.java index 77984c1353f6f..26079533d2a5b 100644 --- a/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelOsgiTestSupport.java +++ b/components/camel-osgi/src/test/java/org/apache/camel/osgi/CamelOsgiTestSupport.java @@ -16,7 +16,6 @@ */ package org.apache.camel.osgi; -import junit.framework.TestCase; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -26,7 +25,7 @@ public class CamelOsgiTestSupport extends Assert { private Activator testActivator; - private MockBundleContext bundleContext = new MockBundleContext(); + private MockBundleContext bundleContext = new CamelMockBundleContext(); private OsgiPackageScanClassResolver resolver = new OsgiPackageScanClassResolver(bundleContext); private MockBundle bundle = new CamelMockBundle(); diff --git a/components/camel-osgi/src/test/java/org/apache/camel/osgi/test/MyService.java b/components/camel-osgi/src/test/java/org/apache/camel/osgi/test/MyService.java new file mode 100644 index 0000000000000..65e246f9de205 --- /dev/null +++ b/components/camel-osgi/src/test/java/org/apache/camel/osgi/test/MyService.java @@ -0,0 +1,24 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://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.apache.camel.osgi.test; + +public class MyService { + public String sayHi() { + return "Hello"; + } + +}
0d456d2091f5f8dd3a954ab64e7b78a08246f892
camel
minor tidy up of test case--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@654441 13f79535-47bb-0310-9956-ffa450edef68-
p
https://github.com/apache/camel
diff --git a/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java b/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java index dfbc0dcad536e..c92918e36c94e 100644 --- a/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java +++ b/camel-core/src/test/java/org/apache/camel/component/file/FileRouteTest.java @@ -28,13 +28,13 @@ public class FileRouteTest extends ContextTestSupport { protected String uri = "file:target/test-default-inbox"; public void testFileRoute() throws Exception { - MockEndpoint result = resolveMandatoryEndpoint("mock:result", MockEndpoint.class); + MockEndpoint result = getMockEndpoint("mock:result"); result.expectedBodiesReceived(expectedBody); result.setResultWaitTime(5000); template.sendBodyAndHeader(uri, expectedBody, "cheese", 123); - result.assertIsSatisfied(); + assertMockEndpointsSatisifed(); } @Override
74c7d6e7ed1ec3eb4e2f20f6790d9aedb8cd01d5
Mylyn Reviews
342871 Fix findbugs warnings Fixed all findbugs warnings reported in last build
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewResult.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewResult.java index 723bb8e8..2f55d40f 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewResult.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/ReviewResult.java @@ -37,12 +37,12 @@ public void removePropertyChangeListener(String propertyName, } public Date getDate() { - return date; + return date!=null?new Date(date.getTime()):null; } public void setDate(Date date) { Date old = this.date; - this.date = date; + this.date = date!=null?new Date( date.getTime()):null; changeSupport.firePropertyChange("date", old, date); } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java index b58b5fcd..bd4eb747 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/TaskComment.java @@ -39,11 +39,11 @@ public void setText(String text) { } public Date getDate() { - return date; + return date!=null?new Date(date.getTime()):null; } public void setDate(Date date) { - this.date = date; + this.date = date!=null?new Date(date.getTime()):null; } } diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java index 8f2529f3..f7301688 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewScopeNode.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.TreeMap; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; @@ -63,7 +64,7 @@ private String convertScopeToDescription() { counts.get(key).counter++; } boolean isFirstElement = true; - for (String type : counts.keySet()) { + for (Entry<String,Counter> type : counts.entrySet()) { if (isFirstElement) { isFirstElement = false; } else { diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java index 2646a22a..4400f727 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java @@ -36,7 +36,7 @@ * */ public class ReviewDslParser extends Parser { - public static final String[] tokenNames = new String[] { "<invalid>", + static final String[] tokenNames = new String[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "STRING", "INT", "TASK_ID", "ESC_SEQ", "UNICODE_ESC", "OCTAL_ESC", "HEX_DIGIT", "WS", "'Review'", "'result:'", "'Comment:'", "'PASSED'", "'WARNING'", "'FAILED'", @@ -68,7 +68,7 @@ public TreeAdaptor getTreeAdaptor() { } public String[] getTokenNames() { - return tokenNames; + return tokenNames.clone(); } public String getGrammarFileName() { diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java index 9c426928..522d4ac3 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ColumnLabelProvider.java @@ -21,7 +21,7 @@ public class ColumnLabelProvider<T> extends TableLabelProvider { private IColumnSpec<T>[] specs; public ColumnLabelProvider(IColumnSpec<T>[] specs) { - this.specs = specs; + this.specs = specs.clone(); } @SuppressWarnings("unchecked") diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java index 92ed9129..f65767e8 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewSummaryTaskEditorPart.java @@ -189,7 +189,7 @@ private TreeViewer createTreeWithColumns(Tree tree) { - private final class ScopeViewerFilter extends ViewerFilter { + private static final class ScopeViewerFilter extends ViewerFilter { @Override public boolean select(Viewer viewer, Object parentElement, Object element) {
362e94ffa7bc065e0a88f6f999c9c491b06e8946
Vala
girparser: use identifier prefix from GIR when appropriate Fixes bug 731066
a
https://github.com/GNOME/vala/
diff --git a/vala/valagirparser.vala b/vala/valagirparser.vala index 5ac350e946..b1561e86e3 100644 --- a/vala/valagirparser.vala +++ b/vala/valagirparser.vala @@ -639,13 +639,42 @@ public class Vala.GirParser : CodeVisitor { var prefix = symbol.get_attribute_string ("CCode", "lower_case_cprefix"); if (prefix == null && (symbol is ObjectTypeSymbol || symbol is Struct)) { - if (metadata.has_argument (ArgumentType.CPREFIX)) { + if (metadata.has_argument (ArgumentType.LOWER_CASE_CPREFIX)) { + prefix = metadata.get_string (ArgumentType.LOWER_CASE_CPREFIX); + } else if (metadata.has_argument (ArgumentType.CPREFIX)) { prefix = metadata.get_string (ArgumentType.CPREFIX); } else { prefix = symbol.get_attribute_string ("CCode", "cprefix"); } } + if (prefix == null && girdata != null && (girdata.contains ("c:symbol-prefix") || girdata.contains("c:symbol-prefixes"))) { + /* Use the prefix in the gir. We look up prefixes up to the root. + If some node does not have girdata, we ignore it as i might be + a namespace created due to reparenting. */ + unowned Node cur = this; + do { + if (cur.girdata != null) { + var p = cur.girdata["c:symbol-prefix"]; + if (p == null) { + p = cur.girdata["c:symbol-prefixes"]; + if (p != null) { + var idx = p.index_of (","); + if (idx >= 0) { + p = p.substring (0, idx); + } + } + } + + if (p != null) { + prefix = p+"_"+prefix; + } + } + + cur = cur.parent; + } while (cur != null); + } + if (prefix == null) { prefix = get_default_lower_case_cprefix (); } @@ -1106,11 +1135,7 @@ public class Vala.GirParser : CodeVisitor { // lower_case_cprefix if (get_lower_case_cprefix () != get_default_lower_case_cprefix ()) { - if (symbol is Class) { - symbol.set_attribute_string ("CCode", "cprefix", get_lower_case_cprefix ()); - } else { - symbol.set_attribute_string ("CCode", "lower_case_cprefix", get_lower_case_cprefix ()); - } + symbol.set_attribute_string ("CCode", "lower_case_cprefix", get_lower_case_cprefix ()); } // lower_case_csuffix if (get_lower_case_csuffix () != get_default_lower_case_csuffix ()) { diff --git a/vapi/gstreamer-audio-1.0.vapi b/vapi/gstreamer-audio-1.0.vapi index ecec039535..4715435b54 100644 --- a/vapi/gstreamer-audio-1.0.vapi +++ b/vapi/gstreamer-audio-1.0.vapi @@ -353,18 +353,13 @@ namespace Gst { [NoWrapper] public virtual bool unprepare (); } - [CCode (cheader_filename = "gst/audio/audio.h", cname = "GstStreamVolume", type_cname = "GstStreamVolumeInterface", type_id = "gst_stream_volume_get_type ()")] + [CCode (cheader_filename = "gst/audio/audio.h", cname = "GstStreamVolume", lower_case_cprefix = "gst_stream_volume_", type_cname = "GstStreamVolumeInterface", type_id = "gst_stream_volume_get_type ()")] [GIR (name = "StreamVolume")] public interface StreamVolume : GLib.Object { - [CCode (cname = "gst_stream_volume_convert_volume")] public static double convert_volume (Gst.Audio.StreamVolumeFormat from, Gst.Audio.StreamVolumeFormat to, double val); - [CCode (cname = "gst_stream_volume_get_mute")] public bool get_mute (); - [CCode (cname = "gst_stream_volume_get_volume")] public double get_volume (Gst.Audio.StreamVolumeFormat format); - [CCode (cname = "gst_stream_volume_set_mute")] public void set_mute (bool mute); - [CCode (cname = "gst_stream_volume_set_volume")] public void set_volume (Gst.Audio.StreamVolumeFormat format, double val); [NoAccessorMethod] public abstract bool mute { get; set; } diff --git a/vapi/gstreamer-base-1.0.vapi b/vapi/gstreamer-base-1.0.vapi index 96f9c2998e..4ffe5b50a8 100644 --- a/vapi/gstreamer-base-1.0.vapi +++ b/vapi/gstreamer-base-1.0.vapi @@ -3,48 +3,31 @@ [CCode (cprefix = "Gst", gir_namespace = "GstBase", gir_version = "1.0", lower_case_cprefix = "gst_")] namespace Gst { namespace Base { - [CCode (cheader_filename = "gst/base/base.h", cname = "GstAdapter", type_id = "gst_adapter_get_type ()")] + [CCode (cheader_filename = "gst/base/base.h", cname = "GstAdapter", lower_case_cprefix = "gst_adapter_", type_id = "gst_adapter_get_type ()")] [GIR (name = "Adapter")] public class Adapter : GLib.Object { - [CCode (cname = "gst_adapter_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public Adapter (); - [CCode (cname = "gst_adapter_available")] public size_t available (); - [CCode (cname = "gst_adapter_available_fast")] public size_t available_fast (); - [CCode (cname = "gst_adapter_clear")] public void clear (); - [CCode (cname = "gst_adapter_copy")] public void copy ([CCode (array_length_cname = "size", array_length_pos = 2.1, array_length_type = "gsize")] out unowned uint8[] dest, size_t offset); - [CCode (cname = "gst_adapter_copy_bytes")] public GLib.Bytes copy_bytes (size_t offset, size_t size); - [CCode (cname = "gst_adapter_flush")] public void flush (size_t flush); - [CCode (array_length_pos = 0.1, array_length_type = "gsize", cname = "gst_adapter_map")] + [CCode (array_length_pos = 0.1, array_length_type = "gsize")] public unowned uint8[] map (); - [CCode (cname = "gst_adapter_masked_scan_uint32")] public ssize_t masked_scan_uint32 (uint32 mask, uint32 pattern, size_t offset, size_t size); - [CCode (cname = "gst_adapter_masked_scan_uint32_peek")] public ssize_t masked_scan_uint32_peek (uint32 mask, uint32 pattern, size_t offset, size_t size, uint32 value); - [CCode (cname = "gst_adapter_prev_dts")] public Gst.ClockTime prev_dts (out uint64 distance); - [CCode (cname = "gst_adapter_prev_dts_at_offset")] public Gst.ClockTime prev_dts_at_offset (size_t offset, out uint64 distance); - [CCode (cname = "gst_adapter_prev_pts")] public Gst.ClockTime prev_pts (out uint64 distance); - [CCode (cname = "gst_adapter_prev_pts_at_offset")] public Gst.ClockTime prev_pts_at_offset (size_t offset, out uint64 distance); - [CCode (cname = "gst_adapter_push")] public void push (owned Gst.Buffer buf); - [CCode (array_length_pos = 0.1, array_length_type = "gsize", cname = "gst_adapter_take")] + [CCode (array_length_pos = 0.1, array_length_type = "gsize")] public uint8[] take (); - [CCode (cname = "gst_adapter_take_buffer")] public Gst.Buffer take_buffer (size_t nbytes); - [CCode (cname = "gst_adapter_take_buffer_fast")] public Gst.Buffer take_buffer_fast (size_t nbytes); - [CCode (cname = "gst_adapter_take_list")] public GLib.List<Gst.Buffer> take_list (size_t nbytes); - [CCode (cname = "gst_adapter_unmap")] public void unmap (); } [CCode (cheader_filename = "gst/base/gstadapter.h,gst/base/gstbaseparse.h,gst/base/gstbasesink.h,gst/base/gstbasesrc.h,gst/base/gstbasetransform.h,gst/base/gstbitreader.h,gst/base/gstbytereader.h,gst/base/gstbytewriter.h,gst/base/gstcollectpads.h,gst/base/gstpushsrc.h,gst/base/gsttypefindhelper.h", cname = "GstBitReader")] @@ -314,69 +297,43 @@ namespace Gst { public ByteWriter.with_data ([CCode (array_length_type = "guint")] uint8[] data, uint size, bool initialized); public ByteWriter.with_size (uint size, bool fixed); } - [CCode (cheader_filename = "gst/base/base.h", cname = "GstCollectPads", type_id = "gst_collect_pads_get_type ()")] + [CCode (cheader_filename = "gst/base/base.h", cname = "GstCollectPads", lower_case_cprefix = "gst_collect_pads_", type_id = "gst_collect_pads_get_type ()")] [GIR (name = "CollectPads")] public class CollectPads : Gst.Object { public weak GLib.SList<void*> data; - [CCode (cname = "gst_collect_pads_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public CollectPads (); - [CCode (cname = "gst_collect_pads_available")] public uint available (); - [CCode (cname = "gst_collect_pads_clip_running_time")] public Gst.FlowReturn clip_running_time (Gst.Base.CollectData cdata, Gst.Buffer buf, Gst.Buffer? outbuf, void* user_data); - [CCode (cname = "gst_collect_pads_event_default")] public bool event_default (Gst.Base.CollectData data, Gst.Event event, bool discard); - [CCode (cname = "gst_collect_pads_flush")] public uint flush (Gst.Base.CollectData data, uint size); - [CCode (cname = "gst_collect_pads_peek")] public Gst.Buffer peek (Gst.Base.CollectData data); - [CCode (cname = "gst_collect_pads_pop")] public Gst.Buffer pop (Gst.Base.CollectData data); - [CCode (cname = "gst_collect_pads_query_default")] public bool query_default (Gst.Base.CollectData data, Gst.Query query, bool discard); - [CCode (cname = "gst_collect_pads_read_buffer")] public Gst.Buffer read_buffer (Gst.Base.CollectData data, uint size); - [CCode (cname = "gst_collect_pads_remove_pad")] public bool remove_pad (Gst.Pad pad); - [CCode (cname = "gst_collect_pads_set_flushing")] public void set_flushing (bool flushing); - [CCode (cname = "gst_collect_pads_set_waiting")] public void set_waiting (Gst.Base.CollectData data, bool waiting); - [CCode (cname = "gst_collect_pads_src_event_default")] public bool src_event_default (Gst.Pad pad, Gst.Event event); - [CCode (cname = "gst_collect_pads_start")] public void start (); - [CCode (cname = "gst_collect_pads_stop")] public void stop (); - [CCode (cname = "gst_collect_pads_take_buffer")] public Gst.Buffer take_buffer (Gst.Base.CollectData data, uint size); } - [CCode (cheader_filename = "gst/base/base.h", cname = "GstDataQueue", type_id = "gst_data_queue_get_type ()")] + [CCode (cheader_filename = "gst/base/base.h", cname = "GstDataQueue", lower_case_cprefix = "gst_data_queue_", type_id = "gst_data_queue_get_type ()")] [GIR (name = "DataQueue")] public class DataQueue : GLib.Object { [CCode (has_construct_function = false)] protected DataQueue (); - [CCode (cname = "gst_data_queue_drop_head")] public bool drop_head (GLib.Type type); - [CCode (cname = "gst_data_queue_flush")] public void flush (); - [CCode (cname = "gst_data_queue_get_level")] public void get_level (Gst.Base.DataQueueSize level); - [CCode (cname = "gst_data_queue_is_empty")] public bool is_empty (); - [CCode (cname = "gst_data_queue_is_full")] public bool is_full (); - [CCode (cname = "gst_data_queue_limits_changed")] public void limits_changed (); - [CCode (cname = "gst_data_queue_peek")] public bool peek (Gst.Base.DataQueueItem item); - [CCode (cname = "gst_data_queue_pop")] public bool pop (Gst.Base.DataQueueItem item); - [CCode (cname = "gst_data_queue_push")] public bool push (Gst.Base.DataQueueItem item); - [CCode (cname = "gst_data_queue_push_force")] public bool push_force (Gst.Base.DataQueueItem item); - [CCode (cname = "gst_data_queue_set_flushing")] public void set_flushing (bool flushing); [NoAccessorMethod] public uint current_level_bytes { get; } @@ -465,7 +422,7 @@ namespace Gst { public void free (); public void init (); } - [CCode (cheader_filename = "gst/base/base.h", cname = "GstPushSrc", type_id = "gst_push_src_get_type ()")] + [CCode (cheader_filename = "gst/base/base.h", cname = "GstPushSrc", lower_case_cprefix = "gst_push_src_", type_id = "gst_push_src_get_type ()")] [GIR (name = "PushSrc")] public class PushSrc : Gst.Base.Src { [CCode (has_construct_function = false)] diff --git a/vapi/gstreamer-check-1.0.vapi b/vapi/gstreamer-check-1.0.vapi index d4344cb7a6..bf939f3ccc 100644 --- a/vapi/gstreamer-check-1.0.vapi +++ b/vapi/gstreamer-check-1.0.vapi @@ -3,7 +3,7 @@ [CCode (cprefix = "Gst", gir_namespace = "GstCheck", gir_version = "1.0", lower_case_cprefix = "gst_")] namespace Gst { namespace Check { - [CCode (cheader_filename = "gst/check/gstbufferstraw.h,gst/check/gstcheck.h,gst/check/gstconsistencychecker.h,gst/check/internal-check.h", cname = "GstStreamConsistency", cprefix = "gst_consistency_checker_", lower_case_cprefix = "gst_consistency_checker_")] + [CCode (cheader_filename = "gst/check/gstbufferstraw.h,gst/check/gstcheck.h,gst/check/gstconsistencychecker.h,gst/check/internal-check.h", cname = "GstStreamConsistency", lower_case_cprefix = "gst_consistency_checker_")] [Compact] [GIR (name = "StreamConsistency")] public class StreamConsistency { @@ -12,37 +12,25 @@ namespace Gst { public void free (); public void reset (); } - [CCode (cheader_filename = "gst/check/check.h", cname = "GstTestClock", type_id = "gst_test_clock_get_type ()")] + [CCode (cheader_filename = "gst/check/check.h", cname = "GstTestClock", lower_case_cprefix = "gst_test_clock_", type_id = "gst_test_clock_get_type ()")] [GIR (name = "TestClock")] public class TestClock : Gst.Clock { - [CCode (cname = "gst_test_clock_new", has_construct_function = false, type = "GstClock*")] + [CCode (has_construct_function = false, type = "GstClock*")] public TestClock (); - [CCode (cname = "gst_test_clock_advance_time")] public void advance_time (Gst.ClockTimeDiff delta); - [CCode (cname = "gst_test_clock_get_next_entry_time")] public Gst.ClockTime get_next_entry_time (); - [CCode (cname = "gst_test_clock_has_id")] public bool has_id (Gst.ClockID id); - [CCode (cname = "gst_test_clock_id_list_get_latest_time")] public static Gst.ClockTime id_list_get_latest_time (GLib.List<Gst.ClockID?>? pending_list); - [CCode (cname = "gst_test_clock_peek_id_count")] public uint peek_id_count (); - [CCode (cname = "gst_test_clock_peek_next_pending_id")] public bool peek_next_pending_id (out Gst.ClockID pending_id); - [CCode (cname = "gst_test_clock_process_id_list")] public uint process_id_list (GLib.List<Gst.ClockID?>? pending_list); - [CCode (cname = "gst_test_clock_process_next_clock_id")] public Gst.ClockID process_next_clock_id (); - [CCode (cname = "gst_test_clock_set_time")] public void set_time (Gst.ClockTime new_time); - [CCode (cname = "gst_test_clock_wait_for_multiple_pending_ids")] public void wait_for_multiple_pending_ids (uint count, out GLib.List<Gst.ClockID?> pending_list); - [CCode (cname = "gst_test_clock_wait_for_next_pending_id")] public void wait_for_next_pending_id (out Gst.ClockID pending_id); - [CCode (cname = "gst_test_clock_wait_for_pending_id_count")] [Deprecated] public void wait_for_pending_id_count (uint count); - [CCode (cname = "gst_test_clock_new_with_start_time", has_construct_function = false, type = "GstClock*")] + [CCode (has_construct_function = false, type = "GstClock*")] public TestClock.with_start_time (Gst.ClockTime start_time); [NoAccessorMethod] public uint64 start_time { get; construct; } diff --git a/vapi/gstreamer-controller-1.0.vapi b/vapi/gstreamer-controller-1.0.vapi index de0d4e8ddc..dacf931c76 100644 --- a/vapi/gstreamer-controller-1.0.vapi +++ b/vapi/gstreamer-controller-1.0.vapi @@ -3,10 +3,10 @@ [CCode (cprefix = "Gst", gir_namespace = "GstController", gir_version = "1.0", lower_case_cprefix = "gst_")] namespace Gst { namespace Controller { - [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstARGBControlBinding", type_id = "gst_argb_control_binding_get_type ()")] + [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstARGBControlBinding", lower_case_cprefix = "gst_argb_control_binding_", type_id = "gst_argb_control_binding_get_type ()")] [GIR (name = "ARGBControlBinding")] public class ARGBControlBinding : Gst.ControlBinding { - [CCode (cname = "gst_argb_control_binding_new", has_construct_function = false, type = "GstControlBinding*")] + [CCode (has_construct_function = false, type = "GstControlBinding*")] public ARGBControlBinding (Gst.Object object, string property_name, Gst.ControlSource cs_a, Gst.ControlSource cs_r, Gst.ControlSource cs_g, Gst.ControlSource cs_b); [NoAccessorMethod] public Gst.ControlSource control_source_a { owned get; set construct; } @@ -17,26 +17,26 @@ namespace Gst { [NoAccessorMethod] public Gst.ControlSource control_source_r { owned get; set construct; } } - [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstDirectControlBinding", type_id = "gst_direct_control_binding_get_type ()")] + [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstDirectControlBinding", lower_case_cprefix = "gst_direct_control_binding_", type_id = "gst_direct_control_binding_get_type ()")] [GIR (name = "DirectControlBinding")] public class DirectControlBinding : Gst.ControlBinding { - [CCode (cname = "gst_direct_control_binding_new", has_construct_function = false, type = "GstControlBinding*")] + [CCode (has_construct_function = false, type = "GstControlBinding*")] public DirectControlBinding (Gst.Object object, string property_name, Gst.ControlSource cs); [NoAccessorMethod] public Gst.ControlSource control_source { owned get; set construct; } } - [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstInterpolationControlSource", type_id = "gst_interpolation_control_source_get_type ()")] + [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstInterpolationControlSource", lower_case_cprefix = "gst_interpolation_control_source_", type_id = "gst_interpolation_control_source_get_type ()")] [GIR (name = "InterpolationControlSource")] public class InterpolationControlSource : Gst.Controller.TimedValueControlSource { - [CCode (cname = "gst_interpolation_control_source_new", has_construct_function = false, type = "GstControlSource*")] + [CCode (has_construct_function = false, type = "GstControlSource*")] public InterpolationControlSource (); [NoAccessorMethod] public Gst.Controller.InterpolationMode mode { get; set; } } - [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstLFOControlSource", type_id = "gst_lfo_control_source_get_type ()")] + [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstLFOControlSource", lower_case_cprefix = "gst_lfo_control_source_", type_id = "gst_lfo_control_source_get_type ()")] [GIR (name = "LFOControlSource")] public class LFOControlSource : Gst.ControlSource { - [CCode (cname = "gst_lfo_control_source_new", has_construct_function = false, type = "GstControlSource*")] + [CCode (has_construct_function = false, type = "GstControlSource*")] public LFOControlSource (); [NoAccessorMethod] public double amplitude { get; set; } @@ -49,7 +49,7 @@ namespace Gst { [NoAccessorMethod] public Gst.Controller.LFOWaveform waveform { get; set; } } - [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstTimedValueControlSource", type_id = "gst_timed_value_control_source_get_type ()")] + [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstTimedValueControlSource", lower_case_cprefix = "gst_timed_value_control_source_", type_id = "gst_timed_value_control_source_get_type ()")] [GIR (name = "TimedValueControlSource")] public abstract class TimedValueControlSource : Gst.ControlSource { public weak GLib.Mutex @lock; @@ -58,25 +58,18 @@ namespace Gst { public GLib.Sequence<Gst.Controller.ControlPoint?> values; [CCode (has_construct_function = false)] protected TimedValueControlSource (); - [CCode (cname = "gst_timed_value_control_source_find_control_point_iter")] public unowned GLib.SequenceIter find_control_point_iter (Gst.ClockTime timestamp); - [CCode (cname = "gst_timed_value_control_source_get_all")] public GLib.List<weak Gst.TimedValue?> get_all (); - [CCode (cname = "gst_timed_value_control_source_get_count")] public int get_count (); - [CCode (cname = "gst_timed_value_control_source_set")] public bool @set (Gst.ClockTime timestamp, double value); - [CCode (cname = "gst_timed_value_control_source_set_from_list")] public bool set_from_list (GLib.SList<Gst.TimedValue?> timedvalues); - [CCode (cname = "gst_timed_value_control_source_unset")] public bool unset (Gst.ClockTime timestamp); - [CCode (cname = "gst_timed_value_control_source_unset_all")] public void unset_all (); } - [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstTriggerControlSource", type_id = "gst_trigger_control_source_get_type ()")] + [CCode (cheader_filename = "gst/controller/controller.h", cname = "GstTriggerControlSource", lower_case_cprefix = "gst_trigger_control_source_", type_id = "gst_trigger_control_source_get_type ()")] [GIR (name = "TriggerControlSource")] public class TriggerControlSource : Gst.Controller.TimedValueControlSource { - [CCode (cname = "gst_trigger_control_source_new", has_construct_function = false, type = "GstControlSource*")] + [CCode (has_construct_function = false, type = "GstControlSource*")] public TriggerControlSource (); [NoAccessorMethod] public int64 tolerance { get; set; } diff --git a/vapi/gstreamer-pbutils-1.0.vapi b/vapi/gstreamer-pbutils-1.0.vapi index f493c5bad3..dd211cf225 100644 --- a/vapi/gstreamer-pbutils-1.0.vapi +++ b/vapi/gstreamer-pbutils-1.0.vapi @@ -35,18 +35,14 @@ namespace Gst { public static unowned string get_profile (uint8 vis_obj_seq, uint len); } } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscoverer", type_id = "gst_discoverer_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscoverer", lower_case_cprefix = "gst_discoverer_", type_id = "gst_discoverer_get_type ()")] [GIR (name = "Discoverer")] public class Discoverer : GLib.Object { - [CCode (cname = "gst_discoverer_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public Discoverer (Gst.ClockTime timeout) throws GLib.Error; - [CCode (cname = "gst_discoverer_discover_uri")] public Gst.PbUtils.DiscovererInfo discover_uri (string uri) throws GLib.Error; - [CCode (cname = "gst_discoverer_discover_uri_async")] public bool discover_uri_async (string uri); - [CCode (cname = "gst_discoverer_start")] public void start (); - [CCode (cname = "gst_discoverer_stop")] public void stop (); [NoAccessorMethod] public uint64 timeout { get; set construct; } @@ -55,247 +51,165 @@ namespace Gst { public virtual signal void source_setup (Gst.Element source); public virtual signal void starting (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererAudioInfo", type_id = "gst_discoverer_audio_info_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererAudioInfo", lower_case_cprefix = "gst_discoverer_audio_info_", type_id = "gst_discoverer_audio_info_get_type ()")] [GIR (name = "DiscovererAudioInfo")] public class DiscovererAudioInfo : Gst.PbUtils.DiscovererStreamInfo { [CCode (has_construct_function = false)] protected DiscovererAudioInfo (); - [CCode (cname = "gst_discoverer_audio_info_get_bitrate")] public uint get_bitrate (); - [CCode (cname = "gst_discoverer_audio_info_get_channels")] public uint get_channels (); - [CCode (cname = "gst_discoverer_audio_info_get_depth")] public uint get_depth (); - [CCode (cname = "gst_discoverer_audio_info_get_language")] public unowned string get_language (); - [CCode (cname = "gst_discoverer_audio_info_get_max_bitrate")] public uint get_max_bitrate (); - [CCode (cname = "gst_discoverer_audio_info_get_sample_rate")] public uint get_sample_rate (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererContainerInfo", type_id = "gst_discoverer_container_info_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererContainerInfo", lower_case_cprefix = "gst_discoverer_container_info_", type_id = "gst_discoverer_container_info_get_type ()")] [GIR (name = "DiscovererContainerInfo")] public class DiscovererContainerInfo : Gst.PbUtils.DiscovererStreamInfo { [CCode (has_construct_function = false)] protected DiscovererContainerInfo (); - [CCode (cname = "gst_discoverer_container_info_get_streams")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_streams (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererInfo", type_id = "gst_discoverer_info_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererInfo", lower_case_cprefix = "gst_discoverer_info_", type_id = "gst_discoverer_info_get_type ()")] [GIR (name = "DiscovererInfo")] public class DiscovererInfo : GLib.Object { [CCode (has_construct_function = false)] protected DiscovererInfo (); - [CCode (cname = "gst_discoverer_info_copy")] public Gst.PbUtils.DiscovererInfo copy (); - [CCode (cname = "gst_discoverer_info_get_audio_streams")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_audio_streams (); - [CCode (cname = "gst_discoverer_info_get_container_streams")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_container_streams (); - [CCode (cname = "gst_discoverer_info_get_duration")] public Gst.ClockTime get_duration (); - [CCode (cname = "gst_discoverer_info_get_misc")] [Deprecated] public unowned Gst.Structure get_misc (); - [CCode (array_length = false, array_null_terminated = true, cname = "gst_discoverer_info_get_missing_elements_installer_details")] + [CCode (array_length = false, array_null_terminated = true)] public string[] get_missing_elements_installer_details (); - [CCode (cname = "gst_discoverer_info_get_result")] public Gst.PbUtils.DiscovererResult get_result (); - [CCode (cname = "gst_discoverer_info_get_seekable")] public bool get_seekable (); - [CCode (cname = "gst_discoverer_info_get_stream_info")] public Gst.PbUtils.DiscovererStreamInfo get_stream_info (); - [CCode (cname = "gst_discoverer_info_get_stream_list")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_stream_list (); - [CCode (cname = "gst_discoverer_info_get_streams")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_streams (GLib.Type streamtype); - [CCode (cname = "gst_discoverer_info_get_subtitle_streams")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_subtitle_streams (); - [CCode (cname = "gst_discoverer_info_get_tags")] public unowned Gst.TagList get_tags (); - [CCode (cname = "gst_discoverer_info_get_toc")] public unowned Gst.Toc get_toc (); - [CCode (cname = "gst_discoverer_info_get_uri")] public unowned string get_uri (); - [CCode (cname = "gst_discoverer_info_get_video_streams")] public GLib.List<Gst.PbUtils.DiscovererStreamInfo> get_video_streams (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererStreamInfo", type_id = "gst_discoverer_stream_info_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererStreamInfo", lower_case_cprefix = "gst_discoverer_stream_info_", type_id = "gst_discoverer_stream_info_get_type ()")] [GIR (name = "DiscovererStreamInfo")] public class DiscovererStreamInfo : GLib.Object { [CCode (has_construct_function = false)] protected DiscovererStreamInfo (); - [CCode (cname = "gst_discoverer_stream_info_get_caps")] public Gst.Caps get_caps (); - [CCode (cname = "gst_discoverer_stream_info_get_misc")] [Deprecated] public unowned Gst.Structure get_misc (); - [CCode (cname = "gst_discoverer_stream_info_get_next")] public Gst.PbUtils.DiscovererStreamInfo get_next (); - [CCode (cname = "gst_discoverer_stream_info_get_previous")] public Gst.PbUtils.DiscovererStreamInfo get_previous (); - [CCode (cname = "gst_discoverer_stream_info_get_stream_id")] public unowned string get_stream_id (); - [CCode (cname = "gst_discoverer_stream_info_get_stream_type_nick")] public unowned string get_stream_type_nick (); - [CCode (cname = "gst_discoverer_stream_info_get_tags")] public unowned Gst.TagList get_tags (); - [CCode (cname = "gst_discoverer_stream_info_get_toc")] public unowned Gst.Toc get_toc (); - [CCode (cname = "gst_discoverer_stream_info_list_free")] public static void list_free (GLib.List<Gst.PbUtils.DiscovererStreamInfo> infos); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererSubtitleInfo", type_id = "gst_discoverer_subtitle_info_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererSubtitleInfo", lower_case_cprefix = "gst_discoverer_subtitle_info_", type_id = "gst_discoverer_subtitle_info_get_type ()")] [GIR (name = "DiscovererSubtitleInfo")] public class DiscovererSubtitleInfo : Gst.PbUtils.DiscovererStreamInfo { [CCode (has_construct_function = false)] protected DiscovererSubtitleInfo (); - [CCode (cname = "gst_discoverer_subtitle_info_get_language")] public unowned string get_language (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererVideoInfo", type_id = "gst_discoverer_video_info_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererVideoInfo", lower_case_cprefix = "gst_discoverer_video_info_", type_id = "gst_discoverer_video_info_get_type ()")] [GIR (name = "DiscovererVideoInfo")] public class DiscovererVideoInfo : Gst.PbUtils.DiscovererStreamInfo { [CCode (has_construct_function = false)] protected DiscovererVideoInfo (); - [CCode (cname = "gst_discoverer_video_info_get_bitrate")] public uint get_bitrate (); - [CCode (cname = "gst_discoverer_video_info_get_depth")] public uint get_depth (); - [CCode (cname = "gst_discoverer_video_info_get_framerate_denom")] public uint get_framerate_denom (); - [CCode (cname = "gst_discoverer_video_info_get_framerate_num")] public uint get_framerate_num (); - [CCode (cname = "gst_discoverer_video_info_get_height")] public uint get_height (); - [CCode (cname = "gst_discoverer_video_info_get_max_bitrate")] public uint get_max_bitrate (); - [CCode (cname = "gst_discoverer_video_info_get_par_denom")] public uint get_par_denom (); - [CCode (cname = "gst_discoverer_video_info_get_par_num")] public uint get_par_num (); - [CCode (cname = "gst_discoverer_video_info_get_width")] public uint get_width (); - [CCode (cname = "gst_discoverer_video_info_is_image")] public bool is_image (); - [CCode (cname = "gst_discoverer_video_info_is_interlaced")] public bool is_interlaced (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingAudioProfile", type_id = "gst_encoding_audio_profile_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingAudioProfile", lower_case_cprefix = "gst_encoding_audio_profile_", type_id = "gst_encoding_audio_profile_get_type ()")] [GIR (name = "EncodingAudioProfile")] public class EncodingAudioProfile : Gst.PbUtils.EncodingProfile { - [CCode (cname = "gst_encoding_audio_profile_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public EncodingAudioProfile (Gst.Caps format, string? preset, Gst.Caps? restriction, uint presence); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingContainerProfile", type_id = "gst_encoding_container_profile_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingContainerProfile", lower_case_cprefix = "gst_encoding_container_profile_", type_id = "gst_encoding_container_profile_get_type ()")] [GIR (name = "EncodingContainerProfile")] public class EncodingContainerProfile : Gst.PbUtils.EncodingProfile { - [CCode (cname = "gst_encoding_container_profile_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public EncodingContainerProfile (string? name, string? description, Gst.Caps format, string? preset); - [CCode (cname = "gst_encoding_container_profile_add_profile")] public bool add_profile (owned Gst.PbUtils.EncodingProfile profile); - [CCode (cname = "gst_encoding_container_profile_contains_profile")] public bool contains_profile (Gst.PbUtils.EncodingProfile profile); - [CCode (cname = "gst_encoding_container_profile_get_profiles")] public unowned GLib.List<Gst.PbUtils.EncodingProfile> get_profiles (); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingProfile", type_id = "gst_encoding_profile_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingProfile", lower_case_cprefix = "gst_encoding_profile_", type_id = "gst_encoding_profile_get_type ()")] [GIR (name = "EncodingProfile")] public class EncodingProfile : GLib.Object { [CCode (has_construct_function = false)] protected EncodingProfile (); - [CCode (cname = "gst_encoding_profile_find")] public static Gst.PbUtils.EncodingProfile find (string targetname, string profilename, string? category); - [CCode (cname = "gst_encoding_profile_from_discoverer")] public static Gst.PbUtils.EncodingProfile from_discoverer (Gst.PbUtils.DiscovererInfo info); - [CCode (cname = "gst_encoding_profile_get_description")] public unowned string get_description (); - [CCode (cname = "gst_encoding_profile_get_file_extension")] public unowned string get_file_extension (); - [CCode (cname = "gst_encoding_profile_get_format")] public Gst.Caps get_format (); - [CCode (cname = "gst_encoding_profile_get_input_caps")] public Gst.Caps get_input_caps (); - [CCode (cname = "gst_encoding_profile_get_name")] public unowned string get_name (); - [CCode (cname = "gst_encoding_profile_get_presence")] public uint get_presence (); - [CCode (cname = "gst_encoding_profile_get_preset")] public unowned string get_preset (); - [CCode (cname = "gst_encoding_profile_get_preset_name")] public unowned string get_preset_name (); - [CCode (cname = "gst_encoding_profile_get_restriction")] public Gst.Caps get_restriction (); - [CCode (cname = "gst_encoding_profile_get_type_nick")] public unowned string get_type_nick (); - [CCode (cname = "gst_encoding_profile_is_equal")] public bool is_equal (Gst.PbUtils.EncodingProfile b); - [CCode (cname = "gst_encoding_profile_set_description")] public void set_description (string description); - [CCode (cname = "gst_encoding_profile_set_format")] public void set_format (Gst.Caps format); - [CCode (cname = "gst_encoding_profile_set_name")] public void set_name (string name); - [CCode (cname = "gst_encoding_profile_set_presence")] public void set_presence (uint presence); - [CCode (cname = "gst_encoding_profile_set_preset")] public void set_preset (string preset); - [CCode (cname = "gst_encoding_profile_set_preset_name")] public void set_preset_name (string preset_name); - [CCode (cname = "gst_encoding_profile_set_restriction")] public void set_restriction (owned Gst.Caps restriction); [NoAccessorMethod] public Gst.Caps restriction_caps { owned get; set; } } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingTarget", type_id = "gst_encoding_target_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingTarget", lower_case_cprefix = "gst_encoding_target_", type_id = "gst_encoding_target_get_type ()")] [GIR (name = "EncodingTarget")] public class EncodingTarget : GLib.Object { - [CCode (cname = "gst_encoding_target_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public EncodingTarget (string name, string category, string description, GLib.List<Gst.PbUtils.EncodingProfile> profiles); - [CCode (cname = "gst_encoding_target_add_profile")] public bool add_profile (owned Gst.PbUtils.EncodingProfile profile); - [CCode (cname = "gst_encoding_target_get_category")] public unowned string get_category (); - [CCode (cname = "gst_encoding_target_get_description")] public unowned string get_description (); - [CCode (cname = "gst_encoding_target_get_name")] public unowned string get_name (); - [CCode (cname = "gst_encoding_target_get_profile")] public Gst.PbUtils.EncodingProfile get_profile (string name); - [CCode (cname = "gst_encoding_target_get_profiles")] public unowned GLib.List<Gst.PbUtils.EncodingProfile> get_profiles (); - [CCode (cname = "gst_encoding_target_load")] public static Gst.PbUtils.EncodingTarget load (string name, string? category) throws GLib.Error; - [CCode (cname = "gst_encoding_target_load_from_file")] public static Gst.PbUtils.EncodingTarget load_from_file (string filepath) throws GLib.Error; - [CCode (cname = "gst_encoding_target_save")] public bool save () throws GLib.Error; - [CCode (cname = "gst_encoding_target_save_to_file")] public bool save_to_file (string filepath) throws GLib.Error; } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingVideoProfile", type_id = "gst_encoding_video_profile_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstEncodingVideoProfile", lower_case_cprefix = "gst_encoding_video_profile_", type_id = "gst_encoding_video_profile_get_type ()")] [GIR (name = "EncodingVideoProfile")] public class EncodingVideoProfile : Gst.PbUtils.EncodingProfile { - [CCode (cname = "gst_encoding_video_profile_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public EncodingVideoProfile (Gst.Caps format, string? preset, Gst.Caps? restriction, uint presence); - [CCode (cname = "gst_encoding_video_profile_get_pass")] public uint get_pass (); - [CCode (cname = "gst_encoding_video_profile_get_variableframerate")] public bool get_variableframerate (); - [CCode (cname = "gst_encoding_video_profile_set_pass")] public void set_pass (uint pass); - [CCode (cname = "gst_encoding_video_profile_set_variableframerate")] public void set_variableframerate (bool variableframerate); } - [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstInstallPluginsContext", copy_function = "g_boxed_copy", free_function = "g_boxed_free", type_id = "gst_install_plugins_context_get_type ()")] + [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstInstallPluginsContext", copy_function = "g_boxed_copy", free_function = "g_boxed_free", lower_case_cprefix = "gst_install_plugins_context_", type_id = "gst_install_plugins_context_get_type ()")] [Compact] [GIR (name = "InstallPluginsContext")] public class InstallPluginsContext { - [CCode (cname = "gst_install_plugins_context_new", has_construct_function = false)] + [CCode (has_construct_function = false)] public InstallPluginsContext (); - [CCode (cname = "gst_install_plugins_context_free")] public void free (); - [CCode (cname = "gst_install_plugins_context_set_xid")] public void set_xid (uint xid); } [CCode (cheader_filename = "gst/pbutils/pbutils.h", cname = "GstDiscovererResult", cprefix = "GST_DISCOVERER_", type_id = "gst_discoverer_result_get_type ()")] diff --git a/vapi/gstreamer-video-1.0.vapi b/vapi/gstreamer-video-1.0.vapi index 5b1f4b5851..658a820b0d 100644 --- a/vapi/gstreamer-video-1.0.vapi +++ b/vapi/gstreamer-video-1.0.vapi @@ -50,7 +50,7 @@ namespace Gst { public Gst.Video.CodecState @ref (); public void unref (); } - [CCode (cheader_filename = "gst/video/video.h", cname = "GstColorBalanceChannel", type_id = "gst_color_balance_channel_get_type ()")] + [CCode (cheader_filename = "gst/video/video.h", cname = "GstColorBalanceChannel", lower_case_cprefix = "gst_color_balance_channel_", type_id = "gst_color_balance_channel_get_type ()")] [GIR (name = "ColorBalanceChannel")] public class ColorBalanceChannel : GLib.Object { public weak string label; @@ -244,7 +244,7 @@ namespace Gst { [NoAccessorMethod] public bool show_preroll_frame { get; set construct; } } - [CCode (cheader_filename = "gst/video/video.h", cname = "GstColorBalance", type_cname = "GstColorBalanceInterface", type_id = "gst_color_balance_get_type ()")] + [CCode (cheader_filename = "gst/video/video.h", cname = "GstColorBalance", lower_case_cprefix = "gst_color_balance_", type_cname = "GstColorBalanceInterface", type_id = "gst_color_balance_get_type ()")] [GIR (name = "ColorBalance")] public interface ColorBalance : GLib.Object { public abstract Gst.Video.ColorBalanceType get_balance_type (); @@ -254,53 +254,31 @@ namespace Gst { [HasEmitter] public virtual signal void value_changed (Gst.Video.ColorBalanceChannel channel, int value); } - [CCode (cheader_filename = "gst/video/video.h", cname = "GstNavigation", type_cname = "GstNavigationInterface", type_id = "gst_navigation_get_type ()")] + [CCode (cheader_filename = "gst/video/video.h", cname = "GstNavigation", lower_case_cprefix = "gst_navigation_", type_cname = "GstNavigationInterface", type_id = "gst_navigation_get_type ()")] [GIR (name = "Navigation")] public interface Navigation : GLib.Object { - [CCode (cname = "gst_navigation_event_get_type")] public static Gst.Video.NavigationEventType event_get_type (Gst.Event event); - [CCode (cname = "gst_navigation_event_parse_command")] public static bool event_parse_command (Gst.Event event, Gst.Video.NavigationCommand command); - [CCode (cname = "gst_navigation_event_parse_key_event")] public static bool event_parse_key_event (Gst.Event event, string key); - [CCode (cname = "gst_navigation_event_parse_mouse_button_event")] public static bool event_parse_mouse_button_event (Gst.Event event, int button, double x, double y); - [CCode (cname = "gst_navigation_event_parse_mouse_move_event")] public static bool event_parse_mouse_move_event (Gst.Event event, double x, double y); - [CCode (cname = "gst_navigation_message_get_type")] public static Gst.Video.NavigationMessageType message_get_type (Gst.Message message); - [CCode (cname = "gst_navigation_message_new_angles_changed")] public static Gst.Message message_new_angles_changed (Gst.Object src, uint cur_angle, uint n_angles); - [CCode (cname = "gst_navigation_message_new_commands_changed")] public static Gst.Message message_new_commands_changed (Gst.Object src); - [CCode (cname = "gst_navigation_message_new_mouse_over")] public static Gst.Message message_new_mouse_over (Gst.Object src, bool active); - [CCode (cname = "gst_navigation_message_parse_angles_changed")] public static bool message_parse_angles_changed (Gst.Message message, uint cur_angle, uint n_angles); - [CCode (cname = "gst_navigation_message_parse_mouse_over")] public static bool message_parse_mouse_over (Gst.Message message, bool active); - [CCode (cname = "gst_navigation_query_get_type")] public static Gst.Video.NavigationQueryType query_get_type (Gst.Query query); - [CCode (cname = "gst_navigation_query_new_angles")] public static Gst.Query query_new_angles (); - [CCode (cname = "gst_navigation_query_new_commands")] public static Gst.Query query_new_commands (); - [CCode (cname = "gst_navigation_query_parse_angles")] public static bool query_parse_angles (Gst.Query query, uint cur_angle, uint n_angles); - [CCode (cname = "gst_navigation_query_parse_commands_length")] public static bool query_parse_commands_length (Gst.Query query, out uint n_cmds); - [CCode (cname = "gst_navigation_query_parse_commands_nth")] public static bool query_parse_commands_nth (Gst.Query query, uint nth, out Gst.Video.NavigationCommand cmd); - [CCode (cname = "gst_navigation_query_set_angles")] public static void query_set_angles (Gst.Query query, uint cur_angle, uint n_angles); - [CCode (cname = "gst_navigation_query_set_commandsv")] public static void query_set_commandsv (Gst.Query query, int n_cmds, Gst.Video.NavigationCommand cmds); - [CCode (cname = "gst_navigation_send_command")] public void send_command (Gst.Video.NavigationCommand command); public abstract void send_event (Gst.Structure structure); - [CCode (cname = "gst_navigation_send_key_event")] public void send_key_event (string event, string key); - [CCode (cname = "gst_navigation_send_mouse_event")] public void send_mouse_event (string event, int button, double x, double y); } [CCode (cheader_filename = "gst/video/video.h", type_id = "gst_video_orientation_get_type ()")] diff --git a/vapi/rest-0.7.vapi b/vapi/rest-0.7.vapi index 444fb73621..bce196ee4a 100644 --- a/vapi/rest-0.7.vapi +++ b/vapi/rest-0.7.vapi @@ -2,7 +2,7 @@ [CCode (cprefix = "Rest", gir_namespace = "Rest", gir_version = "0.7", lower_case_cprefix = "rest_")] namespace Rest { - [CCode (cheader_filename = "rest/oauth2-proxy.h", cname = "OAuth2Proxy", cprefix = "oauth2_proxy_", type_id = "oauth2_proxy_get_type ()")] + [CCode (cheader_filename = "rest/oauth2-proxy.h", cname = "OAuth2Proxy", lower_case_cprefix = "oauth2_proxy_", type_id = "oauth2_proxy_get_type ()")] public class OAuth2Proxy : Rest.Proxy { [CCode (has_construct_function = false, type = "RestProxy*")] public OAuth2Proxy (string client_id, string auth_endpoint, string url_format, bool binding_required); @@ -19,12 +19,12 @@ namespace Rest { [NoAccessorMethod] public string client_id { owned get; construct; } } - [CCode (cheader_filename = "rest/oauth2-proxy-call.h", cname = "OAuth2ProxyCall", cprefix = "oauth2_proxy_call_", type_id = "oauth2_proxy_call_get_type ()")] + [CCode (cheader_filename = "rest/oauth2-proxy-call.h", cname = "OAuth2ProxyCall", lower_case_cprefix = "oauth2_proxy_call_", type_id = "oauth2_proxy_call_get_type ()")] public class OAuth2ProxyCall : Rest.ProxyCall { [CCode (has_construct_function = false)] protected OAuth2ProxyCall (); } - [CCode (cheader_filename = "rest/oauth-proxy.h", cname = "OAuthProxy", cprefix = "oauth_proxy_", type_id = "oauth_proxy_get_type ()")] + [CCode (cheader_filename = "rest/oauth-proxy.h", cname = "OAuthProxy", lower_case_cprefix = "oauth_proxy_", type_id = "oauth_proxy_get_type ()")] public class OAuthProxy : Rest.Proxy { [CCode (has_construct_function = false, type = "RestProxy*")] public OAuthProxy (string consumer_key, string consumer_secret, string url_format, bool binding_required); @@ -54,7 +54,7 @@ namespace Rest { public string token { get; set; } public string token_secret { get; set; } } - [CCode (cheader_filename = "rest/oauth-proxy-call.h", cname = "OAuthProxyCall", cprefix = "oauth_proxy_call_", type_id = "oauth_proxy_call_get_type ()")] + [CCode (cheader_filename = "rest/oauth-proxy-call.h", cname = "OAuthProxyCall", lower_case_cprefix = "oauth_proxy_call_", type_id = "oauth_proxy_call_get_type ()")] public class OAuthProxyCall : Rest.ProxyCall { [CCode (has_construct_function = false)] protected OAuthProxyCall ();
ceb5861998de2e1a07a7279d3f1d26ecfb2c2dca
Mylyn Reviews
Simplified some column handling logic -avoid repetition of column handling,output,...
p
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java new file mode 100644 index 00000000..c5400b7d --- /dev/null +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.reviews.tasks.ui.editors; + +import org.eclipse.swt.graphics.Image; +/** + * @author mattk + * + * @param <T> + */ +public class ColumnLabelProvider<T> extends TableLabelProvider { + + private IColumnSpec<T>[] specs; + + public ColumnLabelProvider(IColumnSpec<T>[] specs) { + this.specs = specs; + } + + @SuppressWarnings("unchecked") + @Override + public Image getColumnImage(Object element, int columnIndex) { + return specs[columnIndex].getImage((T) element); + } + + @SuppressWarnings("unchecked") + @Override + public String getColumnText(Object element, int columnIndex) { + return specs[columnIndex].getText((T) element); + } + +} diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java new file mode 100644 index 00000000..bb87f4f7 --- /dev/null +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java @@ -0,0 +1,28 @@ +/******************************************************************************* + * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.reviews.tasks.ui.editors; + +import org.eclipse.swt.graphics.Image; + +/** + * + * @author mattk + * + * @param <T> + */ +public interface IColumnSpec<T> { + public String getTitle(); + + public String getText(T value); + + public Image getImage(T value); + +} diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java index 275a43a7..12875b04 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java @@ -21,7 +21,6 @@ import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; @@ -84,13 +83,68 @@ public void createControl(final Composite parent, FormToolkit toolkit) { summarySection.setClient(reviewResultsComposite); setSection(toolkit, summarySection); } + enum Column implements IColumnSpec<ITreeNode> { + TASK("Task") { + @Override + public String getText(ITreeNode value) { + return value.getTaskId(); + } + }, + RESULT(Messages.ReviewSummaryTaskEditorPart_Header_Result) { + @Override + public String getText(ITreeNode value) { + return value.getResult() != null ? value.getResult().name() + : ""; + } + + @Override + public Image getImage(ITreeNode value) { + if (value.getResult() == null) + return null; + switch (value.getResult()) { + case FAIL: + return Images.REVIEW_RESULT_FAILED.createImage(); + case WARNING: + return Images.REVIEW_RESULT_WARNING.createImage(); + case PASSED: + return Images.REVIEW_RESULT_PASSED.createImage(); + case TODO: + return Images.REVIEW_RESULT_NONE.createImage(); + } + return null; + } + }, + DESCRIPTION("Description") { + @Override + public String getText(ITreeNode value) { + return value.getDescription(); + } + }, + WHO("Who") { + @Override + public String getText(ITreeNode value) { + return value.getPerson(); + } + }; + + private String title; + + private Column(String title) { + this.title = title; + } + + public String getTitle() { + return title; + } + + public String getText(ITreeNode value) { + return value != null ? value.toString() : ""; + } + + public Image getImage(ITreeNode value) { + return null; + } - private TreeViewerColumn createColumn(TreeViewer tree, String columnTitle) { - TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); - column.getColumn().setText(columnTitle); - column.getColumn().setWidth(100); - column.getColumn().setResizable(true); - return column; } private TreeViewer createResultsViewer(Composite reviewResultsComposite, @@ -105,67 +159,19 @@ private TreeViewer createResultsViewer(Composite reviewResultsComposite, } tree.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); - TreeViewer reviewResults = new TreeViewer(tree); - createColumn(reviewResults, "Task"); - createColumn(reviewResults, - Messages.ReviewSummaryTaskEditorPart_Header_Result); - createColumn(reviewResults, "Description"); - createColumn(reviewResults, "Who"); + TreeViewer reviewResults = createTreeWithColumns(tree); reviewResults.setContentProvider(new ReviewResultContentProvider()); - reviewResults.setLabelProvider(new TableLabelProvider() { - private static final int COLUMN_TASK_ID = 0; - private static final int COLUMN_RESULT = 1; - private static final int COLUMN_DESCRIPTION = 2; - private static final int COLUMN_WHO = 3; - - public Image getColumnImage(Object element, int columnIndex) { - if (columnIndex == COLUMN_RESULT) { - ITreeNode node = (ITreeNode) element; - if (node.getResult() == null) - return null; - switch (node.getResult()) { - case FAIL: - return Images.REVIEW_RESULT_FAILED.createImage(); - case WARNING: - return Images.REVIEW_RESULT_WARNING.createImage(); - case PASSED: - return Images.REVIEW_RESULT_PASSED.createImage(); - case TODO: - return Images.REVIEW_RESULT_NONE.createImage(); - - } - } - return null; - } - - public String getColumnText(Object element, int columnIndex) { - - ITreeNode node = (ITreeNode) element; - switch (columnIndex) { - case COLUMN_TASK_ID: - return node.getTaskId(); - case COLUMN_RESULT: - return node.getResult() != null ? node.getResult().name() - : ""; - case COLUMN_DESCRIPTION: - return node.getDescription(); - case COLUMN_WHO: - return node.getPerson(); - default: - return null; - } - } - - }); + reviewResults.setLabelProvider(new ColumnLabelProvider<ITreeNode>( + Column.values())); reviewResults.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (!event.getSelection().isEmpty()) { ITreeNode treeNode = (ITreeNode) ((IStructuredSelection) event .getSelection()).getFirstElement(); - if(treeNode instanceof ReviewResultNode) { + if (treeNode instanceof ReviewResultNode) { treeNode = treeNode.getParent(); } ITaskProperties task = treeNode.getTask(); @@ -176,6 +182,13 @@ public void doubleClick(DoubleClickEvent event) { return reviewResults; } + private TreeViewer createTreeWithColumns(Tree tree) { + TreeViewer reviewResults = new TreeViewer(tree); + return TreeHelper.createColumns(reviewResults, Column.values()); + } + + + private final class ScopeViewerFilter extends ViewerFilter { @Override public boolean select(Viewer viewer, Object parentElement, diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java index 327e148d..d8bf6cb5 100644 --- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java @@ -37,14 +37,13 @@ import org.eclipse.jface.viewers.TreeNode; import org.eclipse.jface.viewers.TreeNodeContentProvider; import org.eclipse.jface.viewers.TreeViewer; -import org.eclipse.jface.viewers.TreeViewerColumn; import org.eclipse.mylyn.reviews.tasks.core.IReviewFile; import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper; +import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem; import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; import org.eclipse.mylyn.reviews.tasks.core.Rating; import org.eclipse.mylyn.reviews.tasks.core.ReviewResult; import org.eclipse.mylyn.reviews.tasks.core.ReviewScope; -import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem; import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties; import org.eclipse.mylyn.reviews.tasks.ui.Images; import org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin; @@ -84,6 +83,73 @@ public ReviewTaskEditorPart() { setExpandVertically(true); } + private enum Column implements IColumnSpec<TreeNode> { + GROUP("Group") { + @Override + public String getText(TreeNode node) { + Object value = node.getValue(); + if (value instanceof IReviewScopeItem) { + return ((IReviewScopeItem) value).getDescription(); + } + return null; + } + }, + FILES("Filename") { + @Override + public String getText(TreeNode node) { + Object value = node.getValue(); + if (value instanceof IReviewFile) { + return ((IReviewFile) value).getFileName(); + } + return null; + } + + @Override + public Image getImage(TreeNode node) { + Object element = node.getValue(); + if (element instanceof IReviewFile) { + ISharedImages sharedImages = PlatformUI.getWorkbench() + .getSharedImages(); + IReviewFile file = ((IReviewFile) element); + if (file.isNewFile()) { + return new NewFile().createImage(); + } + if (!file.canReview()) { + return new MissingFile().createImage(); + } + + return sharedImages.getImage(ISharedImages.IMG_OBJ_FILE); + } + return null; + } + }; + + /* + * Object element = ((TreeNode) node).getValue(); if (columnIndex == + * COLUMN_FILE) { + * + * } } return null; + */ + private String title; + + private Column(String title) { + this.title = title; + } + + public String getTitle() { + return title; + } + + public String getText(TreeNode value) { + return value != null ? value.toString() : ""; + } + + public Image getImage(TreeNode value) { + return null; + } + + } + @Override public void createControl(Composite parent, FormToolkit toolkit) { section = createSection(parent, toolkit, true); @@ -93,7 +159,7 @@ public void createControl(Composite parent, FormToolkit toolkit) { gd.horizontalSpan = 4; section.setLayout(gl); section.setLayoutData(gd); -setSection(toolkit, section); + setSection(toolkit, section); composite = toolkit.createComposite(section); @@ -104,55 +170,12 @@ public void createControl(Composite parent, FormToolkit toolkit) { fileList.getControl().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); - createColumn(fileList, "Group", 100); - createColumn(fileList, "Filename", 100); + TreeHelper.createColumns(fileList, Column.values()); fileList.getTree().setLinesVisible(true); fileList.getTree().setHeaderVisible(true); - fileList.setLabelProvider(new TableLabelProvider() { - private final int COLUMN_GROUP = 0; - private final int COLUMN_FILE = 1; - - @Override - public String getColumnText(Object node, int columnIndex) { - Object element = ((TreeNode) node).getValue(); - switch (columnIndex) { - case COLUMN_GROUP: - if (element instanceof IReviewScopeItem) { - return ((IReviewScopeItem) element).getDescription(); - } - break; - case COLUMN_FILE: - if (element instanceof IReviewFile) { - return ((IReviewFile) element).getFileName(); - } - break; - } - return null; - } - - @Override - public Image getColumnImage(Object node, int columnIndex) { - Object element = ((TreeNode) node).getValue(); - if (element instanceof IReviewFile) { - if (columnIndex == COLUMN_FILE) { - ISharedImages sharedImages = PlatformUI.getWorkbench() - .getSharedImages(); - IReviewFile file = ((IReviewFile) element); - if (file.isNewFile()) { - return new NewFile().createImage(); - } - if (!file.canReview()) { - return new MissingFile().createImage(); - } - - return sharedImages - .getImage(ISharedImages.IMG_OBJ_FILE); - } - } - return null; - } - }); + fileList.setLabelProvider(new ColumnLabelProvider<TreeNode>(Column + .values())); fileList.setContentProvider(new TreeNodeContentProvider()); fileList.addDoubleClickListener(new IDoubleClickListener() { @@ -161,7 +184,8 @@ public void doubleClick(DoubleClickEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection sel = (IStructuredSelection) selection; - Object value = ((TreeNode)sel.getFirstElement()).getValue(); + Object value = ((TreeNode) sel.getFirstElement()) + .getValue(); if (value instanceof IReviewFile) { final IReviewFile file = (IReviewFile) value; if (file.canReview()) { @@ -224,7 +248,7 @@ public void run() throws Exception { return; } List<IReviewScopeItem> files = reviewScope.getItems(); - + final TreeNode[] rootNodes = new TreeNode[files.size()]; int index = 0; for (IReviewScopeItem item : files) { @@ -244,8 +268,8 @@ public void run() throws Exception { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { - fileList.setInput(rootNodes); - if(rootNodes.length==0) { + fileList.setInput(rootNodes); + if (rootNodes.length == 0) { section.setExpanded(false); } } @@ -261,15 +285,6 @@ public void handleException(Throwable exception) { }); } - private TreeViewerColumn createColumn(TreeViewer tree, String title, - int width) { - TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); - column.getColumn().setText(title); - column.getColumn().setWidth(width); - column.getColumn().setResizable(true); - return column; - } - private void createResultFields(Composite composite, FormToolkit toolkit) { Composite resultComposite = toolkit.createComposite(composite); toolkit.paintBordersFor(resultComposite); diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java new file mode 100644 index 00000000..7d5fb386 --- /dev/null +++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation + *******************************************************************************/ +package org.eclipse.mylyn.reviews.tasks.ui.editors; + +import org.eclipse.jface.viewers.TreeViewer; +import org.eclipse.jface.viewers.TreeViewerColumn; +import org.eclipse.swt.SWT; +/** + * @author mattk + * + */ +public class TreeHelper { + + public static TreeViewer createColumns(TreeViewer tree, + IColumnSpec<?>[] columns) { + for (IColumnSpec<?> column : columns) { + createColumn(tree, column); + } + return tree; + } + + public static TreeViewerColumn createColumn(TreeViewer tree, + IColumnSpec<?> columnSpec) { + TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); + column.getColumn().setText(columnSpec.getTitle()); + column.getColumn().setWidth(100); + column.getColumn().setResizable(true); + return column; + } +}
3e714ddd9f062e534c1ee028ac8b2269a062004b
intellij-community
IDEADEV-11483 IE conditional comments support- [in progress]--
a
https://github.com/JetBrains/intellij-community
diff --git a/platform-resources/src/META-INF/XmlPlugin.xml b/platform-resources/src/META-INF/XmlPlugin.xml index 100f7071318fa..2955152781070 100644 --- a/platform-resources/src/META-INF/XmlPlugin.xml +++ b/platform-resources/src/META-INF/XmlPlugin.xml @@ -254,7 +254,7 @@ <xml.xmlSuppressionProvider implementation="com.intellij.codeInspection.DefaultXmlSuppressionProvider" order="last"/> - <!--<multiHostInjector implementation="com.intellij.psi.impl.source.html.HtmlConditionalCommentInjector"/>--> + <multiHostInjector implementation="com.intellij.psi.impl.source.html.HtmlConditionalCommentInjector"/> <intentionAction> <category>XML</category> diff --git a/xml/impl/src/com/intellij/ide/highlighter/HtmlFileHighlighter.java b/xml/impl/src/com/intellij/ide/highlighter/HtmlFileHighlighter.java index b510d831222b9..330ec39728e4d 100644 --- a/xml/impl/src/com/intellij/ide/highlighter/HtmlFileHighlighter.java +++ b/xml/impl/src/com/intellij/ide/highlighter/HtmlFileHighlighter.java @@ -56,6 +56,10 @@ public class HtmlFileHighlighter extends SyntaxHighlighterBase { keys1.put(XmlTokenType.XML_COMMENT_START, XmlHighlighterColors.HTML_COMMENT); keys1.put(XmlTokenType.XML_COMMENT_END, XmlHighlighterColors.HTML_COMMENT); keys1.put(XmlTokenType.XML_COMMENT_CHARACTERS, XmlHighlighterColors.HTML_COMMENT); + keys1.put(XmlTokenType.XML_CONDITIONAL_COMMENT_END, XmlHighlighterColors.HTML_COMMENT); + keys1.put(XmlTokenType.XML_CONDITIONAL_COMMENT_END_START, XmlHighlighterColors.HTML_COMMENT); + keys1.put(XmlTokenType.XML_CONDITIONAL_COMMENT_START, XmlHighlighterColors.HTML_COMMENT); + keys1.put(XmlTokenType.XML_CONDITIONAL_COMMENT_START_END, XmlHighlighterColors.HTML_COMMENT); keys1.put(XmlTokenType.XML_START_TAG_START, XmlHighlighterColors.HTML_TAG); keys1.put(XmlTokenType.XML_END_TAG_START, XmlHighlighterColors.HTML_TAG); diff --git a/xml/impl/src/com/intellij/lang/html/HtmlParsing.java b/xml/impl/src/com/intellij/lang/html/HtmlParsing.java index 49774b0b6c746..ce9108a27525b 100644 --- a/xml/impl/src/com/intellij/lang/html/HtmlParsing.java +++ b/xml/impl/src/com/intellij/lang/html/HtmlParsing.java @@ -416,7 +416,9 @@ protected void parseComment() { advance(); while (true) { final IElementType tt = token(); - if (tt == XmlTokenType.XML_COMMENT_CHARACTERS || tt == XmlTokenType.XML_CHAR_ENTITY_REF) { + if (tt == XmlTokenType.XML_COMMENT_CHARACTERS || tt == XmlTokenType.XML_CHAR_ENTITY_REF || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_START + || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_START_END || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_END_START + || tt == XmlTokenType.XML_CONDITIONAL_COMMENT_END) { advance(); continue; } diff --git a/xml/impl/src/com/intellij/lexer/_HtmlLexer.java b/xml/impl/src/com/intellij/lexer/_HtmlLexer.java index 9e1954ed1ba7e..0911995fa5282 100644 --- a/xml/impl/src/com/intellij/lexer/_HtmlLexer.java +++ b/xml/impl/src/com/intellij/lexer/_HtmlLexer.java @@ -1,4 +1,4 @@ -/* The following code was generated by JFlex 1.4.1 on 12/18/07 7:25 PM */ +/* The following code was generated by JFlex 1.4.1 on 1/20/09 3:22 PM */ /* It's an automatically generated code. Do not modify it. */ package com.intellij.lexer; @@ -8,9 +8,9 @@ /** - * This class is a scanner generated by + * This class is a scanner generated by * <a href="http://www.jflex.de/">JFlex</a> 1.4.1 - * on 12/18/07 7:25 PM from the specification file + * on 1/20/09 3:22 PM from the specification file * <tt>/Users/spleaner/workspace/IDEA/tools/lexer/_HtmlLexer.flex</tt> */ public class _HtmlLexer implements FlexLexer { @@ -19,6 +19,7 @@ public class _HtmlLexer implements FlexLexer { /** lexical states */ public static final int PROCESSING_INSTRUCTION = 9; + public static final int C_COMMENT_END = 14; public static final int END_TAG_NAME = 4; public static final int START_TAG_NAME = 3; public static final int ATTRIBUTE_VALUE_SQ = 8; @@ -30,98 +31,100 @@ public class _HtmlLexer implements FlexLexer { public static final int TAG_ATTRIBUTES = 5; public static final int COMMENT = 2; public static final int ATTRIBUTE_VALUE_START = 6; + public static final int C_COMMENT_START = 13; public static final int END_TAG_NAME2 = 11; - /** + /** * Translates characters to character classes */ - private static final String ZZ_CMAP_PACKED = - "\11\0\2\3\1\0\2\3\22\0\1\3\1\12\1\7\1\6\1\37"+ - "\1\0\1\47\1\10\5\0\1\5\1\4\1\44\12\2\1\1\1\50"+ - "\1\11\1\46\1\42\1\43\1\0\1\57\1\34\1\16\1\13\1\24"+ - "\1\57\1\1\1\25\1\36\2\1\1\30\1\26\1\1\1\14\1\22"+ - "\3\1\1\17\1\32\3\1\1\21\1\1\1\0\1\45\2\0\1\1"+ - "\1\0\1\52\1\35\1\16\1\13\1\24\1\57\1\51\1\25\1\36"+ - "\2\1\1\31\1\27\1\55\1\15\1\23\1\54\1\1\1\53\1\20"+ - "\1\33\2\1\1\56\1\21\1\1\1\40\1\0\1\41\54\0\1\1"+ - "\12\0\1\1\4\0\1\1\5\0\27\1\1\0\37\1\1\0\u013f\1"+ - "\31\0\162\1\4\0\14\1\16\0\5\1\11\0\1\1\213\0\1\1"+ - "\13\0\1\1\1\0\3\1\1\0\1\1\1\0\24\1\1\0\54\1"+ - "\1\0\46\1\1\0\5\1\4\0\202\1\10\0\105\1\1\0\46\1"+ - "\2\0\2\1\6\0\20\1\41\0\46\1\2\0\1\1\7\0\47\1"+ - "\110\0\33\1\5\0\3\1\56\0\32\1\5\0\13\1\43\0\2\1"+ - "\1\0\143\1\1\0\1\1\17\0\2\1\7\0\2\1\12\0\3\1"+ - "\2\0\1\1\20\0\1\1\1\0\36\1\35\0\3\1\60\0\46\1"+ - "\13\0\1\1\u0152\0\66\1\3\0\1\1\22\0\1\1\7\0\12\1"+ - "\43\0\10\1\2\0\2\1\2\0\26\1\1\0\7\1\1\0\1\1"+ - "\3\0\4\1\3\0\1\1\36\0\2\1\1\0\3\1\16\0\2\1"+ - "\23\0\6\1\4\0\2\1\2\0\26\1\1\0\7\1\1\0\2\1"+ - "\1\0\2\1\1\0\2\1\37\0\4\1\1\0\1\1\23\0\3\1"+ - "\20\0\11\1\1\0\3\1\1\0\26\1\1\0\7\1\1\0\2\1"+ - "\1\0\5\1\3\0\1\1\22\0\1\1\17\0\2\1\43\0\10\1"+ - "\2\0\2\1\2\0\26\1\1\0\7\1\1\0\2\1\1\0\5\1"+ - "\3\0\1\1\36\0\2\1\1\0\3\1\17\0\1\1\21\0\1\1"+ - "\1\0\6\1\3\0\3\1\1\0\4\1\3\0\2\1\1\0\1\1"+ - "\1\0\2\1\3\0\2\1\3\0\3\1\3\0\10\1\1\0\3\1"+ - "\113\0\10\1\1\0\3\1\1\0\27\1\1\0\12\1\1\0\5\1"+ - "\46\0\2\1\43\0\10\1\1\0\3\1\1\0\27\1\1\0\12\1"+ - "\1\0\5\1\3\0\1\1\40\0\1\1\1\0\2\1\43\0\10\1"+ - "\1\0\3\1\1\0\27\1\1\0\20\1\46\0\2\1\43\0\22\1"+ - "\3\0\30\1\1\0\11\1\1\0\1\1\2\0\7\1\72\0\60\1"+ - "\1\0\2\1\14\0\7\1\72\0\2\1\1\0\1\1\2\0\2\1"+ - "\1\0\1\1\2\0\1\1\6\0\4\1\1\0\7\1\1\0\3\1"+ - "\1\0\1\1\1\0\1\1\2\0\2\1\1\0\4\1\1\0\2\1"+ - "\11\0\1\1\2\0\5\1\1\0\1\1\25\0\2\1\42\0\1\1"+ - "\77\0\10\1\1\0\42\1\35\0\4\1\164\0\42\1\1\0\5\1"+ - "\1\0\2\1\45\0\6\1\112\0\46\1\12\0\51\1\7\0\132\1"+ - "\5\0\104\1\5\0\122\1\6\0\7\1\1\0\77\1\1\0\1\1"+ - "\1\0\4\1\2\0\7\1\1\0\1\1\1\0\4\1\2\0\47\1"+ - "\1\0\1\1\1\0\4\1\2\0\37\1\1\0\1\1\1\0\4\1"+ - "\2\0\7\1\1\0\1\1\1\0\4\1\2\0\7\1\1\0\7\1"+ - "\1\0\27\1\1\0\37\1\1\0\1\1\1\0\4\1\2\0\7\1"+ - "\1\0\47\1\1\0\23\1\105\0\125\1\14\0\u026c\1\2\0\10\1"+ - "\12\0\32\1\5\0\113\1\25\0\15\1\1\0\4\1\16\0\22\1"+ - "\16\0\22\1\16\0\15\1\1\0\3\1\17\0\64\1\43\0\1\1"+ - "\4\0\1\1\103\0\130\1\10\0\51\1\127\0\35\1\63\0\36\1"+ - "\2\0\5\1\u038b\0\154\1\224\0\234\1\4\0\132\1\6\0\26\1"+ - "\2\0\6\1\2\0\46\1\2\0\6\1\2\0\10\1\1\0\1\1"+ - "\1\0\1\1\1\0\1\1\1\0\37\1\2\0\65\1\1\0\7\1"+ - "\1\0\1\1\3\0\3\1\1\0\7\1\3\0\4\1\2\0\6\1"+ - "\4\0\15\1\5\0\3\1\1\0\7\1\164\0\1\1\15\0\1\1"+ - "\202\0\1\1\4\0\1\1\2\0\12\1\1\0\1\1\3\0\5\1"+ - "\6\0\1\1\1\0\1\1\1\0\1\1\1\0\4\1\1\0\3\1"+ - "\1\0\7\1\3\0\3\1\5\0\5\1\u0ebb\0\2\1\52\0\5\1"+ - "\5\0\2\1\4\0\126\1\6\0\3\1\1\0\132\1\1\0\4\1"+ - "\5\0\50\1\4\0\136\1\21\0\30\1\70\0\20\1\u0200\0\u19b6\1"+ - "\112\0\u51a6\1\132\0\u048d\1\u0773\0\u2ba4\1\u215c\0\u012e\1\2\0\73\1"+ - "\225\0\7\1\14\0\5\1\5\0\1\1\1\0\12\1\1\0\15\1"+ - "\1\0\5\1\1\0\1\1\1\0\2\1\1\0\2\1\1\0\154\1"+ - "\41\0\u016b\1\22\0\100\1\2\0\66\1\50\0\14\1\164\0\5\1"+ - "\1\0\207\1\44\0\32\1\6\0\32\1\13\0\131\1\3\0\6\1"+ - "\2\0\6\1\2\0\6\1\2\0\3\1\43\0"; - - /** + private static final String ZZ_CMAP_PACKED = + "\11\0\2\3\1\0\2\3\22\0\1\3\1\13\1\10\1\7\1\40"+ + "\1\0\1\45\1\11\1\44\1\44\3\0\1\6\1\5\1\47\12\2"+ + "\1\4\1\54\1\12\1\53\1\43\1\46\1\0\1\63\1\35\1\17"+ + "\1\14\1\25\1\63\1\1\1\26\1\37\2\1\1\31\1\27\1\1"+ + "\1\15\1\23\3\1\1\20\1\33\3\1\1\22\1\1\1\50\1\52"+ + "\1\51\1\0\1\4\1\0\1\56\1\36\1\17\1\14\1\25\1\63"+ + "\1\55\1\26\1\37\2\1\1\32\1\30\1\61\1\16\1\24\1\60"+ + "\1\1\1\57\1\21\1\34\2\1\1\62\1\22\1\1\1\41\1\44"+ + "\1\42\54\0\1\1\12\0\1\1\4\0\1\1\5\0\27\1\1\0"+ + "\37\1\1\0\u013f\1\31\0\162\1\4\0\14\1\16\0\5\1\11\0"+ + "\1\1\213\0\1\1\13\0\1\1\1\0\3\1\1\0\1\1\1\0"+ + "\24\1\1\0\54\1\1\0\46\1\1\0\5\1\4\0\202\1\10\0"+ + "\105\1\1\0\46\1\2\0\2\1\6\0\20\1\41\0\46\1\2\0"+ + "\1\1\7\0\47\1\110\0\33\1\5\0\3\1\56\0\32\1\5\0"+ + "\13\1\43\0\2\1\1\0\143\1\1\0\1\1\17\0\2\1\7\0"+ + "\2\1\12\0\3\1\2\0\1\1\20\0\1\1\1\0\36\1\35\0"+ + "\3\1\60\0\46\1\13\0\1\1\u0152\0\66\1\3\0\1\1\22\0"+ + "\1\1\7\0\12\1\43\0\10\1\2\0\2\1\2\0\26\1\1\0"+ + "\7\1\1\0\1\1\3\0\4\1\3\0\1\1\36\0\2\1\1\0"+ + "\3\1\16\0\2\1\23\0\6\1\4\0\2\1\2\0\26\1\1\0"+ + "\7\1\1\0\2\1\1\0\2\1\1\0\2\1\37\0\4\1\1\0"+ + "\1\1\23\0\3\1\20\0\11\1\1\0\3\1\1\0\26\1\1\0"+ + "\7\1\1\0\2\1\1\0\5\1\3\0\1\1\22\0\1\1\17\0"+ + "\2\1\43\0\10\1\2\0\2\1\2\0\26\1\1\0\7\1\1\0"+ + "\2\1\1\0\5\1\3\0\1\1\36\0\2\1\1\0\3\1\17\0"+ + "\1\1\21\0\1\1\1\0\6\1\3\0\3\1\1\0\4\1\3\0"+ + "\2\1\1\0\1\1\1\0\2\1\3\0\2\1\3\0\3\1\3\0"+ + "\10\1\1\0\3\1\113\0\10\1\1\0\3\1\1\0\27\1\1\0"+ + "\12\1\1\0\5\1\46\0\2\1\43\0\10\1\1\0\3\1\1\0"+ + "\27\1\1\0\12\1\1\0\5\1\3\0\1\1\40\0\1\1\1\0"+ + "\2\1\43\0\10\1\1\0\3\1\1\0\27\1\1\0\20\1\46\0"+ + "\2\1\43\0\22\1\3\0\30\1\1\0\11\1\1\0\1\1\2\0"+ + "\7\1\72\0\60\1\1\0\2\1\14\0\7\1\72\0\2\1\1\0"+ + "\1\1\2\0\2\1\1\0\1\1\2\0\1\1\6\0\4\1\1\0"+ + "\7\1\1\0\3\1\1\0\1\1\1\0\1\1\2\0\2\1\1\0"+ + "\4\1\1\0\2\1\11\0\1\1\2\0\5\1\1\0\1\1\25\0"+ + "\2\1\42\0\1\1\77\0\10\1\1\0\42\1\35\0\4\1\164\0"+ + "\42\1\1\0\5\1\1\0\2\1\45\0\6\1\112\0\46\1\12\0"+ + "\51\1\7\0\132\1\5\0\104\1\5\0\122\1\6\0\7\1\1\0"+ + "\77\1\1\0\1\1\1\0\4\1\2\0\7\1\1\0\1\1\1\0"+ + "\4\1\2\0\47\1\1\0\1\1\1\0\4\1\2\0\37\1\1\0"+ + "\1\1\1\0\4\1\2\0\7\1\1\0\1\1\1\0\4\1\2\0"+ + "\7\1\1\0\7\1\1\0\27\1\1\0\37\1\1\0\1\1\1\0"+ + "\4\1\2\0\7\1\1\0\47\1\1\0\23\1\105\0\125\1\14\0"+ + "\u026c\1\2\0\10\1\12\0\32\1\5\0\113\1\25\0\15\1\1\0"+ + "\4\1\16\0\22\1\16\0\22\1\16\0\15\1\1\0\3\1\17\0"+ + "\64\1\43\0\1\1\4\0\1\1\103\0\130\1\10\0\51\1\127\0"+ + "\35\1\63\0\36\1\2\0\5\1\u038b\0\154\1\224\0\234\1\4\0"+ + "\132\1\6\0\26\1\2\0\6\1\2\0\46\1\2\0\6\1\2\0"+ + "\10\1\1\0\1\1\1\0\1\1\1\0\1\1\1\0\37\1\2\0"+ + "\65\1\1\0\7\1\1\0\1\1\3\0\3\1\1\0\7\1\3\0"+ + "\4\1\2\0\6\1\4\0\15\1\5\0\3\1\1\0\7\1\164\0"+ + "\1\1\15\0\1\1\202\0\1\1\4\0\1\1\2\0\12\1\1\0"+ + "\1\1\3\0\5\1\6\0\1\1\1\0\1\1\1\0\1\1\1\0"+ + "\4\1\1\0\3\1\1\0\7\1\3\0\3\1\5\0\5\1\u0ebb\0"+ + "\2\1\52\0\5\1\5\0\2\1\4\0\126\1\6\0\3\1\1\0"+ + "\132\1\1\0\4\1\5\0\50\1\4\0\136\1\21\0\30\1\70\0"+ + "\20\1\u0200\0\u19b6\1\112\0\u51a6\1\132\0\u048d\1\u0773\0\u2ba4\1\u215c\0"+ + "\u012e\1\2\0\73\1\225\0\7\1\14\0\5\1\5\0\1\1\1\0"+ + "\12\1\1\0\15\1\1\0\5\1\1\0\1\1\1\0\2\1\1\0"+ + "\2\1\1\0\154\1\41\0\u016b\1\22\0\100\1\2\0\66\1\50\0"+ + "\14\1\164\0\5\1\1\0\207\1\44\0\32\1\6\0\32\1\13\0"+ + "\131\1\3\0\6\1\2\0\6\1\2\0\6\1\2\0\3\1\43\0"; + + /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); - /** + /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = - "\1\1\5\0\1\2\2\0\1\3\3\0\1\1\1\4"+ - "\5\1\1\5\1\6\4\5\1\7\1\5\3\10\1\11"+ - "\1\12\1\13\2\11\1\14\1\15\1\11\1\16\1\2"+ - "\1\17\1\20\2\2\1\21\1\22\4\21\1\3\1\23"+ - "\1\5\1\24\3\25\1\26\1\27\1\0\1\30\1\31"+ - "\14\0\1\31\1\32\2\2\5\0\1\33\1\34\1\35"+ - "\1\36\11\0\1\37\1\0\1\40\1\2\1\40\1\41"+ - "\1\0\1\42\3\0\1\14\3\0\1\43\2\0\1\44"; + "\1\1\5\0\1\2\2\0\1\3\5\0\1\1\1\4"+ + "\5\1\1\5\1\6\4\5\1\7\1\5\4\10\1\11"+ + "\1\12\1\13\1\14\2\12\1\15\1\16\1\12\1\17"+ + "\1\2\1\20\1\21\2\2\1\22\1\23\4\22\1\3"+ + "\1\24\1\5\1\25\3\26\1\27\1\10\2\27\1\30"+ + "\1\31\1\32\1\0\1\33\1\34\15\0\1\34\1\35"+ + "\2\2\3\0\1\36\2\0\1\37\1\40\1\41\1\42"+ + "\11\0\1\43\1\44\1\0\1\45\1\2\1\45\1\46"+ + "\1\0\1\47\3\0\1\15\3\0\1\50\2\0\1\51"; private static int [] zzUnpackAction() { - int [] result = new int[116]; + int [] result = new int[128]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; @@ -140,30 +143,31 @@ private static int zzUnpackAction(String packed, int offset, int [] result) { } - /** + /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = - "\0\0\0\60\0\140\0\220\0\300\0\360\0\u0120\0\u0150"+ - "\0\u0180\0\u01b0\0\u01e0\0\u0210\0\u0240\0\u0270\0\u02a0\0\u02d0"+ - "\0\u0300\0\u0330\0\u0360\0\u0390\0\u02d0\0\u03c0\0\u03f0\0\u0420"+ - "\0\u0450\0\u0480\0\u02d0\0\u0390\0\u02d0\0\u04b0\0\u0390\0\u02d0"+ - "\0\u04e0\0\u02d0\0\u0390\0\u0510\0\u0540\0\u02d0\0\u0570\0\u02d0"+ - "\0\u05a0\0\u02d0\0\u02d0\0\u05d0\0\u0600\0\u02d0\0\u02d0\0\u0630"+ - "\0\u0660\0\u0390\0\u0690\0\u06c0\0\u02d0\0\u06f0\0\u0720\0\u02d0"+ - "\0\u0570\0\u0390\0\u0750\0\u0780\0\u07b0\0\u02d0\0\u07e0\0\u0810"+ - "\0\u0840\0\u0870\0\u08a0\0\u08d0\0\u0900\0\u0930\0\u03f0\0\u0420"+ - "\0\u0960\0\u0990\0\u09c0\0\u02d0\0\u02d0\0\u09f0\0\u0a20\0\u0a50"+ - "\0\u0a80\0\u0ab0\0\u0ae0\0\u0b10\0\u0b40\0\u0b70\0\u02d0\0\u02d0"+ - "\0\u0ba0\0\u0bd0\0\u0c00\0\u0c30\0\u0c60\0\u0c90\0\u0cc0\0\u0cf0"+ - "\0\u0d20\0\u02d0\0\u0d50\0\u05a0\0\u0d80\0\u02d0\0\u02d0\0\u0db0"+ - "\0\u02d0\0\u0de0\0\u0e10\0\u0e40\0\u02d0\0\u0e70\0\u0ea0\0\u0ed0"+ - "\0\u02d0\0\u0f00\0\u0f30\0\u02d0"; + "\0\0\0\64\0\150\0\234\0\320\0\u0104\0\u0138\0\u016c"+ + "\0\u01a0\0\u01d4\0\u0208\0\u023c\0\u0270\0\u02a4\0\u02d8\0\u030c"+ + "\0\u0340\0\u0374\0\u03a8\0\u03dc\0\u0410\0\u0444\0\u0374\0\u0478"+ + "\0\u04ac\0\u04e0\0\u0514\0\u0548\0\u0374\0\u0410\0\u0374\0\u057c"+ + "\0\u05b0\0\u0410\0\u0374\0\u0374\0\u05e4\0\u0374\0\u0410\0\u0618"+ + "\0\u064c\0\u0374\0\u0680\0\u0374\0\u06b4\0\u0374\0\u0374\0\u06e8"+ + "\0\u071c\0\u0374\0\u0374\0\u0750\0\u0410\0\u0784\0\u07b8\0\u07ec"+ + "\0\u0374\0\u0820\0\u0854\0\u0374\0\u0410\0\u0680\0\u0374\0\u0888"+ + "\0\u0410\0\u08bc\0\u0374\0\u08f0\0\u0924\0\u0958\0\u0374\0\u098c"+ + "\0\u09c0\0\u09f4\0\u0a28\0\u0a5c\0\u0a90\0\u0ac4\0\u0af8\0\u04ac"+ + "\0\u04e0\0\u0b2c\0\u0b60\0\u0b94\0\u0bc8\0\u0374\0\u0374\0\u0bfc"+ + "\0\u0c30\0\u0c64\0\u0c98\0\u0ccc\0\u0374\0\u0d00\0\u0d34\0\u0d68"+ + "\0\u0d9c\0\u0374\0\u0374\0\u0dd0\0\u0e04\0\u0e38\0\u0e6c\0\u0ea0"+ + "\0\u0ed4\0\u0f08\0\u0f3c\0\u0f70\0\u0374\0\u0374\0\u0fa4\0\u06b4"+ + "\0\u0fd8\0\u0374\0\u0374\0\u100c\0\u0374\0\u1040\0\u1074\0\u10a8"+ + "\0\u0374\0\u10dc\0\u1110\0\u1144\0\u0374\0\u1178\0\u11ac\0\u0374"; private static int [] zzUnpackRowMap() { - int [] result = new int[116]; + int [] result = new int[128]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; @@ -180,83 +184,89 @@ private static int zzUnpackRowMap(String packed, int offset, int [] result) { return j; } - /** + /** * The transition table of the DFA */ private static final int [] ZZ_TRANS = zzUnpackTrans(); private static final String ZZ_TRANS_PACKED_0 = - "\3\16\1\17\2\16\1\20\2\16\1\21\25\16\1\22"+ - "\5\16\1\23\1\16\1\24\10\16\3\25\1\26\3\25"+ - "\1\27\1\30\11\25\2\31\1\25\1\32\14\25\1\33"+ - "\4\25\1\34\10\25\5\35\1\36\41\35\1\37\10\35"+ - "\1\40\1\41\1\40\1\26\5\40\1\42\1\40\24\41"+ - "\10\40\1\43\1\40\7\41\1\40\1\41\1\40\1\26"+ - "\5\40\1\44\1\40\24\41\10\40\1\43\1\40\7\41"+ - "\1\40\1\45\1\40\1\26\7\40\24\45\3\40\1\46"+ - "\1\40\1\47\1\40\1\50\1\43\1\40\7\45\3\51"+ - "\1\26\3\51\1\52\1\53\26\51\1\54\2\51\1\46"+ - "\1\51\1\55\13\51\7\56\1\57\27\56\1\60\5\56"+ - "\1\61\1\56\1\62\20\56\1\57\26\56\1\63\5\56"+ - "\1\61\1\56\1\62\10\56\42\64\1\65\1\66\14\64"+ - "\6\25\1\67\2\25\1\42\35\25\1\34\10\25\3\40"+ - "\1\26\2\40\1\45\2\40\1\44\30\40\1\46\4\40"+ - "\1\43\10\40\3\70\1\26\5\70\1\42\30\70\1\46"+ - "\1\70\1\71\2\70\1\72\10\70\3\16\1\0\2\16"+ - "\1\0\2\16\1\0\25\16\1\0\5\16\1\23\1\16"+ - "\1\0\10\16\3\0\1\17\135\0\1\73\4\0\1\74"+ - "\3\0\1\75\24\73\4\0\1\76\1\77\4\0\7\73"+ - "\40\0\1\100\17\0\3\16\1\0\5\16\1\0\33\16"+ - "\1\23\1\16\1\0\10\16\1\0\1\101\4\0\1\102"+ - "\4\0\16\101\1\103\5\101\12\0\1\103\1\104\1\101"+ - "\1\105\1\106\2\101\3\0\1\26\54\0\7\107\1\56"+ - "\50\107\10\110\1\56\47\110\32\0\2\111\43\0\2\112"+ - "\44\0\1\113\53\0\2\41\1\0\2\41\5\0\24\41"+ - "\12\0\7\41\44\0\1\114\14\0\2\45\1\0\2\45"+ - "\5\0\24\45\12\0\7\45\42\0\1\115\15\0\3\51"+ - "\1\0\3\51\2\0\31\51\1\0\1\51\1\116\16\51"+ - "\1\0\3\51\2\0\27\51\1\117\1\51\1\0\1\51"+ - "\1\116\55\51\1\115\1\51\1\116\13\51\40\0\1\120"+ - "\56\0\1\56\60\0\1\121\17\0\42\64\1\0\1\122"+ - "\56\64\1\65\15\64\1\0\2\67\1\0\2\67\5\0"+ - "\24\67\12\0\7\67\1\0\2\73\1\0\2\73\5\0"+ - "\24\73\12\0\7\73\1\0\2\74\1\0\2\74\5\0"+ - "\24\74\12\0\7\74\5\0\1\123\5\0\1\124\45\0"+ - "\1\125\4\0\1\126\4\0\24\125\12\0\7\125\41\100"+ - "\1\127\16\100\1\0\2\101\1\0\2\101\5\0\24\101"+ - "\11\0\1\130\7\101\2\0\1\131\53\0\1\132\2\0"+ - "\2\101\1\0\2\101\5\0\5\101\1\133\16\101\11\0"+ - "\1\130\7\101\1\0\2\101\1\0\2\101\5\0\10\101"+ - "\1\134\3\101\1\135\7\101\11\0\1\130\7\101\1\0"+ - "\2\101\1\0\2\101\5\0\20\101\1\136\3\101\11\0"+ - "\1\130\7\101\1\0\2\101\1\0\2\101\5\0\22\101"+ - "\1\137\1\101\11\0\1\130\7\101\34\0\2\140\50\0"+ - "\2\141\33\0\1\113\36\0\1\142\15\0\42\51\1\0"+ - "\1\51\1\116\13\51\3\117\1\143\3\117\2\143\30\117"+ - "\1\144\1\143\1\117\1\145\13\117\7\120\1\0\31\120"+ - "\1\146\16\120\10\121\1\0\30\121\1\146\16\121\42\64"+ - "\1\0\15\64\5\0\1\147\66\0\2\150\43\0\2\125"+ - "\1\0\2\125\5\0\24\125\12\0\7\125\1\0\2\126"+ - "\1\0\2\126\5\0\24\126\12\0\7\126\2\0\1\131"+ - "\45\0\1\151\11\0\1\152\10\0\1\152\2\0\1\152"+ - "\5\0\1\152\7\0\2\152\14\0\1\152\4\0\1\152"+ - "\1\0\2\101\1\0\2\101\5\0\24\101\11\0\1\151"+ - "\7\101\1\0\2\101\1\0\2\101\5\0\2\101\1\153"+ - "\21\101\11\0\1\130\7\101\1\0\2\101\1\0\2\101"+ - "\5\0\10\101\1\133\13\101\11\0\1\130\7\101\1\0"+ - "\2\101\1\0\2\101\5\0\2\101\1\103\21\101\11\0"+ - "\1\130\7\101\1\0\2\101\1\0\2\101\5\0\24\101"+ - "\11\0\1\130\2\101\1\135\4\101\30\0\2\154\56\0"+ - "\2\155\26\0\41\143\1\146\16\143\41\117\1\144\1\143"+ - "\1\117\1\145\13\117\16\0\1\156\43\0\1\152\10\0"+ - "\1\152\2\0\1\152\5\0\1\152\7\0\2\152\12\0"+ - "\1\151\1\0\1\152\4\0\1\152\1\0\2\101\1\0"+ - "\2\101\5\0\24\101\11\0\1\130\2\101\1\133\4\101"+ - "\36\0\1\157\40\0\2\160\55\0\1\161\62\0\1\162"+ - "\60\0\2\163\60\0\1\164\33\0"; + "\3\20\1\21\3\20\1\22\2\20\1\23\25\20\1\24"+ + "\4\20\1\25\4\20\1\26\11\20\3\27\1\30\4\27"+ + "\1\31\1\32\11\27\2\33\1\27\1\34\14\27\1\35"+ + "\1\27\1\36\16\27\6\37\1\40\3\37\1\41\32\37"+ + "\1\42\2\37\1\43\13\37\1\44\1\45\1\44\1\30"+ + "\1\45\5\44\1\46\1\44\24\45\5\44\1\47\7\44"+ + "\7\45\1\44\1\45\1\44\1\30\1\45\5\44\1\50"+ + "\1\44\24\45\5\44\1\47\7\44\7\45\1\44\1\51"+ + "\1\44\1\30\1\51\7\44\24\51\3\44\1\52\1\44"+ + "\1\47\1\44\1\53\3\44\1\54\1\44\7\51\3\55"+ + "\1\30\4\55\1\56\1\57\26\55\1\60\2\55\1\52"+ + "\3\55\1\61\14\55\10\62\1\63\27\62\1\64\4\62"+ + "\1\65\4\62\1\66\22\62\1\63\26\62\1\67\4\62"+ + "\1\65\4\62\1\66\11\62\43\70\1\71\2\70\1\72"+ + "\15\70\7\27\1\73\2\27\1\46\32\27\1\36\16\27"+ + "\3\44\1\30\3\44\1\51\2\44\1\50\30\44\1\52"+ + "\1\44\1\47\16\44\3\74\1\30\6\74\1\46\30\74"+ + "\1\52\1\74\1\75\1\74\1\76\14\74\1\77\1\100"+ + "\12\77\24\100\5\77\1\101\3\77\1\102\3\77\7\100"+ + "\1\77\1\100\12\77\24\100\5\77\1\101\3\77\1\103"+ + "\3\77\7\100\3\20\1\0\3\20\1\0\2\20\1\0"+ + "\25\20\1\0\4\20\1\0\4\20\1\26\11\20\3\0"+ + "\1\21\145\0\1\104\2\0\1\104\2\0\1\105\3\0"+ + "\1\106\24\104\6\0\1\107\1\110\5\0\7\104\41\0"+ + "\1\111\23\0\1\112\2\0\1\112\2\0\1\113\4\0"+ + "\16\112\1\114\5\112\15\0\1\114\1\115\1\112\1\116"+ + "\1\117\2\112\3\20\1\0\6\20\1\0\32\20\1\0"+ + "\4\20\1\26\11\20\3\0\1\30\60\0\10\120\1\62"+ + "\53\120\11\121\1\62\52\121\33\0\2\122\47\0\2\123"+ + "\50\0\1\124\70\0\1\125\51\0\2\45\1\0\3\45"+ + "\5\0\24\45\15\0\7\45\47\0\1\126\15\0\2\51"+ + "\1\0\3\51\5\0\24\51\15\0\7\51\43\0\1\127"+ + "\20\0\3\55\1\0\4\55\2\0\31\55\1\0\3\55"+ + "\1\130\17\55\1\0\4\55\2\0\27\55\1\131\1\55"+ + "\1\0\3\55\1\130\57\55\1\127\3\55\1\130\14\55"+ + "\41\0\1\132\62\0\1\62\64\0\1\133\22\0\43\70"+ + "\1\0\2\70\1\134\60\70\1\71\20\70\1\0\2\73"+ + "\1\0\3\73\5\0\24\73\15\0\7\73\1\0\3\100"+ + "\1\0\1\100\5\0\25\100\4\0\2\100\7\0\7\100"+ + "\43\0\1\135\21\0\2\104\1\0\3\104\5\0\24\104"+ + "\15\0\7\104\1\0\2\105\1\0\3\105\5\0\24\105"+ + "\15\0\7\105\6\0\1\136\5\0\1\137\50\0\1\140"+ + "\2\0\1\140\2\0\1\141\4\0\24\140\15\0\7\140"+ + "\42\111\1\142\21\111\1\0\2\112\1\0\3\112\5\0"+ + "\24\112\14\0\1\143\7\112\2\0\1\144\57\0\1\145"+ + "\2\0\2\112\1\0\3\112\5\0\5\112\1\146\16\112"+ + "\14\0\1\143\7\112\1\0\2\112\1\0\3\112\5\0"+ + "\10\112\1\147\3\112\1\150\7\112\14\0\1\143\7\112"+ + "\1\0\2\112\1\0\3\112\5\0\20\112\1\151\3\112"+ + "\14\0\1\143\7\112\1\0\2\112\1\0\3\112\5\0"+ + "\22\112\1\152\1\112\14\0\1\143\7\112\35\0\2\153"+ + "\54\0\2\154\36\0\1\124\37\0\1\155\70\0\1\156"+ + "\13\0\43\55\1\0\3\55\1\130\14\55\3\131\1\157"+ + "\4\131\2\157\30\131\1\160\1\157\3\131\1\161\14\131"+ + "\10\132\1\0\31\132\1\162\21\132\11\133\1\0\30\133"+ + "\1\162\21\133\43\70\1\0\20\70\6\0\1\163\72\0"+ + "\2\164\46\0\2\140\1\0\3\140\5\0\24\140\15\0"+ + "\7\140\1\0\2\141\1\0\3\141\5\0\24\141\15\0"+ + "\7\141\2\0\1\144\51\0\1\165\11\0\1\166\11\0"+ + "\1\166\2\0\1\166\5\0\1\166\7\0\2\166\17\0"+ + "\1\166\4\0\1\166\1\0\2\112\1\0\3\112\5\0"+ + "\24\112\14\0\1\165\7\112\1\0\2\112\1\0\3\112"+ + "\5\0\2\112\1\167\21\112\14\0\1\143\7\112\1\0"+ + "\2\112\1\0\3\112\5\0\10\112\1\146\13\112\14\0"+ + "\1\143\7\112\1\0\2\112\1\0\3\112\5\0\2\112"+ + "\1\114\21\112\14\0\1\143\7\112\1\0\2\112\1\0"+ + "\3\112\5\0\24\112\14\0\1\143\2\112\1\150\4\112"+ + "\31\0\2\170\62\0\2\171\31\0\42\157\1\162\21\157"+ + "\42\131\1\160\1\157\3\131\1\161\14\131\17\0\1\172"+ + "\46\0\1\166\11\0\1\166\2\0\1\166\5\0\1\166"+ + "\7\0\2\166\15\0\1\165\1\0\1\166\4\0\1\166"+ + "\1\0\2\112\1\0\3\112\5\0\24\112\14\0\1\143"+ + "\2\112\1\146\4\112\37\0\1\173\44\0\2\174\61\0"+ + "\1\175\66\0\1\176\64\0\2\177\64\0\1\200\36\0"; private static int [] zzUnpackTrans() { - int [] result = new int[3936]; + int [] result = new int[4576]; int offset = 0; offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); return result; @@ -297,16 +307,17 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = - "\1\1\5\0\1\1\2\0\1\1\3\0\2\1\1\11"+ - "\4\1\1\11\5\1\1\11\1\1\1\11\2\1\1\11"+ + "\1\1\5\0\1\1\2\0\1\1\5\0\2\1\1\11"+ + "\4\1\1\11\5\1\1\11\1\1\1\11\3\1\2\11"+ "\1\1\1\11\3\1\1\11\1\1\1\11\1\1\2\11"+ - "\2\1\2\11\5\1\1\11\2\1\1\11\4\1\1\0"+ - "\1\11\1\1\14\0\2\11\2\1\5\0\2\1\2\11"+ - "\11\0\1\11\1\0\2\1\2\11\1\0\1\11\3\0"+ - "\1\11\3\0\1\11\2\0\1\11"; + "\2\1\2\11\5\1\1\11\2\1\1\11\2\1\1\11"+ + "\3\1\1\11\2\1\1\0\1\11\1\1\15\0\2\11"+ + "\2\1\3\0\1\11\2\0\2\1\2\11\11\0\2\11"+ + "\1\0\2\1\2\11\1\0\1\11\3\0\1\11\3\0"+ + "\1\11\2\0\1\11"; private static int [] zzUnpackAttribute() { - int [] result = new int[116]; + int [] result = new int[128]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; @@ -387,7 +398,7 @@ public _HtmlLexer(java.io.InputStream in) { this(new java.io.InputStreamReader(in)); } - /** + /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table @@ -397,7 +408,7 @@ public _HtmlLexer(java.io.InputStream in) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ - while (i < 1254) { + while (i < 1260) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); @@ -427,7 +438,7 @@ public void reset(CharSequence buffer, int start, int end,int initialState){ // For Demetra compatibility public void reset(CharSequence buffer, int initialState){ zzBuffer = buffer; - zzBufferArray = null; + zzBufferArray = null; zzCurrentPos = zzMarkedPos = zzStartRead = 0; zzPushbackPos = 0; zzAtEOF = false; @@ -548,7 +559,7 @@ public void yypushback(int number) { private void zzDoEOF() { if (!zzEOFDone) { zzEOFDone = true; - + } } @@ -631,150 +642,170 @@ else if (zzAtEOF) { zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { - case 17: + case 18: { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; } - case 37: break; - case 22: + case 42: break; + case 25: { yybegin(START_TAG_NAME); yypushback(yylength()); } - case 38: break; - case 21: + case 43: break; + case 22: { return XmlTokenType.XML_TAG_CHARACTERS; } - case 39: break; - case 14: + case 44: break; + case 15: { yybegin(ATTRIBUTE_VALUE_START); return XmlTokenType.XML_EQ; } - case 40: break; - case 29: + case 45: break; + case 33: { return elTokenType; } - case 41: break; - case 12: + case 46: break; + case 13: { return XmlTokenType.XML_NAME; } - case 42: break; - case 18: + case 47: break; + case 19: { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER; } - case 43: break; - case 9: + case 48: break; + case 10: { yybegin(YYINITIAL); yypushback(1); break; } - case 44: break; - case 35: + case 49: break; + case 40: { return XmlTokenType.XML_DOCTYPE_PUBLIC; } - case 45: break; - case 33: + case 50: break; + case 38: { yybegin(COMMENT); return XmlTokenType.XML_COMMENT_START; } - case 46: break; - case 4: + case 51: break; + case 4: { return XmlTokenType.XML_REAL_WHITE_SPACE; } - case 47: break; - case 27: + case 52: break; + case 31: { yybegin(END_TAG_NAME); yypushback(yylength()); } - case 48: break; - case 1: + case 53: break; + case 1: { return XmlTokenType.XML_DATA_CHARACTERS; } - case 49: break; - case 28: + case 54: break; + case 24: + { yybegin(COMMENT); return XmlTokenType.XML_CONDITIONAL_COMMENT_END; + } + case 55: break; + case 32: { yybegin(END_TAG_NAME2); yypushback(yylength()); } - case 50: break; - case 5: + case 56: break; + case 5: { return XmlTokenType.XML_BAD_CHARACTER; } - case 51: break; - case 13: + case 57: break; + case 14: { yybegin(YYINITIAL); return XmlTokenType.XML_TAG_END; } - case 52: break; - case 25: + case 58: break; + case 30: + { yybegin(COMMENT); return XmlTokenType.XML_CONDITIONAL_COMMENT_START_END; + } + case 59: break; + case 28: { return XmlTokenType.XML_END_TAG_START; } - case 53: break; - case 31: + case 60: break; + case 35: { yybegin(YYINITIAL); return XmlTokenType.XML_COMMENT_END; } - case 54: break; - case 36: + case 61: break; + case 41: { yybegin(DOC_TYPE); return XmlTokenType.XML_DOCTYPE_START; } - case 55: break; - case 3: + case 62: break; + case 3: { return XmlTokenType.XML_PI_TARGET; } - case 56: break; - case 26: + case 63: break; + case 29: { yybegin(YYINITIAL); return XmlTokenType.XML_EMPTY_ELEMENT_END; } - case 57: break; - case 24: + case 64: break; + case 36: + { yybegin(C_COMMENT_END); return XmlTokenType.XML_CONDITIONAL_COMMENT_END_START; + } + case 65: break; + case 27: { yybegin(PROCESSING_INSTRUCTION); return XmlTokenType.XML_PI_START; } - case 58: break; - case 20: + case 66: break; + case 9: + { yybegin(C_COMMENT_START); return XmlTokenType.XML_CONDITIONAL_COMMENT_START; + } + case 67: break; + case 21: { yybegin(TAG_CHARACTERS); return XmlTokenType.XML_NAME; } - case 59: break; - case 7: + case 68: break; + case 7: { yybegin(YYINITIAL); return XmlTokenType.XML_DOCTYPE_END; } - case 60: break; - case 34: + case 69: break; + case 39: { return XmlTokenType.XML_CHAR_ENTITY_REF; } - case 61: break; - case 11: + case 70: break; + case 12: { return XmlTokenType.XML_START_TAG_START; } - case 62: break; - case 6: + case 71: break; + case 6: { return XmlTokenType.XML_WHITE_SPACE; } - case 63: break; - case 30: + case 72: break; + case 34: { return XmlTokenType.XML_ENTITY_REF_TOKEN; } - case 64: break; - case 32: + case 73: break; + case 23: + { yybegin(COMMENT); return XmlTokenType.XML_COMMENT_CHARACTERS; + } + case 74: break; + case 37: { return elTokenType2; } - case 65: break; - case 19: + case 75: break; + case 20: { yybegin(YYINITIAL); return XmlTokenType.XML_PI_END; } - case 66: break; - case 15: + case 76: break; + case 16: { yybegin(ATTRIBUTE_VALUE_DQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER; } - case 67: break; - case 16: + case 77: break; + case 17: { yybegin(ATTRIBUTE_VALUE_SQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER; } - case 68: break; - case 10: + case 78: break; + case 11: { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_NAME; } - case 69: break; - case 23: + case 79: break; + case 26: { yybegin(START_TAG_NAME2); yypushback(yylength()); } - case 70: break; - case 2: + case 80: break; + case 2: { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; } - case 71: break; - case 8: + case 81: break; + case 8: { return XmlTokenType.XML_COMMENT_CHARACTERS; } - case 72: break; + case 82: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; diff --git a/xml/impl/src/com/intellij/psi/impl/source/html/HtmlConditionalCommentInjector.java b/xml/impl/src/com/intellij/psi/impl/source/html/HtmlConditionalCommentInjector.java new file mode 100644 index 0000000000000..5708b1853aa7e --- /dev/null +++ b/xml/impl/src/com/intellij/psi/impl/source/html/HtmlConditionalCommentInjector.java @@ -0,0 +1,55 @@ +package com.intellij.psi.impl.source.html; + +import com.intellij.lang.ASTNode; +import com.intellij.lang.html.HTMLLanguage; +import com.intellij.lang.injection.MultiHostInjector; +import com.intellij.lang.injection.MultiHostRegistrar; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiComment; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiLanguageInjectionHost; +import com.intellij.psi.tree.TokenSet; +import com.intellij.psi.xml.XmlComment; +import com.intellij.psi.xml.XmlTokenType; +import org.jetbrains.annotations.NotNull; + +import java.util.Arrays; +import java.util.List; + +/** + * @author spleaner + */ +public class HtmlConditionalCommentInjector implements MultiHostInjector { + public void getLanguagesToInject(@NotNull final MultiHostRegistrar registrar, @NotNull final PsiElement host) { + if (host instanceof XmlComment) { + final ASTNode comment = host.getNode(); + if (comment != null) { + final ASTNode[] conditionalStarts = comment.getChildren(TokenSet.create(XmlTokenType.XML_CONDITIONAL_COMMENT_START_END)); + if (conditionalStarts.length > 0) { + final ASTNode[] conditionalEnds = comment.getChildren(TokenSet.create(XmlTokenType.XML_CONDITIONAL_COMMENT_END_START)); + if (conditionalEnds.length > 0) { + final ASTNode[] endOfEnd = comment.getChildren(TokenSet.create(XmlTokenType.XML_CONDITIONAL_COMMENT_END)); + if (endOfEnd.length > 0) { + final TextRange textRange = host.getTextRange(); + final int startOffset = textRange.getStartOffset(); + + final ASTNode start = conditionalStarts[0]; + final ASTNode end = conditionalEnds[0]; + registrar.startInjecting(HTMLLanguage.INSTANCE).addPlace(null, null, (PsiLanguageInjectionHost)host, + new TextRange(start.getTextRange().getEndOffset() - startOffset, + end.getStartOffset() - startOffset)).doneInjecting(); + } + } + } + } + } + + + } + + + @NotNull + public List<? extends Class<? extends PsiElement>> elementsToInjectIn() { + return Arrays.asList(PsiComment.class); + } +} diff --git a/xml/impl/src/com/intellij/psi/impl/source/tree/injected/XmlCommentLiteralEscaper.java b/xml/impl/src/com/intellij/psi/impl/source/tree/injected/XmlCommentLiteralEscaper.java new file mode 100644 index 0000000000000..029c05fbef686 --- /dev/null +++ b/xml/impl/src/com/intellij/psi/impl/source/tree/injected/XmlCommentLiteralEscaper.java @@ -0,0 +1,40 @@ +package com.intellij.psi.impl.source.tree.injected; + +import com.intellij.psi.LiteralTextEscaper; +import com.intellij.psi.impl.source.xml.XmlCommentImpl; +import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.util.ProperTextRange; +import com.intellij.lang.Commenter; +import com.intellij.lang.LanguageCommenters; +import com.intellij.lang.CodeDocumentationAwareCommenter; +import org.jetbrains.annotations.NotNull; + +/** + * @author spleaner + */ +public class XmlCommentLiteralEscaper extends LiteralTextEscaper<XmlCommentImpl> { + public XmlCommentLiteralEscaper(@NotNull XmlCommentImpl host) { + super(host); + } + + public boolean decode(@NotNull final TextRange rangeInsideHost, @NotNull final StringBuilder outChars) { + ProperTextRange.assertProperRange(rangeInsideHost); + outChars.append(myHost.getText(), rangeInsideHost.getStartOffset(), rangeInsideHost.getEndOffset()); + return true; + } + + public int getOffsetInHost(final int offsetInDecoded, @NotNull final TextRange rangeInsideHost) { + int offset = offsetInDecoded + rangeInsideHost.getStartOffset(); + if (offset < rangeInsideHost.getStartOffset()) offset = rangeInsideHost.getStartOffset(); + if (offset > rangeInsideHost.getEndOffset()) offset = rangeInsideHost.getEndOffset(); + return offset; + } + + public boolean isOneLine() { + final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(myHost.getLanguage()); + if (commenter instanceof CodeDocumentationAwareCommenter) { + return myHost.getTokenType() == ((CodeDocumentationAwareCommenter) commenter).getLineCommentTokenType(); + } + return false; + } +} diff --git a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlCommentImpl.java b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlCommentImpl.java index 87e51cc525d30..7b6ed010ae5a6 100644 --- a/xml/impl/src/com/intellij/psi/impl/source/xml/XmlCommentImpl.java +++ b/xml/impl/src/com/intellij/psi/impl/source/xml/XmlCommentImpl.java @@ -1,24 +1,26 @@ package com.intellij.psi.impl.source.xml; -import com.intellij.psi.PsiElementVisitor; -import com.intellij.psi.PsiReference; -import com.intellij.psi.XmlElementVisitor; +import com.intellij.openapi.util.Pair; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.*; +import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.impl.meta.MetaRegistry; import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry; +import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; +import com.intellij.psi.impl.source.tree.injected.XmlCommentLiteralEscaper; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.meta.PsiMetaOwner; import com.intellij.psi.tree.IElementType; -import com.intellij.psi.xml.XmlComment; -import com.intellij.psi.xml.XmlElementType; -import com.intellij.psi.xml.XmlTag; -import com.intellij.psi.xml.XmlTagChild; +import com.intellij.psi.xml.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.List; + /** * @author Mike */ -public class XmlCommentImpl extends XmlElementImpl implements XmlComment, XmlElementType, PsiMetaOwner { +public class XmlCommentImpl extends XmlElementImpl implements XmlComment, XmlElementType, PsiMetaOwner, PsiLanguageInjectionHost { public XmlCommentImpl() { super(XML_COMMENT); } @@ -60,4 +62,32 @@ public PsiReference[] getReferences() { public PsiMetaData getMetaData() { return MetaRegistry.getMetaBase(this); } + + public List<Pair<PsiElement, TextRange>> getInjectedPsi() { + return InjectedLanguageUtil.getInjectedPsiFiles(this); + } + + public void processInjectedPsi(@NotNull final InjectedPsiVisitor visitor) { + InjectedLanguageUtil.enumerate(this, visitor); + } + + public PsiLanguageInjectionHost updateText(@NotNull final String text) { + final PsiFile psiFile = getContainingFile(); + + final XmlDocument document = + ((XmlFile)PsiFileFactory.getInstance(getProject()).createFileFromText("dummy", psiFile.getFileType(), text)).getDocument(); + assert document != null; + + final XmlComment comment = PsiTreeUtil.getChildOfType(document, XmlComment.class); + + assert comment != null; + replaceAllChildrenToChildrenOf(comment.getNode()); + + return this; + } + + @NotNull + public LiteralTextEscaper<? extends PsiLanguageInjectionHost> createLiteralTextEscaper() { + return new XmlCommentLiteralEscaper(this); + } } diff --git a/xml/openapi/src/com/intellij/psi/xml/XmlTokenType.java b/xml/openapi/src/com/intellij/psi/xml/XmlTokenType.java index 721c8d5bc8cc3..9a43f4058f0fc 100644 --- a/xml/openapi/src/com/intellij/psi/xml/XmlTokenType.java +++ b/xml/openapi/src/com/intellij/psi/xml/XmlTokenType.java @@ -92,6 +92,11 @@ public interface XmlTokenType { IElementType XML_BAD_CHARACTER = new IXmlLeafElementType("XML_BAD_CHARACTER"); + IElementType XML_CONDITIONAL_COMMENT_START = new IXmlLeafElementType("CONDITIONAL_COMMENT_START"); + IElementType XML_CONDITIONAL_COMMENT_START_END = new IXmlLeafElementType("CONDITIONAL_COMMENT_START_END"); + IElementType XML_CONDITIONAL_COMMENT_END_START = new IXmlLeafElementType("CONDITIONAL_COMMENT_END_START"); + IElementType XML_CONDITIONAL_COMMENT_END = new IXmlLeafElementType("CONDITIONAL_COMMENT_END"); + TokenSet COMMENTS = TokenSet.create(XML_COMMENT_START, XML_COMMENT_CHARACTERS, XML_COMMENT_END); TokenSet WHITESPACES = TokenSet.create(XML_WHITE_SPACE); }
28f708d59aacda81110f9ed46bba531a5ec884a5
apache$maven-surefire
Applied patch for http://jira.codehaus.org/browse/SUREFIRE-2 with modifications. Added 2 testcases to demonstrate increased flexibility. git-svn-id: https://svn.apache.org/repos/asf/maven/surefire/trunk/surefire@331345 13f79535-47bb-0310-9956-ffa450edef68
p
https://github.com/apache/maven-surefire
diff --git a/surefire/src/main/org/codehaus/surefire/Surefire.java b/surefire/src/main/org/codehaus/surefire/Surefire.java index 46b77aa52e..c42d446d34 100644 --- a/surefire/src/main/org/codehaus/surefire/Surefire.java +++ b/surefire/src/main/org/codehaus/surefire/Surefire.java @@ -2,6 +2,7 @@ import org.codehaus.surefire.battery.Battery; import org.codehaus.surefire.battery.JUnitBattery; +import org.codehaus.surefire.battery.assertion.BatteryTestFailedException; import org.codehaus.surefire.report.ReportEntry; import org.codehaus.surefire.report.Reporter; import org.codehaus.surefire.report.ReporterManager; @@ -78,11 +79,26 @@ public boolean run() { Battery battery = (Battery) i.next(); - if ( battery.getTestCount() > 0 ) + int testCount = 0; + try + { + testCount = battery.getTestCount(); + } + catch ( BatteryTestFailedException e ) + { + e.printStackTrace(); + ReportEntry report = new ReportEntry( e, + "org.codehaus.surefire.Runner", + Surefire.getResources().getString( "bigProblems" ), e ); + + reporterManager.batteryAborted( report ); + } + + if ( testCount > 0 ) { executeBattery( battery, reporterManager ); - nbTests += battery.getTestCount(); + nbTests += testCount; } List list = new ArrayList(); @@ -100,11 +116,26 @@ public boolean run() { Battery b = (Battery) j.next(); - if ( b.getTestCount() > 0 ) + testCount = 0; + try + { + testCount = b.getTestCount(); + } + catch ( BatteryTestFailedException e ) + { + e.printStackTrace(); + ReportEntry report = new ReportEntry( e, + "org.codehaus.surefire.Runner", + Surefire.getResources().getString( "bigProblems" ), e ); + + reporterManager.batteryAborted( report ); + } + + if ( testCount > 0 ) { executeBattery( b, reporterManager ); - nbTests += b.getTestCount(); + nbTests += testCount; } } } @@ -163,6 +194,8 @@ public void executeBattery( Battery battery, ReporterManager reportManager ) } catch ( RuntimeException e ) { + e.printStackTrace(); + rawString = Surefire.getResources().getString( "executeException" ); report = new ReportEntry( this, battery.getBatteryName(), rawString, e ); diff --git a/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java b/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java index fcf7463632..38dd932ab8 100644 --- a/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java +++ b/surefire/src/main/org/codehaus/surefire/battery/JUnitBattery.java @@ -157,11 +157,33 @@ public JUnitBattery( final Class testClass, ClassLoader loader ) addListenerMethod = testResultClass.getMethod( ADD_LISTENER_METHOD, addListenerParamTypes ); - countTestCasesMethod = testInterface.getMethod( COUNT_TEST_CASES_METHOD, new Class[0] ); + if ( testInterface.isAssignableFrom( testClass ) )//testObject.getClass() ) ) + { + countTestCasesMethod = testInterface.getMethod( COUNT_TEST_CASES_METHOD, new Class[0] ); - Class[] runParamTypes = {testResultClass}; + runMethod = testInterface.getMethod( RUN_METHOD, new Class[] { testResultClass } ); - runMethod = testInterface.getMethod( RUN_METHOD, runParamTypes ); + } + else + { + try + { + countTestCasesMethod = testClass.getMethod( COUNT_TEST_CASES_METHOD, new Class[0] ); + } + catch (Exception e) + { + countTestCasesMethod = null; // for clarity + } + + try + { + runMethod = testClass.getMethod( RUN_METHOD, new Class[] { testResultClass } ); + } + catch (Exception e) + { + runMethod = null; // for clarity + } + } } protected Class getTestClass() @@ -169,7 +191,25 @@ protected Class getTestClass() return testClass; } - public void execute( ReporterManager reportManager ) + protected Object getTestClassInstance() + { + return testObject; + } + + public void execute( ReporterManager reportManager ) + throws Exception + { + if ( runMethod != null ) + { + executeJUnit( reportManager ); + } + else + { + super.execute( reportManager ); + } + } + + protected void executeJUnit( ReporterManager reportManager ) { try { @@ -191,19 +231,19 @@ public void execute( ReporterManager reportManager ) } catch ( IllegalArgumentException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } catch ( InstantiationException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } catch ( IllegalAccessException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } catch ( InvocationTargetException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } } @@ -211,21 +251,28 @@ public int getTestCount() { try { - Integer integer = (Integer) countTestCasesMethod.invoke( testObject, new Class[0] ); + if ( countTestCasesMethod != null) + { + Integer integer = (Integer) countTestCasesMethod.invoke( testObject, new Class[0] ); - return integer.intValue(); + return integer.intValue(); + } + else + { + return super.getTestCount(); + } } catch ( IllegalAccessException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } catch ( IllegalArgumentException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } catch ( InvocationTargetException e ) { - throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( e ); + throw new org.codehaus.surefire.battery.assertion.BatteryTestFailedException( testObject.getClass().getName(), e ); } } diff --git a/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java b/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java index 3d5fcfee45..3637060632 100644 --- a/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java +++ b/surefire/src/main/org/codehaus/surefire/report/ConsoleReporter.java @@ -42,7 +42,7 @@ public void runStarting( int testCount ) public void runAborted( ReportEntry report ) { - writer.println( "ABORTED" ); + writer.println( "RUN ABORTED" ); writer.println( report.getSource().getClass().getName() ); writer.println( report.getName() ); writer.println( report.getMessage() ); @@ -51,7 +51,7 @@ public void runAborted( ReportEntry report ) } public void batteryAborted( ReportEntry report ) { - writer.println( "ABORTED" ); + writer.println( "BATTERY ABORTED" ); writer.println( report.getSource().getClass().getName() ); writer.println( report.getName() ); writer.println( report.getMessage() ); diff --git a/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java b/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java index 294c427647..ea2041668a 100644 --- a/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java +++ b/surefire/src/main/org/codehaus/surefire/report/ReporterManager.java @@ -223,7 +223,6 @@ public void batteryCompleted( ReportEntry report ) } catch ( Exception e ) { - handleReporterException( "suiteCompleted", e ); } } } @@ -243,6 +242,8 @@ public void batteryAborted( ReportEntry report ) handleReporterException( "suiteAborted", e ); } } + + ++errors; } // ---------------------------------------------------------------------- diff --git a/surefire/src/test/org/codehaus/surefire/POJOTest.java b/surefire/src/test/org/codehaus/surefire/POJOTest.java new file mode 100644 index 0000000000..5d77187ea6 --- /dev/null +++ b/surefire/src/test/org/codehaus/surefire/POJOTest.java @@ -0,0 +1,18 @@ +package org.codehaus.surefire; + +/** + * Implementation of a POJO with test methods. + */ +public class POJOTest +{ + public void testFoo() + { + System.out.println("Foo"); + } + + public void testBar() + { + System.out.println("Bar"); + } + +} diff --git a/surefire/src/test/org/codehaus/surefire/SysUnitTest.java b/surefire/src/test/org/codehaus/surefire/SysUnitTest.java new file mode 100644 index 0000000000..21ec592333 --- /dev/null +++ b/surefire/src/test/org/codehaus/surefire/SysUnitTest.java @@ -0,0 +1,31 @@ +package org.codehaus.surefire; + +import junit.framework.TestResult; + +/** + * This class provides the 'suite' and junit.framework.Test API + * without implementing an interface. It (hopefully) mimicks + * a sysunit generated testcase. + */ +public class SysUnitTest +{ + public static Object suite() + { + return new SysUnitTest(); + } + + public int countTestCases( TestResult tr ) + { + return 1; + } + + public void run() + { + testFoo(); + } + + public void testFoo() + { + System.out.println("No assert available"); + } +}
328b8d4d2ee831d64f8347072f95cf70a07e24a1
artificerrepo$artificer
Moved the test maven projects. Updated the s-ramp wagon's "get" functionality to bring it in-line with put.
p
https://github.com/artificerrepo/artificer
diff --git a/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java b/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java index c0caeb408..7c3f588e8 100644 --- a/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java +++ b/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java @@ -15,20 +15,13 @@ */ package org.overlord.sramp.wagon; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.io.StringWriter; -import java.security.MessageDigest; import javax.xml.bind.JAXBException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; import org.apache.commons.io.IOUtils; import org.apache.http.conn.HttpHostConnectException; @@ -59,9 +52,7 @@ import org.overlord.sramp.client.SrampServerException; import org.overlord.sramp.wagon.models.MavenGavInfo; import org.overlord.sramp.wagon.util.DevNullOutputStream; -import org.overlord.sramp.wagon.util.PomGenerator; import org.s_ramp.xmlns._2010.s_ramp.BaseArtifactType; -import org.w3c.dom.Document; /** * Implements a wagon provider that uses the S-RAMP Atom API. @@ -127,11 +118,65 @@ public void closeConnection() throws ConnectionException { public void fillInputData(InputData inputData) throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException { Resource resource = inputData.getResource(); - + // Skip maven-metadata.xml files - they are not (yet?) supported if (resource.getName().contains("maven-metadata.xml")) throw new ResourceDoesNotExistException("Could not find file: '" + resource + "'"); logger.debug("Looking up resource from s-ramp repository: " + resource); + + MavenGavInfo gavInfo = MavenGavInfo.fromResource(resource); + if (gavInfo.isHash()) { + doGetHash(gavInfo, inputData); + } else { + doGetArtifact(gavInfo, inputData); + } + + } + + /** + * Gets the hash data from the s-ramp repository and stores it in the {@link InputData} for + * use by Maven. + * @param gavInfo + * @param inputData + * @throws TransferFailedException + * @throws ResourceDoesNotExistException + * @throws AuthorizationException + */ + private void doGetHash(MavenGavInfo gavInfo, InputData inputData) throws TransferFailedException, + ResourceDoesNotExistException, AuthorizationException { + String artyPath = gavInfo.getFullName(); + String hashPropName; + if (gavInfo.getType().endsWith(".md5")) { + hashPropName = "maven.hash.md5"; + artyPath = artyPath.substring(0, artyPath.length() - 4); + } else { + hashPropName = "maven.hash.sha1"; + artyPath = artyPath.substring(0, artyPath.length() - 5); + } + SrampArchiveEntry entry = this.archive.getEntry(artyPath); + if (entry == null) { + throw new ResourceDoesNotExistException("Failed to find resource hash: " + gavInfo.getName()); + } + BaseArtifactType metaData = entry.getMetaData(); + + String hashValue = SrampModelUtils.getCustomProperty(metaData, hashPropName); + if (hashValue == null) { + throw new ResourceDoesNotExistException("Failed to find resource hash: " + gavInfo.getName()); + } + inputData.setInputStream(IOUtils.toInputStream(hashValue)); + } + + /*** + * Gets the artifact content from the s-ramp repository and stores it in the {@link InputData} + * object for use by Maven. + * @param gavInfo + * @param inputData + * @throws TransferFailedException + * @throws ResourceDoesNotExistException + * @throws AuthorizationException + */ + private void doGetArtifact(MavenGavInfo gavInfo, InputData inputData) throws TransferFailedException, + ResourceDoesNotExistException, AuthorizationException { // RESTEasy uses the current thread's context classloader to load its logger class. This // fails in Maven because the context classloader is the wagon plugin's classloader, which // doesn't know about any of the RESTEasy JARs. So here we're temporarily setting the @@ -140,43 +185,19 @@ public void fillInputData(InputData inputData) throws TransferFailedException, ClassLoader oldCtxCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(SrampWagon.class.getClassLoader()); try { - MavenGavInfo gavInfo = MavenGavInfo.fromResource(resource); String endpoint = getSrampEndpoint(); SrampAtomApiClient client = new SrampAtomApiClient(endpoint); // Query the artifact meta data using GAV info BaseArtifactType artifact = findExistingArtifact(client, gavInfo); if (artifact == null) - throw new ResourceDoesNotExistException("Artifact not found in s-ramp repository: '" + resource + "'"); + throw new ResourceDoesNotExistException("Artifact not found in s-ramp repository: '" + gavInfo.getName() + "'"); + this.archive.addEntry(gavInfo.getFullName(), artifact, null); ArtifactType type = ArtifactType.valueOf(artifact); - if ("pom".equals(gavInfo.getType())) { - String serializedPom = generatePom(artifact); - inputData.setInputStream(new ByteArrayInputStream(serializedPom.getBytes("UTF-8"))); - return; - } else if ("pom.sha1".equals(gavInfo.getType())) { - // Generate a SHA1 hash on the fly for the POM - String serializedPom = generatePom(artifact); - MessageDigest md = MessageDigest.getInstance("SHA1"); - md.update(serializedPom.getBytes("UTF-8")); - byte[] mdbytes = md.digest(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mdbytes.length; i++) { - sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); - } - inputData.setInputStream(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); - return; - } else if (gavInfo.getType().endsWith(".sha1")) { - InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); - String sha1Hash = generateSHA1Hash(artifactContent); - inputData.setInputStream(new ByteArrayInputStream(sha1Hash.getBytes("UTF-8"))); - return; - } else { - // Get the artifact content as an input stream - InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); - inputData.setInputStream(artifactContent); - return; - } + // Get the artifact content as an input stream + InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); + inputData.setInputStream(artifactContent); } catch (ResourceDoesNotExistException e) { throw e; } catch (SrampClientException e) { @@ -189,64 +210,6 @@ public void fillInputData(InputData inputData) throws TransferFailedException, } finally { Thread.currentThread().setContextClassLoader(oldCtxCL); } - throw new ResourceDoesNotExistException("Could not find file: '" + resource + "'"); - } - - /** - * Generates a SHA1 hash for the given binary content. - * @param artifactContent an s-ramp artifact input stream - * @return a SHA1 hash - */ - private String generateSHA1Hash(InputStream artifactContent) { - try { - MessageDigest md = MessageDigest.getInstance("SHA1"); - byte[] buff = new byte[2048]; - int count = artifactContent.read(buff); - while (count != -1) { - md.update(buff, 0, count); - count = artifactContent.read(buff); - } - byte[] mdbytes = md.digest(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < mdbytes.length; i++) { - sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); - } - return sb.toString(); - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - IOUtils.closeQuietly(artifactContent); - } - } - - /** - * Generates a POM for the artifact. - * @param artifact - * @throws Exception - */ - private String generatePom(BaseArtifactType artifact) throws Exception { - ArtifactType type = ArtifactType.valueOf(artifact); - PomGenerator pomGenerator = new PomGenerator(); - Document pomDoc = pomGenerator.generatePom(artifact, type); - String serializedPom = serializeDocument(pomDoc); - return serializedPom; - } - - /** - * Serialize a document to a string. - * @param document - */ - private String serializeDocument(Document document) { - try { - StringWriter writer = new StringWriter(); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); - transformer.transform(new DOMSource(document), new StreamResult(writer)); - return writer.toString(); - } catch (Exception e) { - throw new RuntimeException(e); - } } /** @@ -503,7 +466,8 @@ private BaseArtifactType findExistingArtifactByGAV(SrampAtomApiClient client, Ma * @throws SrampServerException * @throws JAXBException */ - private BaseArtifactType findExistingArtifactByUniversal(SrampAtomApiClient client, MavenGavInfo gavInfo) throws SrampServerException, SrampClientException, JAXBException { + private BaseArtifactType findExistingArtifactByUniversal(SrampAtomApiClient client, MavenGavInfo gavInfo) + throws SrampServerException, SrampClientException, JAXBException { String artifactType = gavInfo.getGroupId().substring(gavInfo.getGroupId().indexOf('.') + 1); String uuid = gavInfo.getArtifactId(); Entry entry = null; diff --git a/s-ramp-wagon/src/main/resources/org/overlord/sramp/wagon/util/pom.template b/s-ramp-wagon/src/main/resources/org/overlord/sramp/wagon/util/pom.template deleted file mode 100644 index f512f2053..000000000 --- a/s-ramp-wagon/src/main/resources/org/overlord/sramp/wagon/util/pom.template +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0"?> -<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 http://maven.apache.org/maven-v4_0_0.xsd"> - - <modelVersion>4.0.0</modelVersion> - <groupId /> - <artifactId /> - <version /> - <name /> - <description /> - <type /> - - <dependencies> - </dependencies> - -</project> \ No newline at end of file diff --git a/s-ramp-wagon/src/test/resources/test-wagon-pull/.gitignore b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/.gitignore similarity index 100% rename from s-ramp-wagon/src/test/resources/test-wagon-pull/.gitignore rename to s-ramp-wagon/src/test/maven-projects/test-wagon-pull/.gitignore diff --git a/s-ramp-wagon/src/test/resources/test-wagon-pull/pom.xml b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/pom.xml similarity index 92% rename from s-ramp-wagon/src/test/resources/test-wagon-pull/pom.xml rename to s-ramp-wagon/src/test/maven-projects/test-wagon-pull/pom.xml index 1f9d097bd..71ea9bf15 100644 --- a/s-ramp-wagon/src/test/resources/test-wagon-pull/pom.xml +++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/pom.xml @@ -5,6 +5,7 @@ <artifactId>test-wagon-pull</artifactId> <version>0.0.1-SNAPSHOT</version> <name>test-wagon-pull</name> + <repositories> <repository> <id>local-sramp-repo</id> @@ -25,7 +26,11 @@ <groupId>org.overlord.sramp.test</groupId> <artifactId>test-wagon-push</artifactId> <version>0.0.1-SNAPSHOT</version> - <type>xsd</type> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.10</version> </dependency> </dependencies> diff --git a/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/main/java/org/overlord/sramp/wagontest/TestPullDependency.java b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/main/java/org/overlord/sramp/wagontest/TestPullDependency.java new file mode 100644 index 000000000..0aed61c75 --- /dev/null +++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/main/java/org/overlord/sramp/wagontest/TestPullDependency.java @@ -0,0 +1,43 @@ +/* + * Copyright 2012 JBoss Inc + * + * 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 + * + * http://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.overlord.sramp.wagontest; + +import org.overlord.sramp.test.wagon.Widget; + +/** + * Tests the ability to create a new instance of the generated class found in + * the test-wagon-push project. + * + * @author [email protected] + */ +public class TestPullDependency { + + /** + * Constructor. + */ + public TestPullDependency() { + } + + /** + * Do something with a Widget. + */ + public void doit() { + Widget widget = new Widget(); + System.out.println("It's done!"); + System.out.println(widget); + } + +} diff --git a/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/test/java/org/overlord/sramp/wagontest/TestPullDependencyTest.java b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/test/java/org/overlord/sramp/wagontest/TestPullDependencyTest.java new file mode 100644 index 000000000..fa54b9f5f --- /dev/null +++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/test/java/org/overlord/sramp/wagontest/TestPullDependencyTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2012 JBoss Inc + * + * 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 + * + * http://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.overlord.sramp.wagontest; + +import org.junit.Test; + +/** + * Unit test. + * + * @author [email protected] + */ +public class TestPullDependencyTest { + + /** + * Test method for {@link org.overlord.sramp.wagontest.TestPullDependency#doit()}. + */ + @Test + public void testDoit() { + TestPullDependency tpd = new TestPullDependency(); + tpd.doit(); + System.out.println("DONE: success"); + } + +} diff --git a/s-ramp-wagon/src/test/resources/test-wagon-push/.gitignore b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/.gitignore similarity index 100% rename from s-ramp-wagon/src/test/resources/test-wagon-push/.gitignore rename to s-ramp-wagon/src/test/maven-projects/test-wagon-push/.gitignore diff --git a/s-ramp-wagon/src/test/resources/test-wagon-push/pom.xml b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/pom.xml similarity index 97% rename from s-ramp-wagon/src/test/resources/test-wagon-push/pom.xml rename to s-ramp-wagon/src/test/maven-projects/test-wagon-push/pom.xml index 595c057ff..0706da5d9 100644 --- a/s-ramp-wagon/src/test/resources/test-wagon-push/pom.xml +++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/pom.xml @@ -10,7 +10,7 @@ <repository> <id>local-sramp-repo</id> <name>Local S-RAMP Repository</name> - <url>sramp://localhost:9090/s-ramp-atom/s-ramp/</url> + <url>sramp://localhost:8080/s-ramp-atom/s-ramp/</url> <layout>default</layout> <releases> <enabled>true</enabled> diff --git a/s-ramp-wagon/src/test/resources/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd similarity index 100% rename from s-ramp-wagon/src/test/resources/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd rename to s-ramp-wagon/src/test/maven-projects/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd
5dfc5a6dff7de7cdff1743a628ee3bb586f6d003
orientdb
last attempt of fixing test failing on ci.--
c
https://github.com/orientechnologies/orientdb
diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java index 91dca4b5700..de83629074a 100644 --- a/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java +++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/GraphTxAbstractTest.java @@ -20,8 +20,8 @@ package com.orientechnologies.orient.graph; -import org.junit.After; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import com.tinkerpop.blueprints.impls.orient.OrientGraph; @@ -31,7 +31,7 @@ * @author Luca Garulli */ public abstract class GraphTxAbstractTest { - protected OrientGraph graph; + protected static OrientGraph graph; public static enum ENV { DEV, RELEASE, CI @@ -58,8 +58,8 @@ public static String getStorageType() { return "plocal"; } - @Before - public void beforeClass() { + @BeforeClass + public static void beforeClass() { if (graph == null) { final String dbName = GraphTxAbstractTest.class.getSimpleName(); final String storageType = getStorageType(); @@ -71,9 +71,10 @@ public void beforeClass() { } - @After - public void afterClass() throws Exception { + @AfterClass + public static void afterClass() throws Exception { graph.shutdown(); graph = null; } + } diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java index 2034cc9e7b8..f8bb970d069 100755 --- a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java +++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/RequireTransactionTest.java @@ -20,14 +20,64 @@ package com.orientechnologies.orient.graph.sql; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + import com.orientechnologies.orient.core.exception.OTransactionException; import com.orientechnologies.orient.graph.GraphTxAbstractTest; -import org.junit.Test; +import com.tinkerpop.blueprints.impls.orient.OrientGraph; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +public class RequireTransactionTest { + + protected static OrientGraph graph; + + public static enum ENV { + DEV, RELEASE, CI + } -public class RequireTransactionTest extends GraphTxAbstractTest { + public static ENV getEnvironment() { + String envName = System.getProperty("orientdb.test.env", "dev").toUpperCase(); + ENV result = null; + try { + result = ENV.valueOf(envName); + } catch (IllegalArgumentException e) { + } + + if (result == null) + result = ENV.DEV; + + return result; + } + + public static String getStorageType() { + if (getEnvironment().equals(ENV.DEV)) + return "memory"; + + return "plocal"; + } + + @BeforeClass + public static void beforeClass() { + if (graph == null) { + final String dbName = GraphTxAbstractTest.class.getSimpleName(); + final String storageType = getStorageType(); + final String buildDirectory = System.getProperty("buildDirectory", "."); + graph = new OrientGraph(storageType + ":" + buildDirectory + "/" + dbName); + graph.drop(); + graph = new OrientGraph(storageType + ":" + buildDirectory + "/" + dbName); + } + + } + + @AfterClass + public static void afterClass() throws Exception { + graph.shutdown(); + graph = null; + } @Test public void requireTxEnable() { diff --git a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java index 54cc8294ea5..74cbf4750ef 100755 --- a/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java +++ b/graphdb/src/test/java/com/orientechnologies/orient/graph/sql/SQLMoveVertexCommandInTxTest.java @@ -21,6 +21,7 @@ package com.orientechnologies.orient.graph.sql; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; import com.orientechnologies.common.util.OCallable; @@ -34,13 +35,14 @@ import com.tinkerpop.blueprints.impls.orient.OrientVertexType; public class SQLMoveVertexCommandInTxTest extends GraphTxAbstractTest { - private OrientVertexType customer; - private OrientVertexType provider; - private OrientEdgeType knows; - private int customerGeniusCluster; - - public void beforeClass() { - super.beforeClass(); + private static OrientVertexType customer; + private static OrientVertexType provider; + private static OrientEdgeType knows; + private static int customerGeniusCluster; + + @BeforeClass + public static void beforeClass() { + GraphTxAbstractTest.beforeClass(); graph.executeOutsideTx(new OCallable<Object, OrientBaseGraph>() { @Override public Object call(OrientBaseGraph iArgument) {
8210d3091f64a3de385ce6f01314322620f82735
kotlin
Initial implementation of KT-6427 Completion to- use Java name suggestion to complete function parameters (+ filtered out- synthetic Kotlin classes from completion)--
a
https://github.com/JetBrains/kotlin
diff --git a/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt b/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt index f6a66580a18d0..a4956fc30ae7c 100644 --- a/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt +++ b/core/util.runtime/src/org/jetbrains/kotlin/utils/addToStdlib.kt @@ -95,3 +95,13 @@ public fun <T : Any> constant(calculator: () -> T): T { } private val constantMap = ConcurrentHashMap<Function0<*>, Any>() + +public fun String.indexOfOrNull(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int? { + val index = indexOf(char, startIndex, ignoreCase) + return if (index >= 0) index else null +} + +public fun String.lastIndexOfOrNull(char: Char, startIndex: Int = 0, ignoreCase: Boolean = false): Int? { + val index = lastIndexOf(char, startIndex, ignoreCase) + return if (index >= 0) index else null +} diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt index 5695484ee29d4..e85703308ead7 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt @@ -19,8 +19,10 @@ package org.jetbrains.kotlin.idea.completion import com.intellij.codeInsight.completion.AllClassesGetter import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.PrefixMatcher +import com.intellij.psi.PsiClass import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.asJava.KotlinLightClass +import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor @@ -31,34 +33,28 @@ import org.jetbrains.kotlin.platform.JavaToKotlinClassMap import org.jetbrains.kotlin.psi.JetFile import org.jetbrains.kotlin.resolve.BindingContext -class AllClassesCompletion(val parameters: CompletionParameters, - val lookupElementFactory: LookupElementFactory, - val resolutionFacade: ResolutionFacade, - val bindingContext: BindingContext, - val moduleDescriptor: ModuleDescriptor, - val scope: GlobalSearchScope, - val prefixMatcher: PrefixMatcher, - val kindFilter: (ClassKind) -> Boolean, - val visibilityFilter: (DeclarationDescriptor) -> Boolean) { - fun collect(result: LookupElementsCollector) { +class AllClassesCompletion(private val parameters: CompletionParameters, + private val kotlinIndicesHelper: KotlinIndicesHelper, + private val prefixMatcher: PrefixMatcher, + private val kindFilter: (ClassKind) -> Boolean) { + fun collect(classDescriptorCollector: (ClassDescriptor) -> Unit, javaClassCollector: (PsiClass) -> Unit) { //TODO: this is a temporary hack until we have built-ins in indices val builtIns = JavaToKotlinClassMap.INSTANCE.allKotlinClasses() val filteredBuiltIns = builtIns.filter { kindFilter(it.getKind()) && prefixMatcher.prefixMatches(it.getName().asString()) } - result.addDescriptorElements(filteredBuiltIns, suppressAutoInsertion = true) + filteredBuiltIns.forEach { classDescriptorCollector(it) } - val project = parameters.getOriginalFile().getProject() - val helper = KotlinIndicesHelper(project, resolutionFacade, bindingContext, scope, moduleDescriptor, visibilityFilter) - result.addDescriptorElements(helper.getClassDescriptors({ prefixMatcher.prefixMatches(it) }, kindFilter), - suppressAutoInsertion = true) + kotlinIndicesHelper.getClassDescriptors({ prefixMatcher.prefixMatches(it) }, kindFilter).forEach { classDescriptorCollector(it) } if (!ProjectStructureUtil.isJsKotlinModule(parameters.getOriginalFile() as JetFile)) { - addAdaptedJavaCompletion(result) + addAdaptedJavaCompletion(javaClassCollector) } } - private fun addAdaptedJavaCompletion(collector: LookupElementsCollector) { + private fun addAdaptedJavaCompletion(collector: (PsiClass) -> Unit) { AllClassesGetter.processJavaClasses(parameters, prefixMatcher, true, { psiClass -> if (psiClass!! !is KotlinLightClass) { // Kotlin class should have already been added as kotlin element before + if (psiClass.isSyntheticKotlinClass()) return@processJavaClasses // filter out synthetic classes produced by Kotlin compiler + val kind = when { psiClass.isAnnotationType() -> ClassKind.ANNOTATION_CLASS psiClass.isInterface() -> ClassKind.INTERFACE @@ -66,9 +62,14 @@ class AllClassesCompletion(val parameters: CompletionParameters, else -> ClassKind.CLASS } if (kindFilter(kind)) { - collector.addElementWithAutoInsertionSuppressed(lookupElementFactory.createLookupElementForJavaClass(psiClass)) + collector(psiClass) } } }) } + + private fun PsiClass.isSyntheticKotlinClass(): Boolean { + if (!getName().contains('$')) return false // optimization to not analyze annotations of all classes + return getModifierList()?.findAnnotation(javaClass<kotlin.jvm.internal.KotlinSyntheticClass>().getName()) != null + } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt index bf305d55203a0..c8f9564bb216a 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt @@ -128,7 +128,7 @@ abstract class CompletionSessionBase(protected val configuration: CompletionSess protected val prefixMatcher: PrefixMatcher = this.resultSet.getPrefixMatcher() - protected val referenceVariantsHelper: ReferenceVariantsHelper = ReferenceVariantsHelper(bindingContext, moduleDescriptor, project) { isVisibleDescriptor(it) } + protected val referenceVariantsHelper: ReferenceVariantsHelper = ReferenceVariantsHelper(bindingContext, moduleDescriptor, project, { isVisibleDescriptor(it) }) protected val receiversData: ReferenceVariantsHelper.ReceiversData? = reference?.let { referenceVariantsHelper.getReferenceVariantsReceivers(it.expression) } @@ -168,7 +168,7 @@ abstract class CompletionSessionBase(protected val configuration: CompletionSess } protected val indicesHelper: KotlinIndicesHelper - get() = KotlinIndicesHelper(project, resolutionFacade, bindingContext, searchScope, moduleDescriptor) { isVisibleDescriptor(it) } + get() = KotlinIndicesHelper(project, resolutionFacade, searchScope, moduleDescriptor, { isVisibleDescriptor(it) }) protected fun isVisibleDescriptor(descriptor: DeclarationDescriptor): Boolean { if (descriptor is DeclarationDescriptorWithVisibility && inDescriptor != null) { @@ -241,7 +241,7 @@ abstract class CompletionSessionBase(protected val configuration: CompletionSess } protected fun getTopLevelExtensions(): Collection<CallableDescriptor> { - val descriptors = indicesHelper.getCallableTopLevelExtensions({ prefixMatcher.prefixMatches(it) }, reference!!.expression) + val descriptors = indicesHelper.getCallableTopLevelExtensions({ prefixMatcher.prefixMatches(it) }, reference!!.expression, bindingContext) return filterShadowedNonImported(descriptors, reference) } @@ -250,10 +250,11 @@ abstract class CompletionSessionBase(protected val configuration: CompletionSess } protected fun addAllClasses(kindFilter: (ClassKind) -> Boolean) { - AllClassesCompletion( - parameters, lookupElementFactory, resolutionFacade, bindingContext, moduleDescriptor, - searchScope, prefixMatcher, kindFilter, { isVisibleDescriptor(it) } - ).collect(collector) + AllClassesCompletion(parameters, indicesHelper, prefixMatcher, kindFilter) + .collect( + { descriptor -> collector.addDescriptorElements(descriptor, suppressAutoInsertion = true) }, + { javaClass -> collector.addElementWithAutoInsertionSuppressed(lookupElementFactory.createLookupElementForJavaClass(javaClass)) } + ) } } @@ -287,6 +288,11 @@ class BasicCompletionSession(configuration: CompletionSessionConfiguration, null } + private val parameterNameAndTypeCompletion = if (completionKind == CompletionKind.ANNOTATION_TYPES_OR_PARAMETER_NAME) + ParameterNameAndTypeCompletion(collector, lookupElementFactory, prefixMatcher) + else + null + private fun calcCompletionKind(): CompletionKind { if (NamedArgumentCompletion.isOnlyNamedArgumentExpected(position)) { return CompletionKind.NAMED_ARGUMENTS_ONLY @@ -327,6 +333,8 @@ class BasicCompletionSession(configuration: CompletionSessionConfiguration, if (completionKind != CompletionKind.NAMED_ARGUMENTS_ONLY) { collector.addDescriptorElements(referenceVariants, suppressAutoInsertion = false) + parameterNameAndTypeCompletion?.addFromImports(reference!!.expression, bindingContext, { isVisibleDescriptor(it) }) + val keywordsPrefix = prefix.substringBefore('@') // if there is '@' in the prefix - use shorter prefix to not loose 'this' etc KeywordCompletion.complete(expression ?: parameters.getPosition(), keywordsPrefix) { lookupElement -> val keyword = lookupElement.getLookupString() @@ -405,6 +413,8 @@ class BasicCompletionSession(configuration: CompletionSessionConfiguration, collector.addDescriptorElements(getTopLevelCallables(), suppressAutoInsertion = true) } } + + parameterNameAndTypeCompletion?.addAll(parameters, indicesHelper) } } diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt index 110e1b57854fc..deef7e1f7c996 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/KotlinCompletionContributor.kt @@ -225,11 +225,6 @@ public class KotlinCompletionContributor : CompletionContributor() { if (parameters.getCompletionType() == CompletionType.BASIC) { val session = BasicCompletionSession(configuration, parameters, result) - if (session.completionKind == BasicCompletionSession.CompletionKind.ANNOTATION_TYPES_OR_PARAMETER_NAME && parameters.isAutoPopup()) { - result.stopHere() - return - } - val somethingAdded = session.complete() if (!somethingAdded && parameters.getInvocationCount() < 2) { // Rerun completion if nothing was found diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt index 3a49024f089e6..1ed9f088b3f09 100644 --- a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/LookupElementsCollector.kt @@ -69,7 +69,7 @@ class LookupElementsCollector( } } - private fun addDescriptorElements(descriptor: DeclarationDescriptor, suppressAutoInsertion: Boolean, withReceiverCast: Boolean) { + public fun addDescriptorElements(descriptor: DeclarationDescriptor, suppressAutoInsertion: Boolean, withReceiverCast: Boolean = false) { run { var lookupElement = lookupElementFactory.createLookupElement(descriptor, true) diff --git a/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ParameterNameAndTypeCompletion.kt b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ParameterNameAndTypeCompletion.kt new file mode 100644 index 0000000000000..269ebb6bc9e74 --- /dev/null +++ b/idea/idea-completion/src/org/jetbrains/kotlin/idea/completion/ParameterNameAndTypeCompletion.kt @@ -0,0 +1,127 @@ +/* + * Copyright 2010-2015 JetBrains s.r.o. + * + * 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 + * + * http://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.jetbrains.kotlin.idea.completion + +import com.intellij.codeInsight.completion.CompletionParameters +import com.intellij.codeInsight.completion.InsertionContext +import com.intellij.codeInsight.completion.PrefixMatcher +import com.intellij.codeInsight.lookup.LookupElement +import com.intellij.codeInsight.lookup.LookupElementDecorator +import com.intellij.codeInsight.lookup.LookupElementPresentation +import com.intellij.psi.PsiClass +import com.intellij.psi.codeStyle.CodeStyleSettingsManager +import org.jetbrains.kotlin.descriptors.ClassifierDescriptor +import org.jetbrains.kotlin.descriptors.DeclarationDescriptor +import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper +import org.jetbrains.kotlin.idea.core.formatter.JetCodeStyleSettings +import org.jetbrains.kotlin.idea.core.refactoring.EmptyValidator +import org.jetbrains.kotlin.idea.core.refactoring.JetNameSuggester +import org.jetbrains.kotlin.psi.JetSimpleNameExpression +import org.jetbrains.kotlin.resolve.BindingContext +import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter +import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered + +class ParameterNameAndTypeCompletion( + private val collector: LookupElementsCollector, + private val lookupElementFactory: LookupElementFactory, + private val prefixMatcher: PrefixMatcher +) { + private val modifiedPrefixMatcher = prefixMatcher.cloneWithPrefix(prefixMatcher.getPrefix().capitalize()) + + public fun addFromImports(nameExpression: JetSimpleNameExpression, bindingContext: BindingContext, visibilityFilter: (DeclarationDescriptor) -> Boolean) { + if (prefixMatcher.getPrefix().isEmpty()) return + + val resolutionScope = bindingContext[BindingContext.RESOLUTION_SCOPE, nameExpression] ?: return + val classifiers = resolutionScope.getDescriptorsFiltered(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS, modifiedPrefixMatcher.asNameFilter()) + + for (classifier in classifiers) { + if (visibilityFilter(classifier)) { + addSuggestionsForClassifier(classifier) + } + } + } + + public fun addAll(parameters: CompletionParameters, indicesHelper: KotlinIndicesHelper) { + if (prefixMatcher.getPrefix().isEmpty()) return + + AllClassesCompletion(parameters, indicesHelper, modifiedPrefixMatcher, { !it.isSingleton() }) + .collect({ addSuggestionsForClassifier(it) }, { addSuggestionsForJavaClass(it) }) + } + + private fun addSuggestionsForClassifier(classifier: DeclarationDescriptor) { + addSuggestions(classifier.getName().asString()) { name -> NameAndDescriptorType(name, classifier as ClassifierDescriptor) } + } + + private fun addSuggestionsForJavaClass(psiClass: PsiClass) { + addSuggestions(psiClass.getName()) { name -> NameAndJavaType(name, psiClass) } + } + + private inline fun addSuggestions(className: String, nameAndTypeFactory: (String) -> NameAndType) { + val parameterNames = JetNameSuggester.getCamelNames(className, EmptyValidator) + for (parameterName in parameterNames) { + if (prefixMatcher.prefixMatches(parameterName)) { + val nameAndType = nameAndTypeFactory(parameterName) + collector.addElement(MyLookupElement(nameAndType, lookupElementFactory)) + } + } + } + + private interface NameAndType { + val parameterName: String + + fun createTypeLookupElement(lookupElementFactory: LookupElementFactory): LookupElement + } + + private data class NameAndDescriptorType(override val parameterName: String, val type: ClassifierDescriptor) : NameAndType { + override fun createTypeLookupElement(lookupElementFactory: LookupElementFactory) + = lookupElementFactory.createLookupElement(type, false) + } + + private data class NameAndJavaType(override val parameterName: String, val type: PsiClass) : NameAndType { + override fun createTypeLookupElement(lookupElementFactory: LookupElementFactory) + = lookupElementFactory.createLookupElementForJavaClass(type) + } + + private class MyLookupElement( + val nameAndType: NameAndType, + factory: LookupElementFactory + ) : LookupElementDecorator<LookupElement>(nameAndType.createTypeLookupElement(factory)) { + override fun getObject() = nameAndType + + override fun equals(other: Any?) + = other is MyLookupElement && nameAndType.parameterName == other.getObject().parameterName && getDelegate() == other.getDelegate() + override fun hashCode() = nameAndType.parameterName.hashCode() + + override fun getLookupString() = nameAndType.parameterName + override fun getAllLookupStrings() = setOf(nameAndType.parameterName) + + override fun renderElement(presentation: LookupElementPresentation) { + super.renderElement(presentation) + presentation.setItemText(nameAndType.parameterName + ": " + presentation.getItemText()) + } + + override fun handleInsert(context: InsertionContext) { + super.handleInsert(context) + + val settings = CodeStyleSettingsManager.getInstance(context.getProject()).getCurrentSettings().getCustomSettings(javaClass<JetCodeStyleSettings>()) + val spaceBefore = if (settings.SPACE_BEFORE_TYPE_COLON) " " else "" + val spaceAfter = if (settings.SPACE_AFTER_TYPE_COLON) " " else "" + val text = nameAndType.parameterName + spaceBefore + ":" + spaceAfter + context.getDocument().insertString(context.getStartOffset(), text) + } + } +} \ No newline at end of file diff --git a/idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup1.kt b/idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup1.kt deleted file mode 100644 index 30d1f85466c72..0000000000000 --- a/idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup1.kt +++ /dev/null @@ -1,4 +0,0 @@ -fun foo(i<caret>) { } - -// INVOCATION_COUNT: 0 -// NUMBER: 0 diff --git a/idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup2.kt b/idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup2.kt deleted file mode 100644 index 7453355e09ab3..0000000000000 --- a/idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup2.kt +++ /dev/null @@ -1,4 +0,0 @@ -fun foo(@inlineOptions i<caret>) { } - -// INVOCATION_COUNT: 0 -// NUMBER: 0 diff --git a/idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplication.kt b/idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplication.kt new file mode 100644 index 0000000000000..3162454ff168d --- /dev/null +++ b/idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplication.kt @@ -0,0 +1,6 @@ +import kotlin.properties.* + +fun f(readOnlyProp<caret>) + +// EXIST: { lookupString: "readOnlyProperty", itemText: "readOnlyProperty: ReadOnlyProperty", tailText: "<R, T> (kotlin.properties)" } +// NUMBER: 1 diff --git a/idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplicationJava.kt b/idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplicationJava.kt new file mode 100644 index 0000000000000..5f6b9fe24f15e --- /dev/null +++ b/idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplicationJava.kt @@ -0,0 +1,6 @@ +import java.io.* + +fun f(printSt<caret>) + +// EXIST_JAVA_ONLY: { lookupString: "printStream", itemText: "printStream: PrintStream", tailText: " (java.io)" } +// NUMBER_JAVA: 1 diff --git a/idea/idea-completion/testData/basic/common/parameterNameAndType/NotImported.kt b/idea/idea-completion/testData/basic/common/parameterNameAndType/NotImported.kt new file mode 100644 index 0000000000000..181fb9881d1e2 --- /dev/null +++ b/idea/idea-completion/testData/basic/common/parameterNameAndType/NotImported.kt @@ -0,0 +1,3 @@ +fun f(read<caret>) + +// EXIST: { lookupString: "readOnlyProperty", itemText: "readOnlyProperty: ReadOnlyProperty", tailText: "<R, T> (kotlin.properties)" } diff --git a/idea/idea-completion/testData/basic/common/parameterNameAndType/NotImportedJava.kt b/idea/idea-completion/testData/basic/common/parameterNameAndType/NotImportedJava.kt new file mode 100644 index 0000000000000..3f30d7f894023 --- /dev/null +++ b/idea/idea-completion/testData/basic/common/parameterNameAndType/NotImportedJava.kt @@ -0,0 +1,3 @@ +fun f(file<caret>) + +// EXIST_JAVA_ONLY: { lookupString: "file", itemText: "file: File", tailText: " (java.io)" } diff --git a/idea/idea-completion/testData/basic/common/parameterNameAndType/Simple.kt b/idea/idea-completion/testData/basic/common/parameterNameAndType/Simple.kt new file mode 100644 index 0000000000000..ee9e2ceaf5fe4 --- /dev/null +++ b/idea/idea-completion/testData/basic/common/parameterNameAndType/Simple.kt @@ -0,0 +1,11 @@ +package pack + +class FooBar + +class Boo + +fun f(b<caret>) + +// EXIST: { lookupString: "bar", itemText: "bar: FooBar", tailText: " (pack)" } +// EXIST: { lookupString: "fooBar", itemText: "fooBar: FooBar", tailText: " (pack)" } +// EXIST: { lookupString: "boo", itemText: "boo: Boo", tailText: " (pack)" } diff --git a/idea/idea-completion/testData/basic/java/NoSyntheticClasses.kt b/idea/idea-completion/testData/basic/java/NoSyntheticClasses.kt new file mode 100644 index 0000000000000..2db57b5278471 --- /dev/null +++ b/idea/idea-completion/testData/basic/java/NoSyntheticClasses.kt @@ -0,0 +1,8 @@ +import kotlin.properties.* + +val x: ReadOnlyPr<caret> + +// INVOCATION_COUNT: 2 +// EXIST: "ReadOnlyProperty" +// ABSENT: "ReadOnlyProperty$$TImpl" +// NOTHING_ELSE diff --git a/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt b/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt index 701f67f739a71..7b6ee42f6f418 100644 --- a/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt +++ b/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt @@ -1,4 +1,4 @@ -// INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD: false +// CODE_STYLE_SETTING: INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD = false fun main(args: Array<String>) { args.fil<caret> diff --git a/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt.after b/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt.after index 660ad3bff5757..c2441ce4a617a 100644 --- a/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt.after +++ b/idea/idea-completion/testData/handlers/basic/highOrderFunctions/FunctionLiteralInsertWhenNoSpacesForBraces.kt.after @@ -1,4 +1,4 @@ -// INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD: false +// CODE_STYLE_SETTING: INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD = false fun main(args: Array<String>) { args.filter {<caret>} diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt new file mode 100644 index 0000000000000..0220ca6e71761 --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt @@ -0,0 +1,8 @@ +// CODE_STYLE_SETTING: SPACE_BEFORE_TYPE_COLON = true +// CODE_STYLE_SETTING: SPACE_AFTER_TYPE_COLON = false + +class FooBar + +fun f(b<caret>) + +// ELEMENT: bar diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt.after b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt.after new file mode 100644 index 0000000000000..4a35270257d5d --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt.after @@ -0,0 +1,8 @@ +// CODE_STYLE_SETTING: SPACE_BEFORE_TYPE_COLON = true +// CODE_STYLE_SETTING: SPACE_AFTER_TYPE_COLON = false + +class FooBar + +fun f(bar :FooBar<caret>) + +// ELEMENT: bar diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt new file mode 100644 index 0000000000000..21825a1893994 --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt @@ -0,0 +1,6 @@ +class FooBar + +fun f(b<caret>) + +// ELEMENT: bar +// CHAR: ',' diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt.after b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt.after new file mode 100644 index 0000000000000..e2fc7d0a67e0a --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt.after @@ -0,0 +1,6 @@ +class FooBar + +fun f(bar: FooBar, <caret>) + +// ELEMENT: bar +// CHAR: ',' diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt new file mode 100644 index 0000000000000..c44f6430b18a3 --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt @@ -0,0 +1,3 @@ +fun f(file<caret>) + +// ELEMENT_TEXT: "file: File" diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt.after b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt.after new file mode 100644 index 0000000000000..cf38dafd0378e --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt.after @@ -0,0 +1,5 @@ +import java.io.File + +fun f(file: File<caret>) + +// ELEMENT_TEXT: "file: File" diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt new file mode 100644 index 0000000000000..77b3bbb40823d --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt @@ -0,0 +1,5 @@ +class FooBar + +fun f(b<caret>) + +// ELEMENT: bar diff --git a/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt.after b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt.after new file mode 100644 index 0000000000000..5f3ad6bd6c53c --- /dev/null +++ b/idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt.after @@ -0,0 +1,5 @@ +class FooBar + +fun f(bar: FooBar<caret>) + +// ELEMENT: bar diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JSBasicCompletionTestGenerated.java b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JSBasicCompletionTestGenerated.java index 479349908c5b7..7337e37100dbd 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JSBasicCompletionTestGenerated.java +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JSBasicCompletionTestGenerated.java @@ -1053,18 +1053,6 @@ public void testFunctionAnnotation2() throws Exception { doTest(fileName); } - @TestMetadata("NoParameterAnnotationAutoPopup1.kt") - public void testNoParameterAnnotationAutoPopup1() throws Exception { - String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup1.kt"); - doTest(fileName); - } - - @TestMetadata("NoParameterAnnotationAutoPopup2.kt") - public void testNoParameterAnnotationAutoPopup2() throws Exception { - String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup2.kt"); - doTest(fileName); - } - @TestMetadata("ParameterAnnotation1.kt") public void testParameterAnnotation1() throws Exception { String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/annotations/ParameterAnnotation1.kt"); @@ -1402,6 +1390,45 @@ public void testWithParameterExpression() throws Exception { } } + @TestMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType") + @TestDataPath("$PROJECT_ROOT") + @RunWith(JUnit3RunnerWithInners.class) + public static class ParameterNameAndType extends AbstractJSBasicCompletionTest { + public void testAllFilesPresentInParameterNameAndType() throws Exception { + JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/idea-completion/testData/basic/common/parameterNameAndType"), Pattern.compile("^(.+)\\.kt$"), true); + } + + @TestMetadata("NoDuplication.kt") + public void testNoDuplication() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplication.kt"); + doTest(fileName); + } + + @TestMetadata("NoDuplicationJava.kt") + public void testNoDuplicationJava() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplicationJava.kt"); + doTest(fileName); + } + + @TestMetadata("NotImported.kt") + public void testNotImported() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NotImported.kt"); + doTest(fileName); + } + + @TestMetadata("NotImportedJava.kt") + public void testNotImportedJava() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NotImportedJava.kt"); + doTest(fileName); + } + + @TestMetadata("Simple.kt") + public void testSimple() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/Simple.kt"); + doTest(fileName); + } + } + @TestMetadata("idea/idea-completion/testData/basic/common/shadowing") @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class) diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmBasicCompletionTestGenerated.java b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmBasicCompletionTestGenerated.java index 3b103f0f601ee..33b3cd9b38799 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmBasicCompletionTestGenerated.java +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/JvmBasicCompletionTestGenerated.java @@ -1053,18 +1053,6 @@ public void testFunctionAnnotation2() throws Exception { doTest(fileName); } - @TestMetadata("NoParameterAnnotationAutoPopup1.kt") - public void testNoParameterAnnotationAutoPopup1() throws Exception { - String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup1.kt"); - doTest(fileName); - } - - @TestMetadata("NoParameterAnnotationAutoPopup2.kt") - public void testNoParameterAnnotationAutoPopup2() throws Exception { - String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/annotations/NoParameterAnnotationAutoPopup2.kt"); - doTest(fileName); - } - @TestMetadata("ParameterAnnotation1.kt") public void testParameterAnnotation1() throws Exception { String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/annotations/ParameterAnnotation1.kt"); @@ -1402,6 +1390,45 @@ public void testWithParameterExpression() throws Exception { } } + @TestMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType") + @TestDataPath("$PROJECT_ROOT") + @RunWith(JUnit3RunnerWithInners.class) + public static class ParameterNameAndType extends AbstractJvmBasicCompletionTest { + public void testAllFilesPresentInParameterNameAndType() throws Exception { + JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/idea-completion/testData/basic/common/parameterNameAndType"), Pattern.compile("^(.+)\\.kt$"), true); + } + + @TestMetadata("NoDuplication.kt") + public void testNoDuplication() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplication.kt"); + doTest(fileName); + } + + @TestMetadata("NoDuplicationJava.kt") + public void testNoDuplicationJava() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NoDuplicationJava.kt"); + doTest(fileName); + } + + @TestMetadata("NotImported.kt") + public void testNotImported() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NotImported.kt"); + doTest(fileName); + } + + @TestMetadata("NotImportedJava.kt") + public void testNotImportedJava() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/NotImportedJava.kt"); + doTest(fileName); + } + + @TestMetadata("Simple.kt") + public void testSimple() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/common/parameterNameAndType/Simple.kt"); + doTest(fileName); + } + } + @TestMetadata("idea/idea-completion/testData/basic/common/shadowing") @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class) @@ -1696,6 +1723,12 @@ public void testNoDuplicationForRuntimeClass() throws Exception { doTest(fileName); } + @TestMetadata("NoSyntheticClasses.kt") + public void testNoSyntheticClasses() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/NoSyntheticClasses.kt"); + doTest(fileName); + } + @TestMetadata("PackageDirective.kt") public void testPackageDirective() throws Exception { String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/basic/java/PackageDirective.kt"); diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt index 9f6265c08b0d7..56531b30b42c5 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/AbstractCompletionHandlerTests.kt @@ -22,6 +22,7 @@ import com.intellij.psi.codeStyle.CodeStyleSettingsManager import org.jetbrains.kotlin.idea.core.formatter.JetCodeStyleSettings import org.jetbrains.kotlin.idea.test.JetWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.test.InTextDirectivesUtils +import org.jetbrains.kotlin.utils.addToStdlib.indexOfOrNull import java.io.File public abstract class AbstractCompletionHandlerTest(private val defaultCompletionType: CompletionType) : CompletionHandlerTestBase() { @@ -31,7 +32,7 @@ public abstract class AbstractCompletionHandlerTest(private val defaultCompletio private val TAIL_TEXT_PREFIX = "TAIL_TEXT:" private val COMPLETION_CHAR_PREFIX = "CHAR:" private val COMPLETION_TYPE_PREFIX = "COMPLETION_TYPE:" - private val INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD = "INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD:" + private val CODE_STYLE_SETTING_PREFIX = "CODE_STYLE_SETTING:" protected open fun doTest(testPath: String) { setUpFixture(testPath) @@ -61,8 +62,17 @@ public abstract class AbstractCompletionHandlerTest(private val defaultCompletio else -> error("Unknown completion type: $completionTypeString") } - InTextDirectivesUtils.getPrefixedBoolean(fileText, INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD)?.let { - JetCodeStyleSettings.getInstance(getProject()).INSERT_WHITESPACES_IN_SIMPLE_ONE_LINE_METHOD = it + val codeStyleSettings = JetCodeStyleSettings.getInstance(getProject()) + for (line in InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, CODE_STYLE_SETTING_PREFIX)) { + val index = line.indexOfOrNull('=') ?: error("Invalid code style setting '$line': '=' expected") + val settingName = line.substring(0, index).trim() + val settingValue = line.substring(index + 1).trim() + val field = codeStyleSettings.javaClass.getDeclaredField(settingName) + when (field.getType().getName()) { + "boolean" -> field.setBoolean(codeStyleSettings, settingValue.toBoolean()) + "int" -> field.setInt(codeStyleSettings, settingValue.toInt()) + else -> error("Unsupported setting type: ${field.getType()}") + } } doTestWithTextLoaded(completionType, invocationCount, lookupString, itemText, tailText, completionChar, testPath + ".after") diff --git a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTestGenerated.java b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTestGenerated.java index 9fdb38f9459f7..5740ee686ab66 100644 --- a/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTestGenerated.java +++ b/idea/idea-completion/tests/org/jetbrains/kotlin/idea/completion/test/handlers/BasicCompletionHandlerTestGenerated.java @@ -239,6 +239,39 @@ public void testWithArgsNonEmptyLambdaAfter() throws Exception { } } + @TestMetadata("idea/idea-completion/testData/handlers/basic/parameterNameAndType") + @TestDataPath("$PROJECT_ROOT") + @RunWith(JUnit3RunnerWithInners.class) + public static class ParameterNameAndType extends AbstractBasicCompletionHandlerTest { + public void testAllFilesPresentInParameterNameAndType() throws Exception { + JetTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/idea-completion/testData/handlers/basic/parameterNameAndType"), Pattern.compile("^(.+)\\.kt$"), true); + } + + @TestMetadata("CodeStyleSettings.kt") + public void testCodeStyleSettings() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/parameterNameAndType/CodeStyleSettings.kt"); + doTest(fileName); + } + + @TestMetadata("Comma.kt") + public void testComma() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/parameterNameAndType/Comma.kt"); + doTest(fileName); + } + + @TestMetadata("InsertImport.kt") + public void testInsertImport() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/parameterNameAndType/InsertImport.kt"); + doTest(fileName); + } + + @TestMetadata("Simple.kt") + public void testSimple() throws Exception { + String fileName = JetTestUtils.navigationMetadata("idea/idea-completion/testData/handlers/basic/parameterNameAndType/Simple.kt"); + doTest(fileName); + } + } + @TestMetadata("idea/idea-completion/testData/handlers/basic/stringTemplate") @TestDataPath("$PROJECT_ROOT") @RunWith(JUnit3RunnerWithInners.class) diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt index 52f238ca2eff4..f66331389cd58 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/KotlinIndicesHelper.kt @@ -46,7 +46,6 @@ import java.util.LinkedHashSet public class KotlinIndicesHelper( private val project: Project, private val resolutionFacade: ResolutionFacade, - private val bindingContext: BindingContext, private val scope: GlobalSearchScope, private val moduleDescriptor: ModuleDescriptor, private val visibilityFilter: (DeclarationDescriptor) -> Boolean @@ -73,36 +72,36 @@ public class KotlinIndicesHelper( } public fun getTopLevelCallables(nameFilter: (String) -> Boolean): Collection<CallableDescriptor> { - return (JetTopLevelFunctionFqnNameIndex.getInstance().getAllKeys(project).sequence() + - JetTopLevelPropertyFqnNameIndex.getInstance().getAllKeys(project).sequence()) + return (JetTopLevelFunctionFqnNameIndex.getInstance().getAllKeys(project).asSequence() + + JetTopLevelPropertyFqnNameIndex.getInstance().getAllKeys(project).asSequence()) .map { FqName(it) } .filter { nameFilter(it.shortName().asString()) } .toSet() .flatMap { findTopLevelCallables(it).filter(visibilityFilter) } } - public fun getCallableTopLevelExtensions(nameFilter: (String) -> Boolean, expression: JetSimpleNameExpression): Collection<CallableDescriptor> { - val receiverValues = receiverValues(expression) + public fun getCallableTopLevelExtensions(nameFilter: (String) -> Boolean, expression: JetSimpleNameExpression, bindingContext: BindingContext): Collection<CallableDescriptor> { + val receiverValues = receiverValues(expression, bindingContext) if (receiverValues.isEmpty()) return emptyList() val dataFlowInfo = bindingContext.getDataFlowInfo(expression) - val receiverTypeNames = possibleReceiverTypeNames(receiverValues.map { it.first }, dataFlowInfo) + val receiverTypeNames = possibleReceiverTypeNames(receiverValues.map { it.first }, dataFlowInfo, bindingContext) val index = JetTopLevelExtensionsByReceiverTypeIndex.INSTANCE val declarations = index.getAllKeys(project) - .sequence() + .asSequence() .filter { JetTopLevelExtensionsByReceiverTypeIndex.receiverTypeNameFromKey(it) in receiverTypeNames && nameFilter(JetTopLevelExtensionsByReceiverTypeIndex.callableNameFromKey(it)) } - .flatMap { index.get(it, project, scope).sequence() } + .flatMap { index.get(it, project, scope).asSequence() } return findSuitableExtensions(declarations, receiverValues, dataFlowInfo, bindingContext) } - private fun possibleReceiverTypeNames(receiverValues: Collection<ReceiverValue>, dataFlowInfo: DataFlowInfo): Set<String> { + private fun possibleReceiverTypeNames(receiverValues: Collection<ReceiverValue>, dataFlowInfo: DataFlowInfo, bindingContext: BindingContext): Set<String> { val result = HashSet<String>() for (receiverValue in receiverValues) { for (type in SmartCastUtils.getSmartCastVariants(receiverValue, bindingContext, moduleDescriptor, dataFlowInfo)) { @@ -118,7 +117,7 @@ public class KotlinIndicesHelper( constructor.getSupertypes().forEach { addTypeNames(it) } } - private fun receiverValues(expression: JetSimpleNameExpression): Collection<Pair<ReceiverValue, CallType>> { + private fun receiverValues(expression: JetSimpleNameExpression, bindingContext: BindingContext): Collection<Pair<ReceiverValue, CallType>> { val receiverPair = ReferenceVariantsHelper.getExplicitReceiverData(expression) if (receiverPair != null) { val (receiverExpression, callType) = receiverPair @@ -173,7 +172,7 @@ public class KotlinIndicesHelper( } public fun getClassDescriptors(nameFilter: (String) -> Boolean, kindFilter: (ClassKind) -> Boolean): Collection<ClassDescriptor> { - return JetFullClassNameIndex.getInstance().getAllKeys(project).sequence() + return JetFullClassNameIndex.getInstance().getAllKeys(project).asSequence() .map { FqName(it) } .filter { nameFilter(it.shortName().asString()) } .toList() diff --git a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/refactoring/JetNameSuggester.java b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/refactoring/JetNameSuggester.java index cbdc3957abcad..66acdc5e5eccb 100644 --- a/idea/idea-core/src/org/jetbrains/kotlin/idea/core/refactoring/JetNameSuggester.java +++ b/idea/idea-core/src/org/jetbrains/kotlin/idea/core/refactoring/JetNameSuggester.java @@ -37,6 +37,7 @@ import org.jetbrains.kotlin.types.checker.JetTypeChecker; import java.util.ArrayList; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -198,6 +199,12 @@ private static void addForClassType(ArrayList<String> result, JetType jetType, J private static final String[] ACCESSOR_PREFIXES = { "get", "is", "set" }; + public static List<String> getCamelNames(String name, JetNameValidator validator) { + ArrayList<String> result = new ArrayList<String>(); + addCamelNames(result, name, validator); + return result; + } + private static void addCamelNames(ArrayList<String> result, String name, JetNameValidator validator) { if (name == "") return; String s = deleteNonLetterFromString(name); diff --git a/idea/src/org/jetbrains/kotlin/idea/quickfix/AutoImportFix.kt b/idea/src/org/jetbrains/kotlin/idea/quickfix/AutoImportFix.kt index c528b5863ca32..d9ae0e1215a25 100644 --- a/idea/src/org/jetbrains/kotlin/idea/quickfix/AutoImportFix.kt +++ b/idea/src/org/jetbrains/kotlin/idea/quickfix/AutoImportFix.kt @@ -138,7 +138,7 @@ public class AutoImportFix(element: JetSimpleNameExpression) : JetHintAction<Jet val result = ArrayList<DeclarationDescriptor>() val moduleDescriptor = resolutionFacade.findModuleDescriptor(element) - val indicesHelper = KotlinIndicesHelper(file.getProject(), resolutionFacade, bindingContext, searchScope, moduleDescriptor, ::isVisible) + val indicesHelper = KotlinIndicesHelper(file.getProject(), resolutionFacade, searchScope, moduleDescriptor, ::isVisible) if (!element.isImportDirectiveExpression() && !JetPsiUtil.isSelectorInQualified(element)) { if (ProjectStructureUtil.isJsKotlinModule(file)) { @@ -150,7 +150,7 @@ public class AutoImportFix(element: JetSimpleNameExpression) : JetHintAction<Jet result.addAll(indicesHelper.getTopLevelCallablesByName(referenceName)) } - result.addAll(indicesHelper.getCallableTopLevelExtensions({ it == referenceName }, element)) + result.addAll(indicesHelper.getCallableTopLevelExtensions({ it == referenceName }, element, bindingContext)) return result }
8d62686d2a5e00f381a2b333b05c4fd70bf8ffb4
Mylyn Reviews
322734: changed labels, border for rating comment
a
https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews
diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java index a91c237a..8c035606 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPart.java @@ -92,6 +92,7 @@ public void createControl(Composite parent, FormToolkit toolkit) { composite.setLayout(new GridLayout(1, true)); fileList = new TableViewer(composite); + fileList.getControl().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true)); @@ -247,7 +248,7 @@ private void createResultFields(Composite composite, FormToolkit toolkit) { false)); resultComposite.setLayout(new GridLayout(2, false)); - toolkit.createLabel(resultComposite, "Rating").setForeground( + toolkit.createLabel(resultComposite, "Rating:").setForeground( toolkit.getColors().getColor(IFormColors.TITLE)); CCombo ratingsCombo = new CCombo(resultComposite, SWT.READ_ONLY | SWT.FLAT); @@ -285,10 +286,10 @@ public Image getImage(Object element) { ratingList.getControl().setLayoutData( new GridData(SWT.LEFT, SWT.TOP, false, false)); - toolkit.createLabel(resultComposite, "Review comment").setForeground( + toolkit.createLabel(resultComposite, "Rating comment:").setForeground( toolkit.getColors().getColor(IFormColors.TITLE)); - final Text commentText = toolkit.createText(resultComposite, "", - SWT.BORDER | SWT.MULTI); + final Text commentText = toolkit.createText(resultComposite, "", SWT.MULTI); + GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); gd.heightHint = 100; commentText.setLayoutData(gd); diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java index 325c5ad9..2e4b4ddb 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/ReviewTaskEditorPartAdvisor.java @@ -79,7 +79,7 @@ public Set<TaskEditorPartDescriptor> getPartContributions(ITask task) { public AbstractTaskEditorPart createPart() { return new ReviewTaskEditorPart(); } - }); + }.setPath(AbstractTaskEditorPage.PATH_ATTRIBUTES)); return parts; } diff --git a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties index f1d4e050..7eb450b0 100644 --- a/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties +++ b/org.eclipse.mylyn.reviews.ui/src/org/eclipse/mylyn/reviews/ui/editors/messages.properties @@ -28,11 +28,11 @@ ReviewEditor_Rating=Rating ReviewEditor_Review=Review ReviewEditor_Submit=Submit ReviewSummaryTaskEditorPart_Header_Author=Author -ReviewSummaryTaskEditorPart_Header_Comment=Comment +ReviewSummaryTaskEditorPart_Header_Comment=Rating Comment ReviewSummaryTaskEditorPart_Header_Scope=Scope -ReviewSummaryTaskEditorPart_Header_Result=Result +ReviewSummaryTaskEditorPart_Header_Result=Rating ReviewSummaryTaskEditorPart_Header_Reviewer=Reviewer -ReviewSummaryTaskEditorPart_Header_ReviewId=Review Id +ReviewSummaryTaskEditorPart_Header_ReviewId=Review Task ReviewSummaryTaskEditorPart_Partname=Review Summary ReviewTaskEditorInput_New_Review=New Review TaskEditorPatchReviewPart_Diff=Differences
1934528d3485b8670a9f74ff84c06819cad2a94c
griddynamics$jagger
functionality is ready, docu is left
p
https://github.com/griddynamics/jagger
diff --git a/chassis/configuration/configuration/reporter/session.comparison.conf.xml b/chassis/configuration/configuration/reporter/session.comparison.conf.xml index 9fb82c8da..972b0cb52 100644 --- a/chassis/configuration/configuration/reporter/session.comparison.conf.xml +++ b/chassis/configuration/configuration/reporter/session.comparison.conf.xml @@ -31,6 +31,7 @@ class="com.griddynamics.jagger.engine.e1.sessioncomparation.ConfigurableSessionComparator"> <property name="comparatorChain"> + <!--??? check if we still need it--> <ref bean="comparators_${chassis.engine.e1.reporting.session.comparison.monitoring.active}"/> </property> <property name="decisionMaker" ref="worstCaseDecisionMaker"/> @@ -71,6 +72,11 @@ <property name="sessionIdProvider" ref="sessionIdProvider"/> </bean> + <bean id="limitSetConfig" class="com.griddynamics.jagger.engine.e1.collector.limits.LimitSetConfig"> + <!--??? env properties --> + <property name="decisionWhenNoMetricForLimit" value="OK"/> + <property name="decisionWhenNoBaselineForMetric" value="FATAL"/> + </bean> <!-- Monitoring --> diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/BasicTGDecisionMakerListener.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/BasicTGDecisionMakerListener.java index 0b9089809..a84ae4320 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/BasicTGDecisionMakerListener.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/BasicTGDecisionMakerListener.java @@ -1,11 +1,20 @@ package com.griddynamics.jagger.engine.e1; +import com.griddynamics.jagger.engine.e1.collector.limits.DecisionPerTest; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerInfo; import com.griddynamics.jagger.engine.e1.services.ServicesAware; -import com.griddynamics.jagger.engine.e1.sessioncomparation.DecisionMakerInfo; -import com.griddynamics.jagger.engine.e1.sessioncomparation.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; +import com.griddynamics.jagger.engine.e1.sessioncomparation.WorstCaseDecisionMaker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + +//??? docu public class BasicTGDecisionMakerListener extends ServicesAware implements Provider<TestGroupDecisionMakerListener> { - //???private static final Logger log = LoggerFactory.getLogger(BasicTGDecisionMakerListener.class); + private static final Logger log = LoggerFactory.getLogger(BasicTGDecisionMakerListener.class); @Override protected void init() { @@ -16,10 +25,20 @@ protected void init() { public TestGroupDecisionMakerListener provide() { return new TestGroupDecisionMakerListener() { @Override - public void onDecisionMaking(DecisionMakerInfo decisionMakerInfo) { - //??? - System.out.println(BasicTGDecisionMakerListener.class); + public Decision onDecisionMaking(TestGroupDecisionMakerInfo decisionMakerInfo) { + Decision decisionPerTestGroup; + WorstCaseDecisionMaker worstCaseDecisionMaker = new WorstCaseDecisionMaker(); + List<Decision> decisions = new ArrayList<Decision>(); + + for (DecisionPerTest decisionPerTest : decisionMakerInfo.getDecisionsPerTest()) { + decisions.add(decisionPerTest.getDecisionPerTest()); + } + + decisionPerTestGroup = worstCaseDecisionMaker.getDecision(decisions); + + log.info("Decision for test group {} - {}",decisionMakerInfo.getTestGroup().getTaskName(),decisionPerTestGroup); + return decisionPerTestGroup; } }; } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerLimit.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerLimit.java new file mode 100644 index 000000000..eeb8ba6ba --- /dev/null +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerLimit.java @@ -0,0 +1,40 @@ +package com.griddynamics.jagger.engine.e1.collector.limits; + +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; + +import java.util.Set; + +//??? docu +public class DecisionPerLimit { + private Limit limit; + private Set<DecisionPerMetric> decisionsPerMetric; + private Decision decisionPerLimit; + + public DecisionPerLimit(Limit limit, Set<DecisionPerMetric> decisionsPerMetric, Decision decisionPerLimit) { + this.limit = limit; + this.decisionsPerMetric = decisionsPerMetric; + this.decisionPerLimit = decisionPerLimit; + } + + public Limit getLimit() { + return limit; + } + + public Set<DecisionPerMetric> getDecisionsPerMetric() { + return decisionsPerMetric; + } + + public Decision getDecisionPerLimit() { + return decisionPerLimit; + } + + @Override + public String toString() { + return "DecisionPerLimit{" + + "\n limit=" + limit + + "\n decisionsPerMetric=" + decisionsPerMetric + + "\n decisionPerLimit=" + decisionPerLimit + + '}'; + } + +} diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerMetric.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerMetric.java new file mode 100644 index 000000000..a3b78fe96 --- /dev/null +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerMetric.java @@ -0,0 +1,45 @@ +package com.griddynamics.jagger.engine.e1.collector.limits; + +import com.griddynamics.jagger.engine.e1.services.data.service.MetricEntity; +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; + +//??? docu +public class DecisionPerMetric { + private MetricEntity metricEntity; + private Double metricValue; + private Double metricRefValue; + private Decision decisionPerMetric; + + public DecisionPerMetric(MetricEntity metricEntity, Double metricValue, Double metricRefValue, Decision decisionPerMetric) { + this.metricEntity = metricEntity; + this.metricValue = metricValue; + this.metricRefValue = metricRefValue; + this.decisionPerMetric = decisionPerMetric; + } + + public MetricEntity getMetricEntity() { + return metricEntity; + } + + public Double getMetricValue() { + return metricValue; + } + + public Double getMetricRefValue() { + return metricRefValue; + } + + public Decision getDecisionPerMetric() { + return decisionPerMetric; + } + + @Override + public String toString() { + return "DecisionPerMetric{" + + "metricId=" + metricEntity.getMetricId() + + ", metricValue=" + metricValue + + ", metricRefValue=" + metricRefValue + + ", decisionPerMetric=" + decisionPerMetric + + '}'; + } +} \ No newline at end of file diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerTest.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerTest.java new file mode 100644 index 000000000..edf0e6ac2 --- /dev/null +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/DecisionPerTest.java @@ -0,0 +1,38 @@ +package com.griddynamics.jagger.engine.e1.collector.limits; + +import com.griddynamics.jagger.engine.e1.services.data.service.TestEntity; +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; + +import java.util.Set; + +public class DecisionPerTest { + private TestEntity testEntity; + private Set<DecisionPerLimit> decisionsPerLimit; + private Decision decisionPerTest; + + public DecisionPerTest(TestEntity testEntity, Set<DecisionPerLimit> decisionsPerLimit, Decision decisionPerTest) { + this.testEntity = testEntity; + this.decisionsPerLimit = decisionsPerLimit; + this.decisionPerTest = decisionPerTest; + } + + public TestEntity getTestEntity() { + return testEntity; + } + + public Set<DecisionPerLimit> getDecisionsPerLimit() { + return decisionsPerLimit; + } + + public Decision getDecisionPerTest() { + return decisionPerTest; + } + + @Override + public String toString() { + return "DecisionPerTest{" + + "testName=" + testEntity.getName() + + ", decisionPerTest=" + decisionPerTest + + '}'; + } +} \ No newline at end of file diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/Limit.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/Limit.java index 2476d61f6..04aadb64d 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/Limit.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/Limit.java @@ -20,13 +20,11 @@ package com.griddynamics.jagger.engine.e1.collector.limits; -//??? strict or relaxed - - /** Class is used to describe individual limits for some metric. Limits are used for decision making * * @details - * Metric comparison will be provided by ??? decision maker @n + * Metric comparison will be provided by @ref BasicTGDecisionMakerListener decision maker or @n + * by custom implementation of @ref TestGroupDecisionMakerListener @n * Metric value will be compared with some reference: ref, where ref is: @n * @li value from baseline when refValue = null @n * @li refValue in all other cases @n diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSet.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSet.java index 3989617b1..d1e73d985 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSet.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSet.java @@ -20,6 +20,7 @@ package com.griddynamics.jagger.engine.e1.collector.limits; +import com.griddynamics.jagger.engine.e1.sessioncomparation.BaselineSessionProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,7 +31,8 @@ public class LimitSet { private List<Limit> limits = Collections.emptyList(); private String id; - //??? set baseline sessionId here + private BaselineSessionProvider baselineSessionProvider; + private LimitSetConfig limitSetConfig; public void setLimits(List<Limit> limits) { @@ -52,6 +54,24 @@ public void setId(String id) { this.id = id; } + public String getBaselineId() { + return baselineSessionProvider.getBaselineSession(); + } + + public void setBaselineSessionProvider(BaselineSessionProvider baselineSessionProvider) { + this.baselineSessionProvider = baselineSessionProvider; + } + + public LimitSetConfig getLimitSetConfig() { + return limitSetConfig; + } + + public void setLimitSetConfig(LimitSetConfig limitSetConfig) { + this.limitSetConfig = limitSetConfig; + } + + // relation single metric - single limit is important + // due to storage in database and displaying in UI private void removeDuplicates(List<Limit> inputList) { Set<String> params = new HashSet<String>(); String param; diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSetConfig.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSetConfig.java new file mode 100644 index 000000000..7497393fb --- /dev/null +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/limits/LimitSetConfig.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2010-2012 Grid Dynamics Consulting Services, Inc, All Rights Reserved + * http://www.griddynamics.com + * + * This library is free software; you can redistribute it and/or modify it under the terms of + * the GNU Lesser General Public License as published by the Free Software Foundation; either + * version 2.1 of the License, or any later version. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.griddynamics.jagger.engine.e1.collector.limits; + +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; + +//??? docu +public class LimitSetConfig { + private Decision decisionWhenNoMetricForLimit; + private Decision decisionWhenNoBaselineForMetric; + + public Decision getDecisionWhenNoMetricForLimit() { + return decisionWhenNoMetricForLimit; + } + + public void setDecisionWhenNoMetricForLimit(Decision decisionWhenNoMetricForLimit) { + this.decisionWhenNoMetricForLimit = decisionWhenNoMetricForLimit; + } + + public Decision getDecisionWhenNoBaselineForMetric() { + return decisionWhenNoBaselineForMetric; + } + + public void setDecisionWhenNoBaselineForMetric(Decision decisionWhenNoBaselineForMetric) { + this.decisionWhenNoBaselineForMetric = decisionWhenNoBaselineForMetric; + } +} + diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/testgroup/TestGroupDecisionMakerInfo.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/testgroup/TestGroupDecisionMakerInfo.java new file mode 100644 index 000000000..656022692 --- /dev/null +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/testgroup/TestGroupDecisionMakerInfo.java @@ -0,0 +1,53 @@ +package com.griddynamics.jagger.engine.e1.collector.testgroup; + +import com.griddynamics.jagger.engine.e1.collector.limits.DecisionPerTest; +import com.griddynamics.jagger.master.CompositeTask; + +import java.util.Set; + +/** Class, which contains information for decision making + * @author Novozhilov Mark + * @n + * @par Details: + * @details + * @n + * */ + + //??? docu +public class TestGroupDecisionMakerInfo { + private CompositeTask testGroup; + private String sessionId; + private Set<DecisionPerTest> decisionsPerTest; + + public TestGroupDecisionMakerInfo(CompositeTask testGroup, String sessionId, Set<DecisionPerTest> decisionsPerTest) { + this.testGroup = testGroup; + this.sessionId = sessionId; + this.decisionsPerTest = decisionsPerTest; + } + + public CompositeTask getTestGroup() { + return testGroup; + } + + public void setTestGroup(CompositeTask testGroup) { + this.testGroup = testGroup; + } + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public Set<DecisionPerTest> getDecisionsPerTest() { + return decisionsPerTest; + } + + public void setDecisionsPerTest(Set<DecisionPerTest> decisionsPerTest) { + this.decisionsPerTest = decisionsPerTest; + } + + +} diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/TestGroupDecisionMakerListener.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/testgroup/TestGroupDecisionMakerListener.java similarity index 66% rename from chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/TestGroupDecisionMakerListener.java rename to chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/testgroup/TestGroupDecisionMakerListener.java index a28b85410..cd09d9f28 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/TestGroupDecisionMakerListener.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/collector/testgroup/TestGroupDecisionMakerListener.java @@ -1,8 +1,11 @@ -package com.griddynamics.jagger.engine.e1.sessioncomparation; +package com.griddynamics.jagger.engine.e1.collector.testgroup; +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; +import com.griddynamics.jagger.engine.e1.sessioncomparation.WorstCaseDecisionMaker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; import java.util.List; /** Listener, executed on decision-making for a test-group @@ -17,7 +20,7 @@ public interface TestGroupDecisionMakerListener { /** Executes after test-group information aggregates in the database. * @param decisionMakerInfo - describes test-group information */ - void onDecisionMaking(DecisionMakerInfo decisionMakerInfo); + Decision onDecisionMaking(TestGroupDecisionMakerInfo decisionMakerInfo); /** Class is used by Jagger for sequential execution of several listeners @n * Not required for custom test-group decision maker listeners */ @@ -31,14 +34,21 @@ private Composer(List<TestGroupDecisionMakerListener> listenerList){ } @Override - public void onDecisionMaking(DecisionMakerInfo decisionMakerInfo) { + public Decision onDecisionMaking(TestGroupDecisionMakerInfo decisionMakerInfo) { + List<Decision> decisions = new ArrayList<Decision>(); + + //??? configurable + WorstCaseDecisionMaker worstCaseDecisionMaker = new WorstCaseDecisionMaker(); + for (TestGroupDecisionMakerListener listener : listenerList){ try{ - listener.onDecisionMaking(decisionMakerInfo); + decisions.add(listener.onDecisionMaking(decisionMakerInfo)); }catch (RuntimeException ex){ log.error("Failed to call on decision making in {} test-group-decision-maker-listener", listener.toString(), ex); } } + + return worstCaseDecisionMaker.getDecision(decisions); } public static TestGroupDecisionMakerListener compose(List<TestGroupDecisionMakerListener> listeners){ return new Composer(listeners); diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/DecisionMakerInfo.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/DecisionMakerInfo.java deleted file mode 100644 index 58828fc09..000000000 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/DecisionMakerInfo.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.griddynamics.jagger.engine.e1.sessioncomparation; - -import com.griddynamics.jagger.engine.e1.scenario.WorkloadTask; - -import java.util.List; - -/** Class, which contains information for decision making - * @author Novozhilov Mark - * @n - * @par Details: - * @details - * @n - * */ - - public class DecisionMakerInfo { - - public List<WorkloadTask> getTasks() { - return tasks; - } - - public void setTasks(List<WorkloadTask> tasks) { - this.tasks = tasks; - } - - //??? temp - List<WorkloadTask> tasks; - - - public String getSessionId() { - return sessionId; - } - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - //??? - String sessionId; - - - //TODO add implementation - - //??? should contain - // session Id - // test names or ids - } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/WorstCaseDecisionMaker.java b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/WorstCaseDecisionMaker.java index 70e1280e6..55aae6702 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/WorstCaseDecisionMaker.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/engine/e1/sessioncomparation/WorstCaseDecisionMaker.java @@ -22,6 +22,8 @@ import com.google.common.collect.Multimap; +import java.util.List; + /** Returns the worst decision of comparisons * @author Dmitry Kotlyarov * @n @@ -52,4 +54,18 @@ public Decision makeDecision(Multimap<String, Verdict> verdicts) { return worstResult; } + //??? docu + + //??? can be part of separate interface + public Decision getDecision(List<Decision> decisions) { + Decision worstCaseDecision = Decision.OK; + + for (Decision decision : decisions) { + if (decision.ordinal() > worstCaseDecision.ordinal()) { + worstCaseDecision = decision; + } + } + + return worstCaseDecision; + } } diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/master/CompositeTask.java b/chassis/core/src/main/java/com/griddynamics/jagger/master/CompositeTask.java index 93b1a124d..e1a301351 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/master/CompositeTask.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/master/CompositeTask.java @@ -23,7 +23,7 @@ import com.google.common.collect.ImmutableList; import com.griddynamics.jagger.engine.e1.Provider; import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupListener; -import com.griddynamics.jagger.engine.e1.sessioncomparation.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerListener; import com.griddynamics.jagger.master.configuration.Task; import java.util.List; diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java b/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java index 3fd1be7cf..0ad294005 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/master/DecisionMakerDistributionListener.java @@ -2,32 +2,32 @@ import com.griddynamics.jagger.coordinator.NodeContext; import com.griddynamics.jagger.coordinator.NodeId; -import com.griddynamics.jagger.dbapi.DatabaseService; import com.griddynamics.jagger.engine.e1.ProviderUtil; +import com.griddynamics.jagger.engine.e1.collector.limits.*; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerInfo; import com.griddynamics.jagger.engine.e1.scenario.WorkloadTask; import com.griddynamics.jagger.engine.e1.services.DataService; import com.griddynamics.jagger.engine.e1.services.DefaultDataService; import com.griddynamics.jagger.engine.e1.services.JaggerPlace; -import com.griddynamics.jagger.engine.e1.sessioncomparation.DecisionMakerInfo; -import com.griddynamics.jagger.engine.e1.sessioncomparation.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.services.data.service.MetricEntity; +import com.griddynamics.jagger.engine.e1.services.data.service.TestEntity; +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.sessioncomparation.WorstCaseDecisionMaker; import com.griddynamics.jagger.master.configuration.Task; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.*; -/** - * Created with IntelliJ IDEA. - * User: mnovozhilov - * Date: 2/7/14 - * Time: 3:03 PM - * To change this template use File | Settings | File Templates. - */ public class DecisionMakerDistributionListener implements DistributionListener { + private static final Logger log = LoggerFactory.getLogger(DecisionMakerDistributionListener.class); + private NodeContext nodeContext; - private DatabaseService databaseService; + private WorstCaseDecisionMaker worstCaseDecisionMaker = new WorstCaseDecisionMaker(); - public DecisionMakerDistributionListener(NodeContext nodeContext, DatabaseService databaseService) { + public DecisionMakerDistributionListener(NodeContext nodeContext) { this.nodeContext = nodeContext; - this.databaseService = databaseService; } @Override @@ -45,40 +45,237 @@ public void onTaskDistributionCompleted(String sessionId, String taskId, Task ta nodeContext, JaggerPlace.TEST_GROUP_DECISION_MAKER_LISTENER)); + DataService dataService = new DefaultDataService(nodeContext); + + // Get tests in test group CompositeTask compositeTask = (CompositeTask) task; - List<WorkloadTask> children = new ArrayList<WorkloadTask>(); + List<WorkloadTask> workloadTasks = new ArrayList<WorkloadTask>(); for (CompositableTask compositableTask : compositeTask.getAttendant()) { if (compositableTask instanceof WorkloadTask) { - children.add((WorkloadTask)compositableTask); + workloadTasks.add((WorkloadTask) compositableTask); } } for (CompositableTask compositableTask : compositeTask.getLeading()) { if (compositableTask instanceof WorkloadTask) { - children.add((WorkloadTask)compositableTask); + workloadTasks.add((WorkloadTask) compositableTask); } } - DataService dataService = new DefaultDataService(nodeContext); - for (CompositableTask workloadTask : children) { - //??? + // Make decision per tests + Set<DecisionPerTest> decisionsPerTest = new HashSet<DecisionPerTest>(); + + for (WorkloadTask workloadTask : workloadTasks) { + if (workloadTask.getLimits() != null) { + String testName = workloadTask.getName(); + + // Get data for current session + TestEntity testEntity = dataService.getTestByName(sessionId,testName); + Set<MetricEntity> metricEntitySet = dataService.getMetrics(testEntity); + Map<MetricEntity,Double> metricValues = dataService.getMetricSummary(metricEntitySet); + + Map<String,MetricEntity> idToEntity = new HashMap<String, MetricEntity>(); + for (MetricEntity metricEntity : metricValues.keySet()) { + idToEntity.put(metricEntity.getMetricId(),metricEntity); + } + + // Get relation limit <-> metrics + boolean needBaselineSessionValue = false; + Map<Limit,Set<MetricEntity>> limitToEntity = new HashMap<Limit, Set<MetricEntity>>(); + for (Limit limit : workloadTask.getLimits().getLimits()) { + limitToEntity.put(limit,getMetricsForLimit(limit, idToEntity)); + if (!limitToEntity.get(limit).isEmpty()) { + if (limit.getRefValue() == null) { + needBaselineSessionValue = true; + } + } + } + + // Get data for baseline session + //??? check that sessions match or not + Map<String,Double> metricIdToValuesBaseline = new HashMap<String, Double>(); + if (needBaselineSessionValue) { + String baselineId = workloadTask.getLimits().getBaselineId(); + TestEntity testEntityBaseline = dataService.getTestByName(baselineId, testName); + if (testEntityBaseline != null) { + Set<MetricEntity> metricEntitySetBaseline = dataService.getMetrics(testEntityBaseline); + Map<MetricEntity,Double> metricValuesBaseline = dataService.getMetricSummary(metricEntitySetBaseline); + for (Map.Entry<MetricEntity,Double> entry : metricValuesBaseline.entrySet()) { + metricIdToValuesBaseline.put(entry.getKey().getMetricId(),entry.getValue()); + } + } + else { + log.error("Was not able to find test {} in baseline session {}",testName,baselineId); + } + } + + log.info("Making decision for test: {} (baseline session: {})",testName,sessionId); + + // Compare + Set<DecisionPerLimit> decisionsPerLimit = new HashSet<DecisionPerLimit>(); + for (Limit limit : workloadTask.getLimits().getLimits()) { + DecisionPerLimit decisionPerLimit = compareMetricsToLimit(limit,limitToEntity.get(limit), + metricValues,metricIdToValuesBaseline, + workloadTask.getLimits().getLimitSetConfig()); + + log.debug(decisionPerLimit.toString()); + + decisionsPerLimit.add(decisionPerLimit); + } + + // decisionPetTest = worst case decisionPerLimit + Decision decisionPerTest; + List<Decision> decisions = new ArrayList<Decision>(); + for (DecisionPerLimit decisionPerLimit : decisionsPerLimit) { + decisions.add(decisionPerLimit.getDecisionPerLimit()); + } + decisionPerTest = worstCaseDecisionMaker.getDecision(decisions); + + DecisionPerTest resultForTest = new DecisionPerTest(testEntity, decisionsPerLimit, decisionPerTest); + log.info(resultForTest.toString()); + + decisionsPerTest.add(resultForTest); + } + } + + // call test group listener + TestGroupDecisionMakerInfo testGroupDecisionMakerInfo = + new TestGroupDecisionMakerInfo((CompositeTask)task,sessionId,decisionsPerTest); + Decision decisionPerTestGroup = decisionMakerListener.onDecisionMaking(testGroupDecisionMakerInfo); + + //??? log final decision + + //??? save decision + } + } + + + private Set<MetricEntity> getMetricsForLimit(Limit limit, Map<String, MetricEntity> idToEntity) { + String metricId = limit.getMetricName(); + Set<MetricEntity> metricsForLimit = new HashSet<MetricEntity>(); + + // Strict matching + if (idToEntity.keySet().contains(metricId)) { + metricsForLimit.add(idToEntity.get(metricId)); + } + else { + // Matching to regex (f.e. agent name(s) or aggregator name(s) omitted) + String regex = "^" + metricId + ".*"; + for (String id : idToEntity.keySet()) { + if (id.matches(regex)) { + metricsForLimit.add(idToEntity.get(id)); + } } + } + + return metricsForLimit; + } + private DecisionPerLimit compareMetricsToLimit(Limit limit, Set<MetricEntity> metricsPerLimit, + Map<MetricEntity, Double> metricValues, + Map<String, Double> metricValuesBaseline, + LimitSetConfig limitSetConfig) { + Set<DecisionPerMetric> decisionsPerMetric = new HashSet<DecisionPerMetric>(); + for (MetricEntity metricEntity : metricsPerLimit) { + Double refValue = limit.getRefValue(); + Double value = metricValues.get(metricEntity); + Decision decision = Decision.OK; -// //??? -// RootNode rootNode = databaseService.getControlTreeForSessions(new HashSet<String>(Arrays.asList(sessionId))); -// SummaryNode summaryNode = rootNode.getSummaryNode(); -// -// + // if null - we are comparing to baseline + if (refValue == null) { + if (metricValuesBaseline.containsKey(metricEntity.getMetricId())) { + refValue = metricValuesBaseline.get(metricEntity.getMetricId()); + } + } + if (refValue == null) { + String errorText = "Reference value for comparison of metric vs baseline was not found. Metric: {},\n" + + "Decision per metric: {}"; + switch (limitSetConfig.getDecisionWhenNoBaselineForMetric()) { + case OK: + decision = Decision.OK; + log.info(errorText,metricEntity.toString(), decision); + break; + case WARNING: + decision = Decision.WARNING; + log.warn(errorText, metricEntity.toString(), decision); + break; + default: + decision = Decision.FATAL; + log.error(errorText, metricEntity.toString(), decision); + break; + } + } + else { + if ((refValue > 0.0) || (refValue.equals(0D))) { + if (value < limit.getLowerErrorThreshold()*refValue) { + decision = Decision.FATAL; + } + else if (value < limit.getLowerWarningThreshold()*refValue) { + decision = Decision.WARNING; + } + else if (value < limit.getUpperWarningThreshold()*refValue) { + decision = Decision.OK; + } + else if (value < limit.getUpperErrorThreshold()*refValue) { + decision = Decision.WARNING; + } + else { + decision = Decision.FATAL; + } + } + else { + if (value < limit.getUpperErrorThreshold()*refValue) { + decision = Decision.FATAL; + } + else if (value < limit.getUpperWarningThreshold()*refValue) { + decision = Decision.WARNING; + } + else if (value < limit.getLowerWarningThreshold()*refValue) { + decision = Decision.OK; + } + else if (value < limit.getLowerErrorThreshold()*refValue) { + decision = Decision.WARNING; + } + else { + decision = Decision.FATAL; + } + } + } - DecisionMakerInfo decisionMakerInfo = new DecisionMakerInfo(); - //??? - decisionMakerInfo.setTasks(children); - //??? - decisionMakerInfo.setSessionId(sessionId); + decisionsPerMetric.add(new DecisionPerMetric(metricEntity, value, refValue, decision)); + } - decisionMakerListener.onDecisionMaking(decisionMakerInfo); + // decisionPerLimit = worst case decisionPerLimit + Decision decisionPerLimit; + List<Decision> decisions = new ArrayList<Decision>(); + for (DecisionPerMetric decisionPerMetric : decisionsPerMetric) { + decisions.add(decisionPerMetric.getDecisionPerMetric()); + log.info(decisionPerMetric.toString()); } + if (decisions.isEmpty()) { + String errorText = "Limit doesn't have any matching metric in current session. Limit {},\n" + + "Decision per limit: {}"; + switch (limitSetConfig.getDecisionWhenNoMetricForLimit()) { + case OK: + decisionPerLimit = Decision.OK; + log.info(errorText,limit, decisionPerLimit); + break; + case WARNING: + decisionPerLimit = Decision.WARNING; + log.warn(errorText,limit, decisionPerLimit); + break; + default: + decisionPerLimit = Decision.FATAL; + log.error(errorText,limit, decisionPerLimit); + break; + } + } + else { + decisionPerLimit = worstCaseDecisionMaker.getDecision(decisions); + } + + return new DecisionPerLimit(limit,decisionsPerMetric,decisionPerLimit); } } + diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java b/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java index ea622e1a0..93948d3ad 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/master/Master.java @@ -180,7 +180,7 @@ public void run() { NodeContext context = contextBuilder.build(); // add additional listener to configuration - configuration.getDistributionListeners().add(new DecisionMakerDistributionListener(context,databaseService)); + configuration.getDistributionListeners().add(new DecisionMakerDistributionListener(context)); Map<NodeType, CountDownLatch> countDownLatchMap = Maps.newHashMap(); CountDownLatch agentCountDownLatch = new CountDownLatch( diff --git a/chassis/core/src/main/java/com/griddynamics/jagger/user/TestGroupConfiguration.java b/chassis/core/src/main/java/com/griddynamics/jagger/user/TestGroupConfiguration.java index def850673..e54ea62d3 100644 --- a/chassis/core/src/main/java/com/griddynamics/jagger/user/TestGroupConfiguration.java +++ b/chassis/core/src/main/java/com/griddynamics/jagger/user/TestGroupConfiguration.java @@ -2,7 +2,7 @@ import com.griddynamics.jagger.engine.e1.Provider; import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupListener; -import com.griddynamics.jagger.engine.e1.sessioncomparation.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerListener; import com.griddynamics.jagger.master.CompositableTask; import com.griddynamics.jagger.master.CompositeTask; import com.griddynamics.jagger.master.configuration.Task; diff --git a/chassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/limit/LimitSetDefinitionParser.java b/chassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/limit/LimitSetDefinitionParser.java index 353bab4f9..00bde0b07 100644 --- a/chassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/limit/LimitSetDefinitionParser.java +++ b/chassis/spring.schema/src/main/java/com/griddynamics/jagger/xml/beanParsers/limit/LimitSetDefinitionParser.java @@ -22,6 +22,10 @@ protected Class getBeanClass(Element element) { protected void parse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { List<Element> limits = DomUtils.getChildElementsByTagName(element, XMLConstants.LIMIT); builder.addPropertyValue(XMLConstants.LIMITS, parseCustomElements(limits, parserContext, builder.getBeanDefinition())); + // inject bean of baseline session provider + builder.addPropertyReference("baselineSessionProvider","baselineSessionProvider"); + // inject config bean + builder.addPropertyReference("limitSetConfig","limitSetConfig"); } @Override diff --git a/chassis/spring.schema/src/test/java/com/griddynamics/jagger/xml/stubs/xml/ExampleDecisionMakerListener.java b/chassis/spring.schema/src/test/java/com/griddynamics/jagger/xml/stubs/xml/ExampleDecisionMakerListener.java index 60c91586d..4a5650107 100644 --- a/chassis/spring.schema/src/test/java/com/griddynamics/jagger/xml/stubs/xml/ExampleDecisionMakerListener.java +++ b/chassis/spring.schema/src/test/java/com/griddynamics/jagger/xml/stubs/xml/ExampleDecisionMakerListener.java @@ -1,9 +1,10 @@ package com.griddynamics.jagger.xml.stubs.xml; import com.griddynamics.jagger.engine.e1.Provider; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerInfo; import com.griddynamics.jagger.engine.e1.services.ServicesAware; -import com.griddynamics.jagger.engine.e1.sessioncomparation.DecisionMakerInfo; -import com.griddynamics.jagger.engine.e1.sessioncomparation.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.collector.testgroup.TestGroupDecisionMakerListener; +import com.griddynamics.jagger.engine.e1.sessioncomparation.Decision; /** * Created with IntelliJ IDEA. @@ -21,8 +22,8 @@ public TestGroupDecisionMakerListener provide() { return new TestGroupDecisionMakerListener() { @Override - public void onDecisionMaking(DecisionMakerInfo decisionMakerInfo) { - + public Decision onDecisionMaking(TestGroupDecisionMakerInfo decisionMakerInfo) { + return Decision.OK; } }; diff --git a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java index 725f8a0c0..b86a183bf 100644 --- a/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java +++ b/dbapi/src/main/java/com/griddynamics/jagger/dbapi/DatabaseServiceImpl.java @@ -39,8 +39,6 @@ */ public class DatabaseServiceImpl implements DatabaseService { - //??? clean printing to screen !!! - private Logger log = LoggerFactory.getLogger(this.getClass()); private EntityManager entityManager;