diff options
author | Eike Stepper | 2012-01-14 10:27:01 +0000 |
---|---|---|
committer | Eike Stepper | 2012-01-14 10:27:01 +0000 |
commit | 0266166cb9ff9535c150250073ea1e57b42d2693 (patch) | |
tree | c006a3bc0ba1f6e1d8a2bc032eedc346f71eab0d /plugins/org.eclipse.net4j.util | |
parent | 7416443692cdda72d1f704ea4fc5ececcc669df7 (diff) | |
download | cdo-0266166cb9ff9535c150250073ea1e57b42d2693.tar.gz cdo-0266166cb9ff9535c150250073ea1e57b42d2693.tar.xz cdo-0266166cb9ff9535c150250073ea1e57b42d2693.zip |
Adjusted copyrights to 2012
Diffstat (limited to 'plugins/org.eclipse.net4j.util')
325 files changed, 32279 insertions, 32279 deletions
diff --git a/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs index aaef0ccba1..6726e7034a 100644 --- a/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs +++ b/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs @@ -1,120 +1,120 @@ -#Thu Feb 04 09:44:24 CET 2010 -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_missing_override_annotations_interface_methods=true -cleanup.add_serial_version_id=true -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.correct_indentation=true -cleanup.format_source_code=true -cleanup.format_source_code_changes_only=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=false -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_trailing_whitespaces=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=false -cleanup.sort_members_all=false -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=true -cleanup.use_this_for_non_static_field_access=true -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=true -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=_EMFT -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_EMFT -formatter_settings_version=11 -org.eclipse.jdt.ui.exception.name=ex -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=org.eclipse.emf.cdo;org.eclipse.emf.internal.cdo;org.eclipse.net4j;org.eclipse.internal.net4j;org.eclipse.emf;org.eclipse;com;org;javax;java; -org.eclipse.jdt.ui.javadoc=true -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.ondemandthreshold=99 -org.eclipse.jdt.ui.overrideannotation=true -org.eclipse.jdt.ui.staticondemandthreshold=99 -org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="false" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment"/><template autoinsert\="false" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment"/><template autoinsert\="false" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment"/><template autoinsert\="false" 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 * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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 * Eike Stepper - initial API and implementation\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 Eike Stepper\r\n */</template><template autoinsert\="false" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment"/><template autoinsert\="false" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment"/><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\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment"/><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.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.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">${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">${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}</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></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_missing_override_annotations_interface_methods=false -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=false -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_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=false -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=false -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=true -sp_cleanup.remove_unused_imports=true -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=true -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true +#Thu Feb 04 09:44:24 CET 2010
+cleanup.add_default_serial_version_id=true
+cleanup.add_generated_serial_version_id=false
+cleanup.add_missing_annotations=true
+cleanup.add_missing_deprecated_annotations=true
+cleanup.add_missing_methods=false
+cleanup.add_missing_nls_tags=false
+cleanup.add_missing_override_annotations=true
+cleanup.add_missing_override_annotations_interface_methods=true
+cleanup.add_serial_version_id=true
+cleanup.always_use_blocks=true
+cleanup.always_use_parentheses_in_expressions=false
+cleanup.always_use_this_for_non_static_field_access=false
+cleanup.always_use_this_for_non_static_method_access=false
+cleanup.convert_to_enhanced_for_loop=false
+cleanup.correct_indentation=true
+cleanup.format_source_code=true
+cleanup.format_source_code_changes_only=false
+cleanup.make_local_variable_final=true
+cleanup.make_parameters_final=false
+cleanup.make_private_fields_final=true
+cleanup.make_type_abstract_if_missing_method=false
+cleanup.make_variable_declarations_final=false
+cleanup.never_use_blocks=false
+cleanup.never_use_parentheses_in_expressions=true
+cleanup.organize_imports=true
+cleanup.qualify_static_field_accesses_with_declaring_class=false
+cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
+cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
+cleanup.qualify_static_member_accesses_with_declaring_class=false
+cleanup.qualify_static_method_accesses_with_declaring_class=false
+cleanup.remove_private_constructors=true
+cleanup.remove_trailing_whitespaces=true
+cleanup.remove_trailing_whitespaces_all=true
+cleanup.remove_trailing_whitespaces_ignore_empty=false
+cleanup.remove_unnecessary_casts=true
+cleanup.remove_unnecessary_nls_tags=true
+cleanup.remove_unused_imports=true
+cleanup.remove_unused_local_variables=false
+cleanup.remove_unused_private_fields=true
+cleanup.remove_unused_private_members=false
+cleanup.remove_unused_private_methods=true
+cleanup.remove_unused_private_types=true
+cleanup.sort_members=false
+cleanup.sort_members_all=false
+cleanup.use_blocks=true
+cleanup.use_blocks_only_for_return_and_throw=false
+cleanup.use_parentheses_in_expressions=true
+cleanup.use_this_for_non_static_field_access=true
+cleanup.use_this_for_non_static_field_access_only_if_necessary=true
+cleanup.use_this_for_non_static_method_access=true
+cleanup.use_this_for_non_static_method_access_only_if_necessary=true
+cleanup_profile=_EMFT
+cleanup_settings_version=2
+eclipse.preferences.version=1
+editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
+formatter_profile=_EMFT
+formatter_settings_version=11
+org.eclipse.jdt.ui.exception.name=ex
+org.eclipse.jdt.ui.gettersetter.use.is=true
+org.eclipse.jdt.ui.ignorelowercasenames=true
+org.eclipse.jdt.ui.importorder=org.eclipse.emf.cdo;org.eclipse.emf.internal.cdo;org.eclipse.net4j;org.eclipse.internal.net4j;org.eclipse.emf;org.eclipse;com;org;javax;java;
+org.eclipse.jdt.ui.javadoc=true
+org.eclipse.jdt.ui.keywordthis=false
+org.eclipse.jdt.ui.ondemandthreshold=99
+org.eclipse.jdt.ui.overrideannotation=true
+org.eclipse.jdt.ui.staticondemandthreshold=99
+org.eclipse.jdt.ui.text.custom_code_templates=<?xml version\="1.0" encoding\="UTF-8" standalone\="no"?><templates><template autoinsert\="false" context\="gettercomment_context" deleted\="false" description\="Comment for getter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.gettercomment" name\="gettercomment"/><template autoinsert\="false" context\="settercomment_context" deleted\="false" description\="Comment for setter method" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.settercomment" name\="settercomment"/><template autoinsert\="false" context\="constructorcomment_context" deleted\="false" description\="Comment for created constructors" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.constructorcomment" name\="constructorcomment"/><template autoinsert\="false" 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 * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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 * Eike Stepper - initial API and implementation\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 Eike Stepper\r\n */</template><template autoinsert\="false" context\="fieldcomment_context" deleted\="false" description\="Comment for fields" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.fieldcomment" name\="fieldcomment"/><template autoinsert\="false" context\="methodcomment_context" deleted\="false" description\="Comment for non-overriding methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.methodcomment" name\="methodcomment"/><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\="delegatecomment_context" deleted\="false" description\="Comment for delegate methods" enabled\="true" id\="org.eclipse.jdt.ui.text.codetemplates.delegatecomment" name\="delegatecomment"/><template autoinsert\="true" context\="newtype_context" deleted\="false" description\="Newly created files" enabled\="true" id\="org.eclipse.jdt.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.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">${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">${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}</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></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_missing_override_annotations_interface_methods=false
+sp_cleanup.add_serial_version_id=false
+sp_cleanup.always_use_blocks=true
+sp_cleanup.always_use_parentheses_in_expressions=false
+sp_cleanup.always_use_this_for_non_static_field_access=false
+sp_cleanup.always_use_this_for_non_static_method_access=false
+sp_cleanup.convert_to_enhanced_for_loop=false
+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_type_abstract_if_missing_method=false
+sp_cleanup.make_variable_declarations_final=false
+sp_cleanup.never_use_blocks=false
+sp_cleanup.never_use_parentheses_in_expressions=true
+sp_cleanup.on_save_use_additional_actions=true
+sp_cleanup.organize_imports=true
+sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
+sp_cleanup.remove_private_constructors=true
+sp_cleanup.remove_trailing_whitespaces=true
+sp_cleanup.remove_trailing_whitespaces_all=true
+sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
+sp_cleanup.remove_unnecessary_casts=true
+sp_cleanup.remove_unnecessary_nls_tags=true
+sp_cleanup.remove_unused_imports=true
+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=true
+sp_cleanup.use_this_for_non_static_field_access=true
+sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
+sp_cleanup.use_this_for_non_static_method_access=true
+sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/plugins/org.eclipse.net4j.util/build.properties b/plugins/org.eclipse.net4j.util/build.properties index a888fd517c..dca3406b70 100644 --- a/plugins/org.eclipse.net4j.util/build.properties +++ b/plugins/org.eclipse.net4j.util/build.properties @@ -1,25 +1,25 @@ -# Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: -# Eike Stepper - initial API and implementation - -# NLS_MESSAGEFORMAT_VAR - -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - .options,\ - about.html,\ - copyright.txt,\ - plugin.properties,\ - plugin.xml,\ - schema/ -src.includes = about.html,\ - copyright.txt - -doc.project = org.eclipse.net4j.util.doc +# Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+# Eike Stepper - initial API and implementation
+
+# NLS_MESSAGEFORMAT_VAR
+
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ .options,\
+ about.html,\
+ copyright.txt,\
+ plugin.properties,\
+ plugin.xml,\
+ schema/
+src.includes = about.html,\
+ copyright.txt
+
+doc.project = org.eclipse.net4j.util.doc
diff --git a/plugins/org.eclipse.net4j.util/copyright.txt b/plugins/org.eclipse.net4j.util/copyright.txt index e921242cf0..8f6328980e 100644 --- a/plugins/org.eclipse.net4j.util/copyright.txt +++ b/plugins/org.eclipse.net4j.util/copyright.txt @@ -1,8 +1,8 @@ -Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: +Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
Eike Stepper - initial API and implementation
\ No newline at end of file diff --git a/plugins/org.eclipse.net4j.util/plugin.properties b/plugins/org.eclipse.net4j.util/plugin.properties index 53a57f2b9a..f250e4d207 100644 --- a/plugins/org.eclipse.net4j.util/plugin.properties +++ b/plugins/org.eclipse.net4j.util/plugin.properties @@ -1,14 +1,14 @@ -# Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: -# Eike Stepper - initial API and implementation - -pluginName = Net4j Utilities -providerName = Eclipse Modeling Project - -extension-point.name = Factories +# Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+# Eike Stepper - initial API and implementation
+
+pluginName = Net4j Utilities
+providerName = Eclipse Modeling Project
+
+extension-point.name = Factories
extension-point.name.0 = Element Processors
\ No newline at end of file diff --git a/plugins/org.eclipse.net4j.util/plugin.xml b/plugins/org.eclipse.net4j.util/plugin.xml index 6c151aa3b3..8bbd7636ba 100644 --- a/plugins/org.eclipse.net4j.util/plugin.xml +++ b/plugins/org.eclipse.net4j.util/plugin.xml @@ -1,39 +1,39 @@ -<?xml version="1.0" encoding="UTF-8"?> -<?eclipse version="3.4"?> -<!-- - Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - Eike Stepper - initial API and implementation ---> - -<plugin> - - <extension-point id="factories" name="%extension-point.name" schema="schema/factories.exsd"/> - <extension-point id="elementProcessors" name="%extension-point.name.0" schema="schema/elementProcessors.exsd"/> - - <extension - point="org.eclipse.net4j.util.factories"> - <factory - class="org.eclipse.net4j.util.concurrent.TimerLifecycle$DaemonFactory" - productGroup="org.eclipse.net4j.util.timers" - type="daemon"/> - <factory - class="org.eclipse.net4j.util.concurrent.ExecutorServiceFactory" - productGroup="org.eclipse.net4j.executorServices" - type="default"/> - <factory - productGroup="org.eclipse.net4j.randomizers" - type="default" - class="org.eclipse.net4j.util.security.RandomizerFactory"/> - <factory - productGroup="org.eclipse.net4j.userManagers" - type="file" - class="org.eclipse.net4j.util.security.FileUserManagerFactory"/> - </extension> - -</plugin> +<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.4"?>
+<!--
+ Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ Eike Stepper - initial API and implementation
+-->
+
+<plugin>
+
+ <extension-point id="factories" name="%extension-point.name" schema="schema/factories.exsd"/>
+ <extension-point id="elementProcessors" name="%extension-point.name.0" schema="schema/elementProcessors.exsd"/>
+
+ <extension
+ point="org.eclipse.net4j.util.factories">
+ <factory
+ class="org.eclipse.net4j.util.concurrent.TimerLifecycle$DaemonFactory"
+ productGroup="org.eclipse.net4j.util.timers"
+ type="daemon"/>
+ <factory
+ class="org.eclipse.net4j.util.concurrent.ExecutorServiceFactory"
+ productGroup="org.eclipse.net4j.executorServices"
+ type="default"/>
+ <factory
+ productGroup="org.eclipse.net4j.randomizers"
+ type="default"
+ class="org.eclipse.net4j.util.security.RandomizerFactory"/>
+ <factory
+ productGroup="org.eclipse.net4j.userManagers"
+ type="file"
+ class="org.eclipse.net4j.util.security.FileUserManagerFactory"/>
+ </extension>
+
+</plugin>
diff --git a/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd b/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd index b6ada0d28e..978f855009 100644 --- a/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd +++ b/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd @@ -1,106 +1,106 @@ -<?xml version='1.0' encoding='UTF-8'?> -<!-- Schema file written by PDE --> -<schema targetNamespace="org.eclipse.net4j.util"> -<annotation> - <appInfo> - <meta.schema plugin="org.eclipse.net4j.util" id="elementProcessors" name="Element Processors"/> - </appInfo> - <documentation> - [Enter description of this extension point.] - </documentation> - </annotation> - - <element name="extension"> - <complexType> - <sequence> - <element ref="elementProcessor" minOccurs="1" maxOccurs="unbounded"/> - </sequence> - <attribute name="point" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - </annotation> - </attribute> - <attribute name="id" type="string"> - <annotation> - <documentation> - - </documentation> - </annotation> - </attribute> - <attribute name="name" type="string"> - <annotation> - <documentation> - - </documentation> - <appInfo> - <meta.attribute translatable="true"/> - </appInfo> - </annotation> - </attribute> - </complexType> - </element> - - <element name="elementProcessor"> - <complexType> - <attribute name="class" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - <appInfo> - <meta.attribute kind="java"/> - </appInfo> - </annotation> - </attribute> - </complexType> - </element> - - <annotation> - <appInfo> - <meta.section type="since"/> - </appInfo> - <documentation> - [Enter the first release in which this extension point appears.] - </documentation> - </annotation> - - <annotation> - <appInfo> - <meta.section type="examples"/> - </appInfo> - <documentation> - [Enter extension point usage example here.] - </documentation> - </annotation> - - <annotation> - <appInfo> - <meta.section type="apiInfo"/> - </appInfo> - <documentation> - [Enter API information here.] - </documentation> - </annotation> - - <annotation> - <appInfo> - <meta.section type="implementation"/> - </appInfo> - <documentation> - [Enter information about supplied implementation of this extension point.] - </documentation> - </annotation> - - <annotation> - <appinfo> - <meta.section type="copyright"/> - </appinfo> - <documentation> - Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.<br> -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 <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> - </documentation> - </annotation> - -</schema> +<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.net4j.util">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.net4j.util" id="elementProcessors" name="Element Processors"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="elementProcessor" minOccurs="1" maxOccurs="unbounded"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute translatable="true"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="elementProcessor">
+ <complexType>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute kind="java"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.<br>
+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 <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.net4j.util/schema/factories.exsd b/plugins/org.eclipse.net4j.util/schema/factories.exsd index 5d4fe31ba2..d0ee9cfccc 100644 --- a/plugins/org.eclipse.net4j.util/schema/factories.exsd +++ b/plugins/org.eclipse.net4j.util/schema/factories.exsd @@ -1,125 +1,125 @@ -<?xml version='1.0' encoding='UTF-8'?> -<!-- Schema file written by PDE --> -<schema targetNamespace="org.eclipse.net4j.util"> -<annotation> - <appInfo> - <meta.schema plugin="org.eclipse.net4j.util" id="factories" name="Factories"/> - </appInfo> - <documentation> - [Enter description of this extension point.] - </documentation> - </annotation> - - <element name="extension"> - <complexType> - <sequence> - <element ref="factory" minOccurs="1" maxOccurs="unbounded"/> - </sequence> - <attribute name="point" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - </annotation> - </attribute> - <attribute name="id" type="string"> - <annotation> - <documentation> - - </documentation> - </annotation> - </attribute> - <attribute name="name" type="string"> - <annotation> - <documentation> - - </documentation> - <appInfo> - <meta.attribute translatable="true"/> - </appInfo> - </annotation> - </attribute> - </complexType> - </element> - - <element name="factory"> - <annotation> - <appInfo> - <meta.element labelAttribute="class"/> - </appInfo> - </annotation> - <complexType> - <attribute name="productGroup" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - </annotation> - </attribute> - <attribute name="type" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - </annotation> - </attribute> - <attribute name="class" type="string" use="required"> - <annotation> - <documentation> - - </documentation> - <appInfo> - <meta.attribute kind="java" basedOn="org.eclipse.net4j.util.factory.IFactory"/> - </appInfo> - </annotation> - </attribute> - </complexType> - </element> - - <annotation> - <appInfo> - <meta.section type="since"/> - </appInfo> - <documentation> - [Enter the first release in which this extension point appears.] - </documentation> - </annotation> - - <annotation> - <appInfo> - <meta.section type="examples"/> - </appInfo> - <documentation> - [Enter extension point usage example here.] - </documentation> - </annotation> - - <annotation> - <appInfo> - <meta.section type="apiInfo"/> - </appInfo> - <documentation> - [Enter API information here.] - </documentation> - </annotation> - - <annotation> - <appInfo> - <meta.section type="implementation"/> - </appInfo> - <documentation> - [Enter information about supplied implementation of this extension point.] - </documentation> - </annotation> - - <annotation> - <appinfo> - <meta.section type="copyright"/> - </appinfo> - <documentation> - Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.<br> -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 <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> - </documentation> - </annotation> - -</schema> +<?xml version='1.0' encoding='UTF-8'?>
+<!-- Schema file written by PDE -->
+<schema targetNamespace="org.eclipse.net4j.util">
+<annotation>
+ <appInfo>
+ <meta.schema plugin="org.eclipse.net4j.util" id="factories" name="Factories"/>
+ </appInfo>
+ <documentation>
+ [Enter description of this extension point.]
+ </documentation>
+ </annotation>
+
+ <element name="extension">
+ <complexType>
+ <sequence>
+ <element ref="factory" minOccurs="1" maxOccurs="unbounded"/>
+ </sequence>
+ <attribute name="point" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="id" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="name" type="string">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute translatable="true"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <element name="factory">
+ <annotation>
+ <appInfo>
+ <meta.element labelAttribute="class"/>
+ </appInfo>
+ </annotation>
+ <complexType>
+ <attribute name="productGroup" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="type" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ </annotation>
+ </attribute>
+ <attribute name="class" type="string" use="required">
+ <annotation>
+ <documentation>
+
+ </documentation>
+ <appInfo>
+ <meta.attribute kind="java" basedOn="org.eclipse.net4j.util.factory.IFactory"/>
+ </appInfo>
+ </annotation>
+ </attribute>
+ </complexType>
+ </element>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="since"/>
+ </appInfo>
+ <documentation>
+ [Enter the first release in which this extension point appears.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="examples"/>
+ </appInfo>
+ <documentation>
+ [Enter extension point usage example here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="apiInfo"/>
+ </appInfo>
+ <documentation>
+ [Enter API information here.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appInfo>
+ <meta.section type="implementation"/>
+ </appInfo>
+ <documentation>
+ [Enter information about supplied implementation of this extension point.]
+ </documentation>
+ </annotation>
+
+ <annotation>
+ <appinfo>
+ <meta.section type="copyright"/>
+ </appinfo>
+ <documentation>
+ Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.<br>
+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 <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a>
+ </documentation>
+ </annotation>
+
+</schema>
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java index a61c00f2be..d997a4969c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java @@ -1,456 +1,456 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.bundle; - -import org.eclipse.net4j.internal.util.om.pref.Preferences; -import org.eclipse.net4j.util.ReflectUtil; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.OMBundle; -import org.eclipse.net4j.util.om.OMPlatform; -import org.eclipse.net4j.util.om.log.Logger; -import org.eclipse.net4j.util.om.log.OMLogger; -import org.eclipse.net4j.util.om.trace.OMTracer; -import org.eclipse.net4j.util.om.trace.Tracer; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.text.MessageFormat; -import java.util.HashMap; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Eike Stepper - */ -public abstract class AbstractBundle implements OMBundle, OMBundle.DebugSupport, OMBundle.TranslationSupport -{ - private static final String CLASS_EXTENSION = ".class"; - - private AbstractPlatform platform; - - private String bundleID; - - private Class<?> accessor; - - private Object bundleContext; - - private boolean debugging; - - private boolean debuggingInitialized; - - private Map<String, Tracer> tracers = new ConcurrentHashMap<String, Tracer>(0); - - private OMLogger logger; - - private Preferences preferences; - - private ResourceBundle resourceBundle; - - private ResourceBundle untranslatedResourceBundle; - - private Map<String, String> strings = new HashMap<String, String>(0); - - private Map<String, String> untranslatedStrings = new HashMap<String, String>(0); - - private boolean shouldTranslate = true; - - public AbstractBundle(AbstractPlatform platform, String bundleID, Class<?> accessor) - { - this.platform = platform; - this.bundleID = bundleID; - this.accessor = accessor; - } - - public OMPlatform getPlatform() - { - return platform; - } - - public String getBundleID() - { - return bundleID; - } - - public Class<?> getAccessor() - { - return accessor; - } - - public Object getBundleContext() - { - return bundleContext; - } - - @Deprecated - public void setBundleContext(Object bundleContext) - { - this.bundleContext = bundleContext; - } - - public DebugSupport getDebugSupport() - { - return this; - } - - public TranslationSupport getTranslationSupport() - { - return this; - } - - public boolean isDebugging() - { - if (!platform.isDebugging()) - { - return false; - } - - if (!debuggingInitialized) - { - debugging = getDebugOption("debug", false); //$NON-NLS-1$ - debuggingInitialized = true; - } - - return debugging; - } - - public void setDebugging(boolean debugging) - { - this.debugging = debugging; - } - - public String getDebugOption(String option, String defaultValue) - { - String value = getDebugOption(option); - return value == null ? defaultValue : value; - } - - public boolean getDebugOption(String option, boolean defaultValue) - { - String value = getDebugOption(option); - return value == null ? defaultValue : Boolean.parseBoolean(value); - } - - public void setDebugOption(String option, boolean value) - { - setDebugOption(option, Boolean.toString(value)); - } - - public int getDebugOption(String option, int defaultValue) - { - try - { - String value = getDebugOption(option); - return value == null ? defaultValue : Integer.parseInt(value); - } - catch (NumberFormatException e) - { - return defaultValue; - } - } - - public void setDebugOption(String option, int value) - { - setDebugOption(option, Integer.toString(value)); - } - - public String getDebugOption(String option) - { - return platform.getDebugOption(bundleID, option); - } - - public void setDebugOption(String option, String value) - { - platform.setDebugOption(bundleID, option, value); - } - - public synchronized OMTracer tracer(String name) - { - OMTracer tracer = tracers.get(name); - if (tracer == null) - { - tracer = createTracer(name); - } - - return tracer; - } - - public synchronized OMLogger logger() - { - if (logger == null) - { - logger = createLogger(); - } - - return logger; - } - - public File getConfigFile() - { - return platform.getConfigFile(getConfigFileName()); - } - - public Properties getConfigProperties() - { - return platform.getConfigProperties(getConfigFileName()); - } - - public synchronized Preferences preferences() - { - if (preferences == null) - { - preferences = new Preferences(this); - } - - return preferences; - } - - public InputStream getInputStream(String path) throws IOException - { - String base = getBaseURL().toString(); - if (!base.endsWith("/")) //$NON-NLS-1$ - { - base += "/"; //$NON-NLS-1$ - } - - if (path.startsWith("/")) //$NON-NLS-1$ - { - path = path.substring(1); - } - - URL url = new URL(base + path); - return url.openStream(); - } - - public boolean shouldTranslate() - { - return shouldTranslate; - } - - public void setShouldTranslate(boolean shouldTranslate) - { - this.shouldTranslate = shouldTranslate; - } - - public String getString(String key, boolean translate) - { - Map<String, String> stringMap = translate ? strings : untranslatedStrings; - String result = stringMap.get(key); - if (result == null) - { - ResourceBundle bundle = translate ? resourceBundle : untranslatedResourceBundle; - if (bundle == null) - { - String packageName = ReflectUtil.getPackageName(accessor); - if (translate) - { - try - { - bundle = resourceBundle = ResourceBundle.getBundle(packageName + ".plugin"); //$NON-NLS-1$ - } - catch (MissingResourceException exception) - { - // If the bundle can't be found the normal way, try to find it as - // the base URL. If that also doesn't work, rethrow the original - // exception. - InputStream inputStream = null; - try - { - inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$ - bundle = new PropertyResourceBundle(inputStream); - untranslatedResourceBundle = resourceBundle = bundle; - inputStream.close(); - } - catch (IOException ignore) - { - } - finally - { - IOUtil.closeSilent(inputStream); - } - - if (resourceBundle == null) - { - throw exception; - } - } - } - else - { - InputStream inputStream = null; - - try - { - inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$ - bundle = untranslatedResourceBundle = new PropertyResourceBundle(inputStream); - inputStream.close(); - } - catch (IOException ioException) - { - throw new MissingResourceException("Missing resource: plugin.properties", accessor //$NON-NLS-1$ - .getName(), key); - } - finally - { - IOUtil.closeSilent(inputStream); - } - } - } - - result = bundle.getString(key); - stringMap.put(key, result); - } - - return result; - } - - public String getString(String key) - { - return getString(key, shouldTranslate()); - } - - public String getString(String key, Object... args) - { - return getString(key, shouldTranslate(), args); - } - - public String getString(String key, boolean translate, Object... args) - { - return MessageFormat.format(getString(key, translate), args); - } - - @Override - public String toString() - { - return bundleID; - } - - public void start() throws Exception - { - invokeMethod("start"); //$NON-NLS-1$ - } - - public void stop() throws Exception - { - try - { - if (preferences != null) - { - preferences.save(); - } - } - catch (RuntimeException ex) - { - OM.LOG.error(ex); - } - - invokeMethod("stop"); //$NON-NLS-1$ - } - - protected OMTracer createTracer(String name) - { - return new Tracer(this, name); - } - - protected OMLogger createLogger() - { - return new Logger(this); - } - - protected String getConfigFileName() - { - return bundleID + ".properties"; //$NON-NLS-1$ - } - - protected final Class<?> getClassFromBundle(String path) - { - if (path.endsWith(CLASS_EXTENSION)) - { - int start = path.startsWith("/") ? 1 : 0; - int end = path.length() - CLASS_EXTENSION.length(); - String className = path.substring(start, end).replace('/', '.'); - - for (;;) - { - try - { - ClassLoader classLoader = getAccessor().getClassLoader(); - Class<?> c = classLoader.loadClass(className); - if (c != null) - { - return c; - } - } - catch (NoClassDefFoundError ex) - { - //$FALL-THROUGH$ - } - catch (ClassNotFoundException ex) - { - //$FALL-THROUGH$ - } - - int dot = className.indexOf('.'); - if (dot == -1) - { - break; - } - - className = className.substring(dot + 1); - } - } - - return null; - } - - private void invokeMethod(String name) throws Exception - { - try - { - Method method = accessor.getDeclaredMethod(name, ReflectUtil.NO_PARAMETERS); - if (!method.isAccessible()) - { - method.setAccessible(true); - } - - method.invoke(null, ReflectUtil.NO_ARGUMENTS); - } - catch (NoSuchMethodException ignore) - { - } - catch (IllegalAccessException ignore) - { - } - catch (InvocationTargetException ex) - { - Throwable targetException = ex.getTargetException(); - if (targetException instanceof Exception) - { - throw (Exception)targetException; - } - else if (targetException instanceof Error) - { - throw (Error)targetException; - } - else - { - OM.LOG.error(targetException); - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.bundle;
+
+import org.eclipse.net4j.internal.util.om.pref.Preferences;
+import org.eclipse.net4j.util.ReflectUtil;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.OMBundle;
+import org.eclipse.net4j.util.om.OMPlatform;
+import org.eclipse.net4j.util.om.log.Logger;
+import org.eclipse.net4j.util.om.log.OMLogger;
+import org.eclipse.net4j.util.om.trace.OMTracer;
+import org.eclipse.net4j.util.om.trace.Tracer;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.text.MessageFormat;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.Properties;
+import java.util.PropertyResourceBundle;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class AbstractBundle implements OMBundle, OMBundle.DebugSupport, OMBundle.TranslationSupport
+{
+ private static final String CLASS_EXTENSION = ".class";
+
+ private AbstractPlatform platform;
+
+ private String bundleID;
+
+ private Class<?> accessor;
+
+ private Object bundleContext;
+
+ private boolean debugging;
+
+ private boolean debuggingInitialized;
+
+ private Map<String, Tracer> tracers = new ConcurrentHashMap<String, Tracer>(0);
+
+ private OMLogger logger;
+
+ private Preferences preferences;
+
+ private ResourceBundle resourceBundle;
+
+ private ResourceBundle untranslatedResourceBundle;
+
+ private Map<String, String> strings = new HashMap<String, String>(0);
+
+ private Map<String, String> untranslatedStrings = new HashMap<String, String>(0);
+
+ private boolean shouldTranslate = true;
+
+ public AbstractBundle(AbstractPlatform platform, String bundleID, Class<?> accessor)
+ {
+ this.platform = platform;
+ this.bundleID = bundleID;
+ this.accessor = accessor;
+ }
+
+ public OMPlatform getPlatform()
+ {
+ return platform;
+ }
+
+ public String getBundleID()
+ {
+ return bundleID;
+ }
+
+ public Class<?> getAccessor()
+ {
+ return accessor;
+ }
+
+ public Object getBundleContext()
+ {
+ return bundleContext;
+ }
+
+ @Deprecated
+ public void setBundleContext(Object bundleContext)
+ {
+ this.bundleContext = bundleContext;
+ }
+
+ public DebugSupport getDebugSupport()
+ {
+ return this;
+ }
+
+ public TranslationSupport getTranslationSupport()
+ {
+ return this;
+ }
+
+ public boolean isDebugging()
+ {
+ if (!platform.isDebugging())
+ {
+ return false;
+ }
+
+ if (!debuggingInitialized)
+ {
+ debugging = getDebugOption("debug", false); //$NON-NLS-1$
+ debuggingInitialized = true;
+ }
+
+ return debugging;
+ }
+
+ public void setDebugging(boolean debugging)
+ {
+ this.debugging = debugging;
+ }
+
+ public String getDebugOption(String option, String defaultValue)
+ {
+ String value = getDebugOption(option);
+ return value == null ? defaultValue : value;
+ }
+
+ public boolean getDebugOption(String option, boolean defaultValue)
+ {
+ String value = getDebugOption(option);
+ return value == null ? defaultValue : Boolean.parseBoolean(value);
+ }
+
+ public void setDebugOption(String option, boolean value)
+ {
+ setDebugOption(option, Boolean.toString(value));
+ }
+
+ public int getDebugOption(String option, int defaultValue)
+ {
+ try
+ {
+ String value = getDebugOption(option);
+ return value == null ? defaultValue : Integer.parseInt(value);
+ }
+ catch (NumberFormatException e)
+ {
+ return defaultValue;
+ }
+ }
+
+ public void setDebugOption(String option, int value)
+ {
+ setDebugOption(option, Integer.toString(value));
+ }
+
+ public String getDebugOption(String option)
+ {
+ return platform.getDebugOption(bundleID, option);
+ }
+
+ public void setDebugOption(String option, String value)
+ {
+ platform.setDebugOption(bundleID, option, value);
+ }
+
+ public synchronized OMTracer tracer(String name)
+ {
+ OMTracer tracer = tracers.get(name);
+ if (tracer == null)
+ {
+ tracer = createTracer(name);
+ }
+
+ return tracer;
+ }
+
+ public synchronized OMLogger logger()
+ {
+ if (logger == null)
+ {
+ logger = createLogger();
+ }
+
+ return logger;
+ }
+
+ public File getConfigFile()
+ {
+ return platform.getConfigFile(getConfigFileName());
+ }
+
+ public Properties getConfigProperties()
+ {
+ return platform.getConfigProperties(getConfigFileName());
+ }
+
+ public synchronized Preferences preferences()
+ {
+ if (preferences == null)
+ {
+ preferences = new Preferences(this);
+ }
+
+ return preferences;
+ }
+
+ public InputStream getInputStream(String path) throws IOException
+ {
+ String base = getBaseURL().toString();
+ if (!base.endsWith("/")) //$NON-NLS-1$
+ {
+ base += "/"; //$NON-NLS-1$
+ }
+
+ if (path.startsWith("/")) //$NON-NLS-1$
+ {
+ path = path.substring(1);
+ }
+
+ URL url = new URL(base + path);
+ return url.openStream();
+ }
+
+ public boolean shouldTranslate()
+ {
+ return shouldTranslate;
+ }
+
+ public void setShouldTranslate(boolean shouldTranslate)
+ {
+ this.shouldTranslate = shouldTranslate;
+ }
+
+ public String getString(String key, boolean translate)
+ {
+ Map<String, String> stringMap = translate ? strings : untranslatedStrings;
+ String result = stringMap.get(key);
+ if (result == null)
+ {
+ ResourceBundle bundle = translate ? resourceBundle : untranslatedResourceBundle;
+ if (bundle == null)
+ {
+ String packageName = ReflectUtil.getPackageName(accessor);
+ if (translate)
+ {
+ try
+ {
+ bundle = resourceBundle = ResourceBundle.getBundle(packageName + ".plugin"); //$NON-NLS-1$
+ }
+ catch (MissingResourceException exception)
+ {
+ // If the bundle can't be found the normal way, try to find it as
+ // the base URL. If that also doesn't work, rethrow the original
+ // exception.
+ InputStream inputStream = null;
+ try
+ {
+ inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$
+ bundle = new PropertyResourceBundle(inputStream);
+ untranslatedResourceBundle = resourceBundle = bundle;
+ inputStream.close();
+ }
+ catch (IOException ignore)
+ {
+ }
+ finally
+ {
+ IOUtil.closeSilent(inputStream);
+ }
+
+ if (resourceBundle == null)
+ {
+ throw exception;
+ }
+ }
+ }
+ else
+ {
+ InputStream inputStream = null;
+
+ try
+ {
+ inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$
+ bundle = untranslatedResourceBundle = new PropertyResourceBundle(inputStream);
+ inputStream.close();
+ }
+ catch (IOException ioException)
+ {
+ throw new MissingResourceException("Missing resource: plugin.properties", accessor //$NON-NLS-1$
+ .getName(), key);
+ }
+ finally
+ {
+ IOUtil.closeSilent(inputStream);
+ }
+ }
+ }
+
+ result = bundle.getString(key);
+ stringMap.put(key, result);
+ }
+
+ return result;
+ }
+
+ public String getString(String key)
+ {
+ return getString(key, shouldTranslate());
+ }
+
+ public String getString(String key, Object... args)
+ {
+ return getString(key, shouldTranslate(), args);
+ }
+
+ public String getString(String key, boolean translate, Object... args)
+ {
+ return MessageFormat.format(getString(key, translate), args);
+ }
+
+ @Override
+ public String toString()
+ {
+ return bundleID;
+ }
+
+ public void start() throws Exception
+ {
+ invokeMethod("start"); //$NON-NLS-1$
+ }
+
+ public void stop() throws Exception
+ {
+ try
+ {
+ if (preferences != null)
+ {
+ preferences.save();
+ }
+ }
+ catch (RuntimeException ex)
+ {
+ OM.LOG.error(ex);
+ }
+
+ invokeMethod("stop"); //$NON-NLS-1$
+ }
+
+ protected OMTracer createTracer(String name)
+ {
+ return new Tracer(this, name);
+ }
+
+ protected OMLogger createLogger()
+ {
+ return new Logger(this);
+ }
+
+ protected String getConfigFileName()
+ {
+ return bundleID + ".properties"; //$NON-NLS-1$
+ }
+
+ protected final Class<?> getClassFromBundle(String path)
+ {
+ if (path.endsWith(CLASS_EXTENSION))
+ {
+ int start = path.startsWith("/") ? 1 : 0;
+ int end = path.length() - CLASS_EXTENSION.length();
+ String className = path.substring(start, end).replace('/', '.');
+
+ for (;;)
+ {
+ try
+ {
+ ClassLoader classLoader = getAccessor().getClassLoader();
+ Class<?> c = classLoader.loadClass(className);
+ if (c != null)
+ {
+ return c;
+ }
+ }
+ catch (NoClassDefFoundError ex)
+ {
+ //$FALL-THROUGH$
+ }
+ catch (ClassNotFoundException ex)
+ {
+ //$FALL-THROUGH$
+ }
+
+ int dot = className.indexOf('.');
+ if (dot == -1)
+ {
+ break;
+ }
+
+ className = className.substring(dot + 1);
+ }
+ }
+
+ return null;
+ }
+
+ private void invokeMethod(String name) throws Exception
+ {
+ try
+ {
+ Method method = accessor.getDeclaredMethod(name, ReflectUtil.NO_PARAMETERS);
+ if (!method.isAccessible())
+ {
+ method.setAccessible(true);
+ }
+
+ method.invoke(null, ReflectUtil.NO_ARGUMENTS);
+ }
+ catch (NoSuchMethodException ignore)
+ {
+ }
+ catch (IllegalAccessException ignore)
+ {
+ }
+ catch (InvocationTargetException ex)
+ {
+ Throwable targetException = ex.getTargetException();
+ if (targetException instanceof Exception)
+ {
+ throw (Exception)targetException;
+ }
+ else if (targetException instanceof Error)
+ {
+ throw (Error)targetException;
+ }
+ else
+ {
+ OM.LOG.error(targetException);
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java index 103b9ebb53..7d0aef5db7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java @@ -1,380 +1,380 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.bundle; - -import org.eclipse.net4j.internal.util.om.LegacyPlatform; -import org.eclipse.net4j.internal.util.om.OSGiPlatform; -import org.eclipse.net4j.util.collection.ConcurrentArray; -import org.eclipse.net4j.util.io.IORuntimeException; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.OMBundle; -import org.eclipse.net4j.util.om.OMPlatform; -import org.eclipse.net4j.util.om.log.OMLogFilter; -import org.eclipse.net4j.util.om.log.OMLogHandler; -import org.eclipse.net4j.util.om.log.OMLogger; -import org.eclipse.net4j.util.om.log.OMLogger.Level; -import org.eclipse.net4j.util.om.trace.ContextTracer; -import org.eclipse.net4j.util.om.trace.OMTraceHandler; -import org.eclipse.net4j.util.om.trace.OMTraceHandlerEvent; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Eike Stepper - */ -public abstract class AbstractPlatform implements OMPlatform -{ - public static final String SYSTEM_PROPERTY_OSGI_STATE = "osgi.instance.area"; //$NON-NLS-1$ - - public static final String SYSTEM_PROPERTY_NET4J_STATE = "net4j.state"; //$NON-NLS-1$ - - public static final String SYSTEM_PROPERTY_NET4J_CONFIG = "net4j.config"; //$NON-NLS-1$ - - static Object systemContext; - - private static ContextTracer __TRACER__; - - private Map<String, AbstractBundle> bundles = new ConcurrentHashMap<String, AbstractBundle>(0); - - private ConcurrentArray<OMLogFilter> logFilters = new ConcurrentArray.Unique<OMLogFilter>() - { - @Override - protected OMLogFilter[] newArray(int length) - { - return new OMLogFilter[length]; - } - }; - - private ConcurrentArray<OMLogHandler> logHandlers = new ConcurrentArray.Unique<OMLogHandler>() - { - @Override - protected OMLogHandler[] newArray(int length) - { - return new OMLogHandler[length]; - } - }; - - private ConcurrentArray<OMTraceHandler> traceHandlers = new ConcurrentArray.Unique<OMTraceHandler>() - { - @Override - protected OMTraceHandler[] newArray(int length) - { - return new OMTraceHandler[length]; - } - }; - - private boolean debugging; - - protected AbstractPlatform() - { - debugging = Boolean.parseBoolean(getProperty("debug", "false")); //$NON-NLS-1$ //$NON-NLS-2$ - } - - public synchronized OMBundle bundle(String bundleID, Class<?> accessor) - { - OMBundle bundle = bundles.get(bundleID); - if (bundle == null) - { - bundle = createBundle(bundleID, accessor); - } - - return bundle; - } - - public void addLogFilter(OMLogFilter logFilter) - { - logFilters.add(logFilter); - } - - public void removeLogFilter(OMLogFilter logFilter) - { - logFilters.remove(logFilter); - } - - public void addLogHandler(OMLogHandler logHandler) - { - logHandlers.add(logHandler); - } - - public void removeLogHandler(OMLogHandler logHandler) - { - logHandlers.remove(logHandler); - } - - public void addTraceHandler(OMTraceHandler traceHandler) - { - traceHandlers.add(traceHandler); - } - - public void removeTraceHandler(OMTraceHandler traceHandler) - { - traceHandlers.remove(traceHandler); - } - - public boolean isExtensionRegistryAvailable() - { - try - { - return internalExtensionRegistryAvailable(); - } - catch (Throwable ex) - { - return false; - } - } - - public boolean isDebugging() - { - return debugging; - } - - public void setDebugging(boolean debugging) - { - this.debugging = debugging; - } - - public File getStateFolder() - { - String state = getProperty(SYSTEM_PROPERTY_NET4J_STATE); - if (state == null) - { - state = getProperty(SYSTEM_PROPERTY_OSGI_STATE); - if (state == null) - { - state = "state"; //$NON-NLS-1$ - } - else - { - try - { - URI uri = new URI(state); - state = new File(new File(uri), ".metadata").getAbsolutePath(); //$NON-NLS-1$; - } - catch (Exception ex) - { - OM.LOG.error("Property " + SYSTEM_PROPERTY_OSGI_STATE + " is not a proper file URI: " + state); //$NON-NLS-1$ //$NON-NLS-2$ - state = "state"; //$NON-NLS-1$ - } - } - } - - File stateFolder = new File(state); - if (!stateFolder.exists()) - { - if (!stateFolder.mkdirs()) - { - throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - if (!stateFolder.isDirectory()) - { - throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - return stateFolder; - } - - public File getConfigFolder() - { - String config = getProperty(SYSTEM_PROPERTY_NET4J_CONFIG, "config"); //$NON-NLS-1$ - File configFolder = new File(config); - if (!configFolder.exists()) - { - if (!configFolder.mkdirs()) - { - OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$ - return null; - } - } - - if (!configFolder.isDirectory()) - { - OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$ - return null; - } - - return configFolder; - } - - public File getConfigFile(String name) - { - File configFolder = getConfigFolder(); - if (configFolder == null) - { - return null; - } - - return new File(configFolder, name); - } - - public Properties getConfigProperties(String name) - { - File configFile = getConfigFile(name); - if (configFile == null) - { - return null; - } - - FileInputStream fis = null; - try - { - fis = new FileInputStream(configFile); - Properties properties = new Properties(); - properties.load(fis); - return properties; - } - catch (IOException ex) - { - OM.LOG.error("Config file " + configFile.getAbsolutePath() + " could not be read"); //$NON-NLS-1$ //$NON-NLS-2$ - return null; - } - finally - { - IOUtil.closeSilent(fis); - } - } - - public void log(OMLogger logger, Level level, String msg, Throwable t) - { - if (!logFilters.isEmpty()) - { - for (OMLogFilter logFilter : logFilters.get()) - { - try - { - if (logFilter.filter(logger, level, msg, t)) - { - if (TRACER().isEnabled()) - { - TRACER().format("Filtered log event: logger={0}, level={1}, msg={2}\n{3}", logger, level, msg, t); - } - - return; - } - } - catch (Exception ex) - { - if (TRACER().isEnabled()) - { - TRACER().trace(ex); - } - } - } - } - - if (!logHandlers.isEmpty()) - { - for (OMLogHandler logHandler : logHandlers.get()) - { - try - { - logHandler.logged(logger, level, msg, t); - } - catch (Exception ex) - { - if (TRACER().isEnabled()) - { - TRACER().trace(ex); - } - } - } - } - } - - public void trace(OMTraceHandlerEvent event) - { - if (!traceHandlers.isEmpty()) - { - for (OMTraceHandler traceHandler : traceHandlers.get()) - { - try - { - traceHandler.traced(event); - } - catch (Exception ex) - { - if (TRACER().isEnabled()) - { - TRACER().trace(ex); - } - } - } - } - } - - protected Map<String, AbstractBundle> getBundles() - { - return bundles; - } - - public String getProperty(String key) - { - return System.getProperty(key); - } - - public String getProperty(String key, String defaultValue) - { - return System.getProperty(key, defaultValue); - } - - protected abstract OMBundle createBundle(String bundleID, Class<?> accessor); - - protected abstract String getDebugOption(String bundleID, String option); - - protected abstract void setDebugOption(String bundleID, String option, String value); - - /** - * TODO Make configurable via system property - */ - public static synchronized OMPlatform createPlatform() - { - try - { - if (systemContext != null) - { - return new OSGiPlatform(systemContext); - } - - return new LegacyPlatform(); - } - catch (Exception ex) - { - if (TRACER().isEnabled()) - { - TRACER().trace(ex); - } - } - - return null; - } - - private static ContextTracer TRACER() - { - if (__TRACER__ == null) - { - __TRACER__ = new ContextTracer(OM.DEBUG_OM, AbstractPlatform.class); - } - - return __TRACER__; - } - - private static boolean internalExtensionRegistryAvailable() throws Throwable - { - return org.eclipse.core.runtime.Platform.getExtensionRegistry() != null; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.bundle;
+
+import org.eclipse.net4j.internal.util.om.LegacyPlatform;
+import org.eclipse.net4j.internal.util.om.OSGiPlatform;
+import org.eclipse.net4j.util.collection.ConcurrentArray;
+import org.eclipse.net4j.util.io.IORuntimeException;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.OMBundle;
+import org.eclipse.net4j.util.om.OMPlatform;
+import org.eclipse.net4j.util.om.log.OMLogFilter;
+import org.eclipse.net4j.util.om.log.OMLogHandler;
+import org.eclipse.net4j.util.om.log.OMLogger;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+import org.eclipse.net4j.util.om.trace.OMTraceHandler;
+import org.eclipse.net4j.util.om.trace.OMTraceHandlerEvent;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URI;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class AbstractPlatform implements OMPlatform
+{
+ public static final String SYSTEM_PROPERTY_OSGI_STATE = "osgi.instance.area"; //$NON-NLS-1$
+
+ public static final String SYSTEM_PROPERTY_NET4J_STATE = "net4j.state"; //$NON-NLS-1$
+
+ public static final String SYSTEM_PROPERTY_NET4J_CONFIG = "net4j.config"; //$NON-NLS-1$
+
+ static Object systemContext;
+
+ private static ContextTracer __TRACER__;
+
+ private Map<String, AbstractBundle> bundles = new ConcurrentHashMap<String, AbstractBundle>(0);
+
+ private ConcurrentArray<OMLogFilter> logFilters = new ConcurrentArray.Unique<OMLogFilter>()
+ {
+ @Override
+ protected OMLogFilter[] newArray(int length)
+ {
+ return new OMLogFilter[length];
+ }
+ };
+
+ private ConcurrentArray<OMLogHandler> logHandlers = new ConcurrentArray.Unique<OMLogHandler>()
+ {
+ @Override
+ protected OMLogHandler[] newArray(int length)
+ {
+ return new OMLogHandler[length];
+ }
+ };
+
+ private ConcurrentArray<OMTraceHandler> traceHandlers = new ConcurrentArray.Unique<OMTraceHandler>()
+ {
+ @Override
+ protected OMTraceHandler[] newArray(int length)
+ {
+ return new OMTraceHandler[length];
+ }
+ };
+
+ private boolean debugging;
+
+ protected AbstractPlatform()
+ {
+ debugging = Boolean.parseBoolean(getProperty("debug", "false")); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ public synchronized OMBundle bundle(String bundleID, Class<?> accessor)
+ {
+ OMBundle bundle = bundles.get(bundleID);
+ if (bundle == null)
+ {
+ bundle = createBundle(bundleID, accessor);
+ }
+
+ return bundle;
+ }
+
+ public void addLogFilter(OMLogFilter logFilter)
+ {
+ logFilters.add(logFilter);
+ }
+
+ public void removeLogFilter(OMLogFilter logFilter)
+ {
+ logFilters.remove(logFilter);
+ }
+
+ public void addLogHandler(OMLogHandler logHandler)
+ {
+ logHandlers.add(logHandler);
+ }
+
+ public void removeLogHandler(OMLogHandler logHandler)
+ {
+ logHandlers.remove(logHandler);
+ }
+
+ public void addTraceHandler(OMTraceHandler traceHandler)
+ {
+ traceHandlers.add(traceHandler);
+ }
+
+ public void removeTraceHandler(OMTraceHandler traceHandler)
+ {
+ traceHandlers.remove(traceHandler);
+ }
+
+ public boolean isExtensionRegistryAvailable()
+ {
+ try
+ {
+ return internalExtensionRegistryAvailable();
+ }
+ catch (Throwable ex)
+ {
+ return false;
+ }
+ }
+
+ public boolean isDebugging()
+ {
+ return debugging;
+ }
+
+ public void setDebugging(boolean debugging)
+ {
+ this.debugging = debugging;
+ }
+
+ public File getStateFolder()
+ {
+ String state = getProperty(SYSTEM_PROPERTY_NET4J_STATE);
+ if (state == null)
+ {
+ state = getProperty(SYSTEM_PROPERTY_OSGI_STATE);
+ if (state == null)
+ {
+ state = "state"; //$NON-NLS-1$
+ }
+ else
+ {
+ try
+ {
+ URI uri = new URI(state);
+ state = new File(new File(uri), ".metadata").getAbsolutePath(); //$NON-NLS-1$;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error("Property " + SYSTEM_PROPERTY_OSGI_STATE + " is not a proper file URI: " + state); //$NON-NLS-1$ //$NON-NLS-2$
+ state = "state"; //$NON-NLS-1$
+ }
+ }
+ }
+
+ File stateFolder = new File(state);
+ if (!stateFolder.exists())
+ {
+ if (!stateFolder.mkdirs())
+ {
+ throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ if (!stateFolder.isDirectory())
+ {
+ throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ return stateFolder;
+ }
+
+ public File getConfigFolder()
+ {
+ String config = getProperty(SYSTEM_PROPERTY_NET4J_CONFIG, "config"); //$NON-NLS-1$
+ File configFolder = new File(config);
+ if (!configFolder.exists())
+ {
+ if (!configFolder.mkdirs())
+ {
+ OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$
+ return null;
+ }
+ }
+
+ if (!configFolder.isDirectory())
+ {
+ OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$
+ return null;
+ }
+
+ return configFolder;
+ }
+
+ public File getConfigFile(String name)
+ {
+ File configFolder = getConfigFolder();
+ if (configFolder == null)
+ {
+ return null;
+ }
+
+ return new File(configFolder, name);
+ }
+
+ public Properties getConfigProperties(String name)
+ {
+ File configFile = getConfigFile(name);
+ if (configFile == null)
+ {
+ return null;
+ }
+
+ FileInputStream fis = null;
+ try
+ {
+ fis = new FileInputStream(configFile);
+ Properties properties = new Properties();
+ properties.load(fis);
+ return properties;
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error("Config file " + configFile.getAbsolutePath() + " could not be read"); //$NON-NLS-1$ //$NON-NLS-2$
+ return null;
+ }
+ finally
+ {
+ IOUtil.closeSilent(fis);
+ }
+ }
+
+ public void log(OMLogger logger, Level level, String msg, Throwable t)
+ {
+ if (!logFilters.isEmpty())
+ {
+ for (OMLogFilter logFilter : logFilters.get())
+ {
+ try
+ {
+ if (logFilter.filter(logger, level, msg, t))
+ {
+ if (TRACER().isEnabled())
+ {
+ TRACER().format("Filtered log event: logger={0}, level={1}, msg={2}\n{3}", logger, level, msg, t);
+ }
+
+ return;
+ }
+ }
+ catch (Exception ex)
+ {
+ if (TRACER().isEnabled())
+ {
+ TRACER().trace(ex);
+ }
+ }
+ }
+ }
+
+ if (!logHandlers.isEmpty())
+ {
+ for (OMLogHandler logHandler : logHandlers.get())
+ {
+ try
+ {
+ logHandler.logged(logger, level, msg, t);
+ }
+ catch (Exception ex)
+ {
+ if (TRACER().isEnabled())
+ {
+ TRACER().trace(ex);
+ }
+ }
+ }
+ }
+ }
+
+ public void trace(OMTraceHandlerEvent event)
+ {
+ if (!traceHandlers.isEmpty())
+ {
+ for (OMTraceHandler traceHandler : traceHandlers.get())
+ {
+ try
+ {
+ traceHandler.traced(event);
+ }
+ catch (Exception ex)
+ {
+ if (TRACER().isEnabled())
+ {
+ TRACER().trace(ex);
+ }
+ }
+ }
+ }
+ }
+
+ protected Map<String, AbstractBundle> getBundles()
+ {
+ return bundles;
+ }
+
+ public String getProperty(String key)
+ {
+ return System.getProperty(key);
+ }
+
+ public String getProperty(String key, String defaultValue)
+ {
+ return System.getProperty(key, defaultValue);
+ }
+
+ protected abstract OMBundle createBundle(String bundleID, Class<?> accessor);
+
+ protected abstract String getDebugOption(String bundleID, String option);
+
+ protected abstract void setDebugOption(String bundleID, String option, String value);
+
+ /**
+ * TODO Make configurable via system property
+ */
+ public static synchronized OMPlatform createPlatform()
+ {
+ try
+ {
+ if (systemContext != null)
+ {
+ return new OSGiPlatform(systemContext);
+ }
+
+ return new LegacyPlatform();
+ }
+ catch (Exception ex)
+ {
+ if (TRACER().isEnabled())
+ {
+ TRACER().trace(ex);
+ }
+ }
+
+ return null;
+ }
+
+ private static ContextTracer TRACER()
+ {
+ if (__TRACER__ == null)
+ {
+ __TRACER__ = new ContextTracer(OM.DEBUG_OM, AbstractPlatform.class);
+ }
+
+ return __TRACER__;
+ }
+
+ private static boolean internalExtensionRegistryAvailable() throws Throwable
+ {
+ return org.eclipse.core.runtime.Platform.getExtensionRegistry() != null;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java index 30222f89ea..d9cb9960d5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java @@ -1,105 +1,105 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.bundle; - -import org.eclipse.net4j.internal.util.container.PluginContainer; -import org.eclipse.net4j.internal.util.om.OSGiBundle; -import org.eclipse.net4j.util.container.IPluginContainer; -import org.eclipse.net4j.util.om.OMBundle; -import org.eclipse.net4j.util.om.OMPlatform; -import org.eclipse.net4j.util.om.OSGiActivator; -import org.eclipse.net4j.util.om.log.EclipseLoggingBridge; -import org.eclipse.net4j.util.om.log.OMLogger; -import org.eclipse.net4j.util.om.log.PrintLogHandler; -import org.eclipse.net4j.util.om.trace.ContextTracer; -import org.eclipse.net4j.util.om.trace.OMTracer; -import org.eclipse.net4j.util.om.trace.PrintTraceHandler; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -/** - * The <em>Operations & Maintenance</em> class of this bundle. - * - * @author Eike Stepper - */ -public abstract class OM -{ - public static final String BUNDLE_ID = "org.eclipse.net4j.util"; //$NON-NLS-1$ - - public static final OMBundle BUNDLE = OMPlatform.INSTANCE.bundle(BUNDLE_ID, OM.class); - - public static final OMTracer DEBUG = BUNDLE.tracer("debug"); //$NON-NLS-1$ - - public static final OMTracer DEBUG_LIFECYCLE = DEBUG.tracer("lifecycle"); //$NON-NLS-1$ - - public static final OMTracer DEBUG_LIFECYCLE_DUMP = DEBUG_LIFECYCLE.tracer("dump"); //$NON-NLS-1$ - - public static final OMTracer DEBUG_CONCURRENCY = DEBUG.tracer("concurrency"); //$NON-NLS-1$ - - public static final OMTracer DEBUG_REGISTRY = DEBUG.tracer("registry"); //$NON-NLS-1$ - - public static final OMTracer DEBUG_OM = DEBUG.tracer("om"); //$NON-NLS-1$ - - public static final OMTracer DEBUG_MONITOR = DEBUG_OM.tracer("monitor"); //$NON-NLS-1$ - - public static final OMLogger LOG = BUNDLE.logger(); - - public static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OM.class); - - /** - * @author Eike Stepper - */ - public static final class Activator implements BundleActivator - { - public void start(BundleContext context) throws Exception - { - AbstractPlatform.systemContext = context; - setBundleContext(context); - ((OSGiBundle)OM.BUNDLE).start(); - - // TODO Make configurable - PrintTraceHandler.CONSOLE.setPattern("{6} [{0}] {5}"); //$NON-NLS-1$ - AbstractPlatform.INSTANCE.addTraceHandler(PrintTraceHandler.CONSOLE); - AbstractPlatform.INSTANCE.addLogHandler(PrintLogHandler.CONSOLE); - - try - { - AbstractPlatform.INSTANCE.addLogHandler(EclipseLoggingBridge.INSTANCE); - } - catch (Throwable ignore) - { - } - - OSGiActivator.traceStart(context); - IPluginContainer container = IPluginContainer.INSTANCE; - if (TRACER.isEnabled()) - { - TRACER.format("Plugin container created: {0}", container); //$NON-NLS-1$ - } - } - - public void stop(BundleContext context) throws Exception - { - OSGiActivator.traceStop(context); - ((OSGiBundle)OM.BUNDLE).stop(); - PluginContainer.dispose(); - setBundleContext(null); - AbstractPlatform.systemContext = null; - } - - @SuppressWarnings("deprecation") - private void setBundleContext(BundleContext context) - { - OM.BUNDLE.setBundleContext(context); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.bundle;
+
+import org.eclipse.net4j.internal.util.container.PluginContainer;
+import org.eclipse.net4j.internal.util.om.OSGiBundle;
+import org.eclipse.net4j.util.container.IPluginContainer;
+import org.eclipse.net4j.util.om.OMBundle;
+import org.eclipse.net4j.util.om.OMPlatform;
+import org.eclipse.net4j.util.om.OSGiActivator;
+import org.eclipse.net4j.util.om.log.EclipseLoggingBridge;
+import org.eclipse.net4j.util.om.log.OMLogger;
+import org.eclipse.net4j.util.om.log.PrintLogHandler;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+import org.eclipse.net4j.util.om.trace.OMTracer;
+import org.eclipse.net4j.util.om.trace.PrintTraceHandler;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+/**
+ * The <em>Operations & Maintenance</em> class of this bundle.
+ *
+ * @author Eike Stepper
+ */
+public abstract class OM
+{
+ public static final String BUNDLE_ID = "org.eclipse.net4j.util"; //$NON-NLS-1$
+
+ public static final OMBundle BUNDLE = OMPlatform.INSTANCE.bundle(BUNDLE_ID, OM.class);
+
+ public static final OMTracer DEBUG = BUNDLE.tracer("debug"); //$NON-NLS-1$
+
+ public static final OMTracer DEBUG_LIFECYCLE = DEBUG.tracer("lifecycle"); //$NON-NLS-1$
+
+ public static final OMTracer DEBUG_LIFECYCLE_DUMP = DEBUG_LIFECYCLE.tracer("dump"); //$NON-NLS-1$
+
+ public static final OMTracer DEBUG_CONCURRENCY = DEBUG.tracer("concurrency"); //$NON-NLS-1$
+
+ public static final OMTracer DEBUG_REGISTRY = DEBUG.tracer("registry"); //$NON-NLS-1$
+
+ public static final OMTracer DEBUG_OM = DEBUG.tracer("om"); //$NON-NLS-1$
+
+ public static final OMTracer DEBUG_MONITOR = DEBUG_OM.tracer("monitor"); //$NON-NLS-1$
+
+ public static final OMLogger LOG = BUNDLE.logger();
+
+ public static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OM.class);
+
+ /**
+ * @author Eike Stepper
+ */
+ public static final class Activator implements BundleActivator
+ {
+ public void start(BundleContext context) throws Exception
+ {
+ AbstractPlatform.systemContext = context;
+ setBundleContext(context);
+ ((OSGiBundle)OM.BUNDLE).start();
+
+ // TODO Make configurable
+ PrintTraceHandler.CONSOLE.setPattern("{6} [{0}] {5}"); //$NON-NLS-1$
+ AbstractPlatform.INSTANCE.addTraceHandler(PrintTraceHandler.CONSOLE);
+ AbstractPlatform.INSTANCE.addLogHandler(PrintLogHandler.CONSOLE);
+
+ try
+ {
+ AbstractPlatform.INSTANCE.addLogHandler(EclipseLoggingBridge.INSTANCE);
+ }
+ catch (Throwable ignore)
+ {
+ }
+
+ OSGiActivator.traceStart(context);
+ IPluginContainer container = IPluginContainer.INSTANCE;
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Plugin container created: {0}", container); //$NON-NLS-1$
+ }
+ }
+
+ public void stop(BundleContext context) throws Exception
+ {
+ OSGiActivator.traceStop(context);
+ ((OSGiBundle)OM.BUNDLE).stop();
+ PluginContainer.dispose();
+ setBundleContext(null);
+ AbstractPlatform.systemContext = null;
+ }
+
+ @SuppressWarnings("deprecation")
+ private void setBundleContext(BundleContext context)
+ {
+ OM.BUNDLE.setBundleContext(context);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java index 4be81e8b9f..2a245e1c2c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.container; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.internal.util.factory.PluginFactoryRegistry; -import org.eclipse.net4j.util.container.IElementProcessor; -import org.eclipse.net4j.util.container.IPluginContainer; -import org.eclipse.net4j.util.container.ManagedContainer; -import org.eclipse.net4j.util.factory.IFactory; -import org.eclipse.net4j.util.factory.IFactoryKey; -import org.eclipse.net4j.util.lifecycle.LifecycleUtil; -import org.eclipse.net4j.util.om.log.OMLogger; -import org.eclipse.net4j.util.registry.IRegistry; - -import java.util.List; - -/** - * @author Eike Stepper - */ -public class PluginContainer extends ManagedContainer implements IPluginContainer -{ - private static PluginContainer instance; - - private PluginContainer() - { - } - - @Override - protected IRegistry<IFactoryKey, IFactory> createFactoryRegistry() - { - return new PluginFactoryRegistry(); - } - - @Override - protected List<IElementProcessor> createPostProcessors() - { - return new PluginElementProcessorList(); - } - - public static void dispose() - { - if (instance != null) - { - LifecycleUtil.deactivate(instance, OMLogger.Level.WARN); - instance = null; - } - } - - public static synchronized PluginContainer getInstance() - { - if (instance == null) - { - instance = new PluginContainer(); - - try - { - instance.activate(); - } - catch (Exception ex) - { - OM.LOG.error(ex); - instance = null; - } - } - - return instance; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.container;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.internal.util.factory.PluginFactoryRegistry;
+import org.eclipse.net4j.util.container.IElementProcessor;
+import org.eclipse.net4j.util.container.IPluginContainer;
+import org.eclipse.net4j.util.container.ManagedContainer;
+import org.eclipse.net4j.util.factory.IFactory;
+import org.eclipse.net4j.util.factory.IFactoryKey;
+import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
+import org.eclipse.net4j.util.om.log.OMLogger;
+import org.eclipse.net4j.util.registry.IRegistry;
+
+import java.util.List;
+
+/**
+ * @author Eike Stepper
+ */
+public class PluginContainer extends ManagedContainer implements IPluginContainer
+{
+ private static PluginContainer instance;
+
+ private PluginContainer()
+ {
+ }
+
+ @Override
+ protected IRegistry<IFactoryKey, IFactory> createFactoryRegistry()
+ {
+ return new PluginFactoryRegistry();
+ }
+
+ @Override
+ protected List<IElementProcessor> createPostProcessors()
+ {
+ return new PluginElementProcessorList();
+ }
+
+ public static void dispose()
+ {
+ if (instance != null)
+ {
+ LifecycleUtil.deactivate(instance, OMLogger.Level.WARN);
+ instance = null;
+ }
+ }
+
+ public static synchronized PluginContainer getInstance()
+ {
+ if (instance == null)
+ {
+ instance = new PluginContainer();
+
+ try
+ {
+ instance.activate();
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ instance = null;
+ }
+ }
+
+ return instance;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java index dc7cc9798b..8fa5704f59 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java @@ -1,253 +1,253 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.container; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.container.IElementProcessor; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import org.eclipse.core.runtime.CoreException; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -/** - * @author Eike Stepper - */ -public class PluginElementProcessorList extends Lifecycle implements List<IElementProcessor> -{ - private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ - - public static final String NAMESPACE = OM.BUNDLE_ID; - - public static final String EXT_POINT = "elementProcessors"; //$NON-NLS-1$ - - private List<IElementProcessor> processors = new ArrayList<IElementProcessor>(); - - private Object extensionRegistryListener; - - public PluginElementProcessorList() - { - } - - public boolean add(IElementProcessor o) - { - return processors.add(o); - } - - public void add(int index, IElementProcessor element) - { - processors.add(index, element); - } - - public boolean addAll(Collection<? extends IElementProcessor> c) - { - return processors.addAll(c); - } - - public boolean addAll(int index, Collection<? extends IElementProcessor> c) - { - return processors.addAll(index, c); - } - - public void clear() - { - processors.clear(); - } - - public boolean contains(Object o) - { - return processors.contains(o); - } - - public boolean containsAll(Collection<?> c) - { - return processors.containsAll(c); - } - - @Override - public boolean equals(Object o) - { - return processors.equals(o); - } - - public IElementProcessor get(int index) - { - return processors.get(index); - } - - @Override - public int hashCode() - { - return processors.hashCode(); - } - - public int indexOf(Object o) - { - return processors.indexOf(o); - } - - public boolean isEmpty() - { - return processors.isEmpty(); - } - - public Iterator<IElementProcessor> iterator() - { - return processors.iterator(); - } - - public int lastIndexOf(Object o) - { - return processors.lastIndexOf(o); - } - - public ListIterator<IElementProcessor> listIterator() - { - return processors.listIterator(); - } - - public ListIterator<IElementProcessor> listIterator(int index) - { - return processors.listIterator(index); - } - - public IElementProcessor remove(int index) - { - return processors.remove(index); - } - - public boolean remove(Object o) - { - return processors.remove(o); - } - - public boolean removeAll(Collection<?> c) - { - return processors.removeAll(c); - } - - public boolean retainAll(Collection<?> c) - { - return processors.retainAll(c); - } - - public IElementProcessor set(int index, IElementProcessor element) - { - return processors.set(index, element); - } - - public int size() - { - return processors.size(); - } - - public List<IElementProcessor> subList(int fromIndex, int toIndex) - { - return processors.subList(fromIndex, toIndex); - } - - public Object[] toArray() - { - return processors.toArray(); - } - - public <T> T[] toArray(T[] a) - { - return processors.toArray(a); - } - - @Override - public String toString() - { - return processors.toString(); - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - try - { - doActivateOSGi(); - } - catch (Throwable t) - { - OM.LOG.warn(t); - } - } - - @Override - protected void doDeactivate() throws Exception - { - try - { - doDeactivateOSGi(); - } - catch (Throwable t) - { - OM.LOG.warn(t); - } - - processors.clear(); - super.doDeactivate(); - } - - private void doActivateOSGi() throws CoreException - { - org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform - .getExtensionRegistry(); - if (extensionRegistry == null) - { - return; - } - - org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor( - NAMESPACE, EXT_POINT); - for (org.eclipse.core.runtime.IConfigurationElement element : elements) - { - IElementProcessor processor = (IElementProcessor)element.createExecutableExtension(ATTR_CLASS); - processors.add(processor); - } - - org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener() - { - public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event) - { - org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT); - for (org.eclipse.core.runtime.IExtensionDelta delta : deltas) - { - // TODO Handle ExtensionDelta - OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$ - } - } - }; - - extensionRegistry.addRegistryChangeListener(listener, NAMESPACE); - extensionRegistryListener = listener; - } - - private void doDeactivateOSGi() - { - org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform - .getExtensionRegistry(); - if (extensionRegistry == null) - { - return; - } - - extensionRegistry - .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.container;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.container.IElementProcessor;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import org.eclipse.core.runtime.CoreException;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * @author Eike Stepper
+ */
+public class PluginElementProcessorList extends Lifecycle implements List<IElementProcessor>
+{
+ private static final String ATTR_CLASS = "class"; //$NON-NLS-1$
+
+ public static final String NAMESPACE = OM.BUNDLE_ID;
+
+ public static final String EXT_POINT = "elementProcessors"; //$NON-NLS-1$
+
+ private List<IElementProcessor> processors = new ArrayList<IElementProcessor>();
+
+ private Object extensionRegistryListener;
+
+ public PluginElementProcessorList()
+ {
+ }
+
+ public boolean add(IElementProcessor o)
+ {
+ return processors.add(o);
+ }
+
+ public void add(int index, IElementProcessor element)
+ {
+ processors.add(index, element);
+ }
+
+ public boolean addAll(Collection<? extends IElementProcessor> c)
+ {
+ return processors.addAll(c);
+ }
+
+ public boolean addAll(int index, Collection<? extends IElementProcessor> c)
+ {
+ return processors.addAll(index, c);
+ }
+
+ public void clear()
+ {
+ processors.clear();
+ }
+
+ public boolean contains(Object o)
+ {
+ return processors.contains(o);
+ }
+
+ public boolean containsAll(Collection<?> c)
+ {
+ return processors.containsAll(c);
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ return processors.equals(o);
+ }
+
+ public IElementProcessor get(int index)
+ {
+ return processors.get(index);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return processors.hashCode();
+ }
+
+ public int indexOf(Object o)
+ {
+ return processors.indexOf(o);
+ }
+
+ public boolean isEmpty()
+ {
+ return processors.isEmpty();
+ }
+
+ public Iterator<IElementProcessor> iterator()
+ {
+ return processors.iterator();
+ }
+
+ public int lastIndexOf(Object o)
+ {
+ return processors.lastIndexOf(o);
+ }
+
+ public ListIterator<IElementProcessor> listIterator()
+ {
+ return processors.listIterator();
+ }
+
+ public ListIterator<IElementProcessor> listIterator(int index)
+ {
+ return processors.listIterator(index);
+ }
+
+ public IElementProcessor remove(int index)
+ {
+ return processors.remove(index);
+ }
+
+ public boolean remove(Object o)
+ {
+ return processors.remove(o);
+ }
+
+ public boolean removeAll(Collection<?> c)
+ {
+ return processors.removeAll(c);
+ }
+
+ public boolean retainAll(Collection<?> c)
+ {
+ return processors.retainAll(c);
+ }
+
+ public IElementProcessor set(int index, IElementProcessor element)
+ {
+ return processors.set(index, element);
+ }
+
+ public int size()
+ {
+ return processors.size();
+ }
+
+ public List<IElementProcessor> subList(int fromIndex, int toIndex)
+ {
+ return processors.subList(fromIndex, toIndex);
+ }
+
+ public Object[] toArray()
+ {
+ return processors.toArray();
+ }
+
+ public <T> T[] toArray(T[] a)
+ {
+ return processors.toArray(a);
+ }
+
+ @Override
+ public String toString()
+ {
+ return processors.toString();
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ try
+ {
+ doActivateOSGi();
+ }
+ catch (Throwable t)
+ {
+ OM.LOG.warn(t);
+ }
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ try
+ {
+ doDeactivateOSGi();
+ }
+ catch (Throwable t)
+ {
+ OM.LOG.warn(t);
+ }
+
+ processors.clear();
+ super.doDeactivate();
+ }
+
+ private void doActivateOSGi() throws CoreException
+ {
+ org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
+ .getExtensionRegistry();
+ if (extensionRegistry == null)
+ {
+ return;
+ }
+
+ org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor(
+ NAMESPACE, EXT_POINT);
+ for (org.eclipse.core.runtime.IConfigurationElement element : elements)
+ {
+ IElementProcessor processor = (IElementProcessor)element.createExecutableExtension(ATTR_CLASS);
+ processors.add(processor);
+ }
+
+ org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener()
+ {
+ public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event)
+ {
+ org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT);
+ for (org.eclipse.core.runtime.IExtensionDelta delta : deltas)
+ {
+ // TODO Handle ExtensionDelta
+ OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$
+ }
+ }
+ };
+
+ extensionRegistry.addRegistryChangeListener(listener, NAMESPACE);
+ extensionRegistryListener = listener;
+ }
+
+ private void doDeactivateOSGi()
+ {
+ org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
+ .getExtensionRegistry();
+ if (extensionRegistry == null)
+ {
+ return;
+ }
+
+ extensionRegistry
+ .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java index c992c1e257..04f569d54e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java @@ -1,127 +1,127 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.factory; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.factory.FactoryDescriptor; -import org.eclipse.net4j.util.factory.IFactory; -import org.eclipse.net4j.util.factory.IFactoryKey; -import org.eclipse.net4j.util.registry.HashMapRegistry; - -/** - * @author Eike Stepper - */ -public class PluginFactoryRegistry extends HashMapRegistry<IFactoryKey, IFactory> -{ - public static final String NAMESPACE = OM.BUNDLE_ID; - - public static final String EXT_POINT = "factories"; //$NON-NLS-1$ - - private Object extensionRegistryListener; - - public PluginFactoryRegistry() - { - } - - @Override - public IFactory get(Object key) - { - IFactory factory = super.get(key); - if (factory instanceof FactoryDescriptor) - { - FactoryDescriptor descriptor = (FactoryDescriptor)factory; - factory = descriptor.createFactory(); - } - - return factory; - } - - public void registerFactory(FactoryDescriptor factory) - { - put(factory.getKey(), factory); - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - try - { - doActivateOSGi(); - } - catch (Throwable t) - { - OM.LOG.warn(t); - } - } - - @Override - protected void doDeactivate() throws Exception - { - try - { - doDeactivateOSGi(); - } - catch (Throwable t) - { - OM.LOG.warn(t); - } - - clear(); - super.doDeactivate(); - } - - private void doActivateOSGi() - { - org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform - .getExtensionRegistry(); - if (extensionRegistry == null) - { - return; - } - - org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor( - NAMESPACE, EXT_POINT); - for (org.eclipse.core.runtime.IConfigurationElement element : elements) - { - registerFactory(new FactoryDescriptor(element)); - } - - org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener() - { - public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event) - { - org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT); - for (org.eclipse.core.runtime.IExtensionDelta delta : deltas) - { - // TODO Handle ExtensionDelta - OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$ - } - } - }; - - extensionRegistry.addRegistryChangeListener(listener, NAMESPACE); - extensionRegistryListener = listener; - } - - private void doDeactivateOSGi() - { - org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform - .getExtensionRegistry(); - if (extensionRegistry == null) - { - return; - } - - extensionRegistry - .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.factory;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.factory.FactoryDescriptor;
+import org.eclipse.net4j.util.factory.IFactory;
+import org.eclipse.net4j.util.factory.IFactoryKey;
+import org.eclipse.net4j.util.registry.HashMapRegistry;
+
+/**
+ * @author Eike Stepper
+ */
+public class PluginFactoryRegistry extends HashMapRegistry<IFactoryKey, IFactory>
+{
+ public static final String NAMESPACE = OM.BUNDLE_ID;
+
+ public static final String EXT_POINT = "factories"; //$NON-NLS-1$
+
+ private Object extensionRegistryListener;
+
+ public PluginFactoryRegistry()
+ {
+ }
+
+ @Override
+ public IFactory get(Object key)
+ {
+ IFactory factory = super.get(key);
+ if (factory instanceof FactoryDescriptor)
+ {
+ FactoryDescriptor descriptor = (FactoryDescriptor)factory;
+ factory = descriptor.createFactory();
+ }
+
+ return factory;
+ }
+
+ public void registerFactory(FactoryDescriptor factory)
+ {
+ put(factory.getKey(), factory);
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ try
+ {
+ doActivateOSGi();
+ }
+ catch (Throwable t)
+ {
+ OM.LOG.warn(t);
+ }
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ try
+ {
+ doDeactivateOSGi();
+ }
+ catch (Throwable t)
+ {
+ OM.LOG.warn(t);
+ }
+
+ clear();
+ super.doDeactivate();
+ }
+
+ private void doActivateOSGi()
+ {
+ org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
+ .getExtensionRegistry();
+ if (extensionRegistry == null)
+ {
+ return;
+ }
+
+ org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor(
+ NAMESPACE, EXT_POINT);
+ for (org.eclipse.core.runtime.IConfigurationElement element : elements)
+ {
+ registerFactory(new FactoryDescriptor(element));
+ }
+
+ org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener()
+ {
+ public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event)
+ {
+ org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT);
+ for (org.eclipse.core.runtime.IExtensionDelta delta : deltas)
+ {
+ // TODO Handle ExtensionDelta
+ OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$
+ }
+ }
+ };
+
+ extensionRegistry.addRegistryChangeListener(listener, NAMESPACE);
+ extensionRegistryListener = listener;
+ }
+
+ private void doDeactivateOSGi()
+ {
+ org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
+ .getExtensionRegistry();
+ if (extensionRegistry == null)
+ {
+ return;
+ }
+
+ extensionRegistry
+ .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java index d793bfd388..2cfb67bb15 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java @@ -1,343 +1,343 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om; - -import org.eclipse.net4j.internal.util.bundle.AbstractBundle; -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.ReflectUtil; -import org.eclipse.net4j.util.StringUtil; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.io.IOUtil; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -/** - * @author Eike Stepper - */ -public class LegacyBundle extends AbstractBundle -{ - private URL baseURL; - - public LegacyBundle(AbstractPlatform platform, String bundleID, Class<?> accessor) - { - super(platform, bundleID, accessor); - - try - { - computeBaseURL(accessor); - if (baseURL == null) - { - throw new IllegalStateException("No base URL"); - } - - loadOptions(); - } - catch (Exception ex) - { - IOUtil.print(ex); - } - } - - public String getStateLocation() - { - return new File(getPlatform().getStateFolder(), ".plugins/" + getBundleID()).getAbsolutePath(); //$NON-NLS-1$ - } - - public URL getBaseURL() - { - return baseURL; - } - - public Iterator<Class<?>> getClasses() - { - List<Class<?>> result = new ArrayList<Class<?>>(); - - if (isArchiveProtocol(baseURL.getProtocol())) - { - JarFile jarFile = null; - - try - { - jarFile = new JarFile(baseURL.getFile()); - - Enumeration<JarEntry> entries = jarFile.entries(); - while (entries.hasMoreElements()) - { - JarEntry jarEntry = entries.nextElement(); - if (!jarEntry.isDirectory()) - { - Class<?> c = getClassFromBundle(jarEntry.getName()); - if (c != null) - { - result.add(c); - } - } - } - } - catch (IOException ex) - { - throw WrappedException.wrap(ex); - } - finally - { - if (jarFile != null) - { - try - { - jarFile.close(); - } - catch (IOException ex) - { - throw WrappedException.wrap(ex); - } - } - } - } - else - { - try - { - URL url = getClassesURL(getAccessor()); - File folder = new File(url.getFile()); - collectFileClasses(folder, null, result); - } - catch (MalformedURLException ex) - { - throw WrappedException.wrap(ex); - } - } - - return result.iterator(); - } - - private void collectFileClasses(File folder, String path, List<Class<?>> result) - { - File file = folder; - if (path == null) - { - path = ""; - } - else - { - file = new File(folder, path); - } - - if (file.isDirectory()) - { - for (String child : file.list()) - { - collectFileClasses(folder, path + "/" + child, result); - } - } - else - { - Class<?> c = getClassFromBundle(path); - if (c != null) - { - result.add(c); - } - } - } - - private void loadOptions() - { - InputStream inputStream = null; - Properties properties = new Properties(); - - try - { - final String prefix = getBundleID() + "/"; //$NON-NLS-1$ - final int length = prefix.length(); - - inputStream = getInputStream(".options"); //$NON-NLS-1$ - properties.load(inputStream); - - for (Entry<Object, Object> entry : properties.entrySet()) - { - try - { - String key = (String)entry.getKey(); - if (key.startsWith(prefix)) - { - String value = (String)entry.getValue(); - setDebugOption(key.substring(length), value); - } - } - catch (RuntimeException ignore) - { - } - } - } - catch (IOException ignore) - { - } - finally - { - IOUtil.closeSilent(inputStream); - } - } - - private void computeBaseURL(Class<?> accessor) throws MalformedURLException - { - // Determine the URL for the class itself. The URL will be of one of the - // following forms, so there are a few good places to consider looking for - // the plugin.properties. - // - // For a plugin.xml with runtime="common.jar": - // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/common.jar!/org/eclipse/common/ - // CommonPlugin.class - // - // For a plugin.xml with runtime="runtime/common.jar": - // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/runtime/common.jar!/org/eclipse/common - // /CommonPlugin.class - // - // For a plugin.xml with runtime="." where the plugin is jarred: - // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common.jar!/org/eclipse/common/CommonPlugin. - // class - // - // For a plugin.xml with runtime="." where the plugin is not jarred. - // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/org/eclipse/emf/common/CommonPlugin.class - // - // Running in PDE with bin on classpath: - // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/bin/org/eclipse/emf/common/CommonPlugin. - // class - - URL url = getClassesURL(accessor); - - // For an archive URI, check for the plugin.properties in the archive. - if (isArchiveProtocol(url.getProtocol())) - { - try - { - // If we can open an input stream, then the plugin.properties is there, - // and we have a good base URL. - URL u = new URL(url.toString() + "plugin.properties"); - InputStream inputStream = null; - - try - { - inputStream = u.openStream(); - } - finally - { - IOUtil.close(inputStream); - } - - baseURL = url; - } - catch (IOException exception) - { - // If the plugin.properties isn't within the root of the archive, create - // a new URI for the folder location of the archive, so we can look in - // the folder that contains it. - url = trimSegments(new URL(url.getFile()), 1); - } - } - - // If we didn't find the plugin.properties in the usual place nor in the - // archive... - if (baseURL == null) - { - // Trim off the "bin" or "runtime" segment. - String lastSegment = lastSegment(url); - if ("bin".equals(lastSegment) || "runtime".equals(lastSegment)) //$NON-NLS-1$ //$NON-NLS-2$ - { - url = trimSegments(url, 1); - } - - try - { - // If we can open an input stream, then the plugin.properties is in the - // folder, and we have a good base URL. - InputStream inputStream = new URL(url.toString() + "plugin.properties").openStream(); //$NON-NLS-1$ - inputStream.close(); - baseURL = url; - } - catch (IOException exception) - { - } - } - - // If we still don't have a good base URL, complain about it. - if (baseURL == null) - { - throw new MissingResourceException("Missing properties: " + accessor.getName(), accessor.getName(), //$NON-NLS-1$ - "plugin.properties"); //$NON-NLS-1$ - } - } - - private static URL getClassesURL(Class<?> accessor) throws MalformedURLException - { - String className = accessor.getName(); - URL url = accessor.getResource(ReflectUtil.getSimpleName(accessor) + ".class"); //$NON-NLS-1$ - - int segmentsToTrim = 1 + StringUtil.occurrences(className, '.'); - return trimSegments(url, segmentsToTrim); - } - - private static String lastSegment(URL url) - { - String path = url.getPath(); - if (path.endsWith("/")) //$NON-NLS-1$ - { - path = path.substring(0, path.length() - 1); - } - - int pos = path.lastIndexOf('/'); - return pos == -1 ? path : path.substring(pos + 1); - } - - private static URL trimSegments(URL url, int count) throws MalformedURLException - { - String path = url.getPath(); - if (path.endsWith("/")) //$NON-NLS-1$ - { - ++count; - } - - for (int i = 0; i < count; i++) - { - int pos = path.lastIndexOf('/'); - if (pos == -1) - { - break; - } - - // TODO Optimize - path = path.substring(0, pos); - } - - return new URL(url.getProtocol() + ":" + path + "/"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /** - * TODO Make configurable - * - * @see org.eclipse.emf.common.util.URI#isArchiveScheme(String) - */ - private static boolean isArchiveProtocol(String scheme) - { - return "jar".equalsIgnoreCase(scheme); //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.ReflectUtil;
+import org.eclipse.net4j.util.StringUtil;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.io.IOUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.MissingResourceException;
+import java.util.Properties;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ * @author Eike Stepper
+ */
+public class LegacyBundle extends AbstractBundle
+{
+ private URL baseURL;
+
+ public LegacyBundle(AbstractPlatform platform, String bundleID, Class<?> accessor)
+ {
+ super(platform, bundleID, accessor);
+
+ try
+ {
+ computeBaseURL(accessor);
+ if (baseURL == null)
+ {
+ throw new IllegalStateException("No base URL");
+ }
+
+ loadOptions();
+ }
+ catch (Exception ex)
+ {
+ IOUtil.print(ex);
+ }
+ }
+
+ public String getStateLocation()
+ {
+ return new File(getPlatform().getStateFolder(), ".plugins/" + getBundleID()).getAbsolutePath(); //$NON-NLS-1$
+ }
+
+ public URL getBaseURL()
+ {
+ return baseURL;
+ }
+
+ public Iterator<Class<?>> getClasses()
+ {
+ List<Class<?>> result = new ArrayList<Class<?>>();
+
+ if (isArchiveProtocol(baseURL.getProtocol()))
+ {
+ JarFile jarFile = null;
+
+ try
+ {
+ jarFile = new JarFile(baseURL.getFile());
+
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements())
+ {
+ JarEntry jarEntry = entries.nextElement();
+ if (!jarEntry.isDirectory())
+ {
+ Class<?> c = getClassFromBundle(jarEntry.getName());
+ if (c != null)
+ {
+ result.add(c);
+ }
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ if (jarFile != null)
+ {
+ try
+ {
+ jarFile.close();
+ }
+ catch (IOException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+ }
+ }
+ else
+ {
+ try
+ {
+ URL url = getClassesURL(getAccessor());
+ File folder = new File(url.getFile());
+ collectFileClasses(folder, null, result);
+ }
+ catch (MalformedURLException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ return result.iterator();
+ }
+
+ private void collectFileClasses(File folder, String path, List<Class<?>> result)
+ {
+ File file = folder;
+ if (path == null)
+ {
+ path = "";
+ }
+ else
+ {
+ file = new File(folder, path);
+ }
+
+ if (file.isDirectory())
+ {
+ for (String child : file.list())
+ {
+ collectFileClasses(folder, path + "/" + child, result);
+ }
+ }
+ else
+ {
+ Class<?> c = getClassFromBundle(path);
+ if (c != null)
+ {
+ result.add(c);
+ }
+ }
+ }
+
+ private void loadOptions()
+ {
+ InputStream inputStream = null;
+ Properties properties = new Properties();
+
+ try
+ {
+ final String prefix = getBundleID() + "/"; //$NON-NLS-1$
+ final int length = prefix.length();
+
+ inputStream = getInputStream(".options"); //$NON-NLS-1$
+ properties.load(inputStream);
+
+ for (Entry<Object, Object> entry : properties.entrySet())
+ {
+ try
+ {
+ String key = (String)entry.getKey();
+ if (key.startsWith(prefix))
+ {
+ String value = (String)entry.getValue();
+ setDebugOption(key.substring(length), value);
+ }
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+ }
+ catch (IOException ignore)
+ {
+ }
+ finally
+ {
+ IOUtil.closeSilent(inputStream);
+ }
+ }
+
+ private void computeBaseURL(Class<?> accessor) throws MalformedURLException
+ {
+ // Determine the URL for the class itself. The URL will be of one of the
+ // following forms, so there are a few good places to consider looking for
+ // the plugin.properties.
+ //
+ // For a plugin.xml with runtime="common.jar":
+ // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/common.jar!/org/eclipse/common/
+ // CommonPlugin.class
+ //
+ // For a plugin.xml with runtime="runtime/common.jar":
+ // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/runtime/common.jar!/org/eclipse/common
+ // /CommonPlugin.class
+ //
+ // For a plugin.xml with runtime="." where the plugin is jarred:
+ // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common.jar!/org/eclipse/common/CommonPlugin.
+ // class
+ //
+ // For a plugin.xml with runtime="." where the plugin is not jarred.
+ // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/org/eclipse/emf/common/CommonPlugin.class
+ //
+ // Running in PDE with bin on classpath:
+ // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/bin/org/eclipse/emf/common/CommonPlugin.
+ // class
+
+ URL url = getClassesURL(accessor);
+
+ // For an archive URI, check for the plugin.properties in the archive.
+ if (isArchiveProtocol(url.getProtocol()))
+ {
+ try
+ {
+ // If we can open an input stream, then the plugin.properties is there,
+ // and we have a good base URL.
+ URL u = new URL(url.toString() + "plugin.properties");
+ InputStream inputStream = null;
+
+ try
+ {
+ inputStream = u.openStream();
+ }
+ finally
+ {
+ IOUtil.close(inputStream);
+ }
+
+ baseURL = url;
+ }
+ catch (IOException exception)
+ {
+ // If the plugin.properties isn't within the root of the archive, create
+ // a new URI for the folder location of the archive, so we can look in
+ // the folder that contains it.
+ url = trimSegments(new URL(url.getFile()), 1);
+ }
+ }
+
+ // If we didn't find the plugin.properties in the usual place nor in the
+ // archive...
+ if (baseURL == null)
+ {
+ // Trim off the "bin" or "runtime" segment.
+ String lastSegment = lastSegment(url);
+ if ("bin".equals(lastSegment) || "runtime".equals(lastSegment)) //$NON-NLS-1$ //$NON-NLS-2$
+ {
+ url = trimSegments(url, 1);
+ }
+
+ try
+ {
+ // If we can open an input stream, then the plugin.properties is in the
+ // folder, and we have a good base URL.
+ InputStream inputStream = new URL(url.toString() + "plugin.properties").openStream(); //$NON-NLS-1$
+ inputStream.close();
+ baseURL = url;
+ }
+ catch (IOException exception)
+ {
+ }
+ }
+
+ // If we still don't have a good base URL, complain about it.
+ if (baseURL == null)
+ {
+ throw new MissingResourceException("Missing properties: " + accessor.getName(), accessor.getName(), //$NON-NLS-1$
+ "plugin.properties"); //$NON-NLS-1$
+ }
+ }
+
+ private static URL getClassesURL(Class<?> accessor) throws MalformedURLException
+ {
+ String className = accessor.getName();
+ URL url = accessor.getResource(ReflectUtil.getSimpleName(accessor) + ".class"); //$NON-NLS-1$
+
+ int segmentsToTrim = 1 + StringUtil.occurrences(className, '.');
+ return trimSegments(url, segmentsToTrim);
+ }
+
+ private static String lastSegment(URL url)
+ {
+ String path = url.getPath();
+ if (path.endsWith("/")) //$NON-NLS-1$
+ {
+ path = path.substring(0, path.length() - 1);
+ }
+
+ int pos = path.lastIndexOf('/');
+ return pos == -1 ? path : path.substring(pos + 1);
+ }
+
+ private static URL trimSegments(URL url, int count) throws MalformedURLException
+ {
+ String path = url.getPath();
+ if (path.endsWith("/")) //$NON-NLS-1$
+ {
+ ++count;
+ }
+
+ for (int i = 0; i < count; i++)
+ {
+ int pos = path.lastIndexOf('/');
+ if (pos == -1)
+ {
+ break;
+ }
+
+ // TODO Optimize
+ path = path.substring(0, pos);
+ }
+
+ return new URL(url.getProtocol() + ":" + path + "/"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * TODO Make configurable
+ *
+ * @see org.eclipse.emf.common.util.URI#isArchiveScheme(String)
+ */
+ private static boolean isArchiveProtocol(String scheme)
+ {
+ return "jar".equalsIgnoreCase(scheme); //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java index 7d523705e6..f5df96131d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java @@ -1,58 +1,58 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om; - -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.om.LegacyUtil; -import org.eclipse.net4j.util.om.OMBundle; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author Eike Stepper - */ -public class LegacyPlatform extends AbstractPlatform -{ - private Map<String, String> debugOptions = new ConcurrentHashMap<String, String>(0); - - public LegacyPlatform() - { - } - - public boolean isOSGiRunning() - { - return false; - } - - @Override - protected OMBundle createBundle(String bundleID, Class<?> accessor) - { - return new LegacyBundle(this, bundleID, accessor); - } - - @Override - protected String getDebugOption(String bundleID, String option) - { - return debugOptions.get(bundleID + "/" + option); //$NON-NLS-1$ - } - - @Override - protected void setDebugOption(String bundleID, String option, String value) - { - debugOptions.put(bundleID + "/" + option, value); //$NON-NLS-1$ - } - - public String[] getCommandLineArgs() - { - return LegacyUtil.getCommandLineArgs(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.om.LegacyUtil;
+import org.eclipse.net4j.util.om.OMBundle;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @author Eike Stepper
+ */
+public class LegacyPlatform extends AbstractPlatform
+{
+ private Map<String, String> debugOptions = new ConcurrentHashMap<String, String>(0);
+
+ public LegacyPlatform()
+ {
+ }
+
+ public boolean isOSGiRunning()
+ {
+ return false;
+ }
+
+ @Override
+ protected OMBundle createBundle(String bundleID, Class<?> accessor)
+ {
+ return new LegacyBundle(this, bundleID, accessor);
+ }
+
+ @Override
+ protected String getDebugOption(String bundleID, String option)
+ {
+ return debugOptions.get(bundleID + "/" + option); //$NON-NLS-1$
+ }
+
+ @Override
+ protected void setDebugOption(String bundleID, String option, String value)
+ {
+ debugOptions.put(bundleID + "/" + option, value); //$NON-NLS-1$
+ }
+
+ public String[] getCommandLineArgs()
+ {
+ return LegacyUtil.getCommandLineArgs();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java index 5c965fa0e1..ed6d5bd4d1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java @@ -1,116 +1,116 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om; - -import org.eclipse.net4j.internal.util.bundle.AbstractBundle; -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.collection.AbstractIterator; - -import org.eclipse.core.runtime.FileLocator; -import org.eclipse.core.runtime.Platform; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; - -import java.io.IOException; -import java.net.URL; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Queue; - -/** - * @author Eike Stepper - */ -public class OSGiBundle extends AbstractBundle -{ - public OSGiBundle(AbstractPlatform platform, String bundleID, Class<?> accessor) - { - super(platform, bundleID, accessor); - } - - @Override - public BundleContext getBundleContext() - { - return (BundleContext)super.getBundleContext(); - } - - public URL getBaseURL() - { - try - { - URL entry = getBundleContext().getBundle().getEntry("/"); //$NON-NLS-1$ - URL baseURL = FileLocator.resolve(entry); - String str = baseURL.toExternalForm(); - if (str.endsWith("/./")) //$NON-NLS-1$ - { - baseURL = new URL(str.substring(0, str.length() - 2)); - } - - return baseURL; - } - catch (IOException ex) - { - throw WrappedException.wrap(ex); - } - } - - public Iterator<Class<?>> getClasses() - { - final Queue<String> folders = new LinkedList<String>(); - folders.offer("/"); - - return new AbstractIterator<Class<?>>() - { - private Enumeration<String> entryPaths; - - @Override - protected Object computeNextElement() - { - for (;;) - { - while (entryPaths != null && entryPaths.hasMoreElements()) - { - String entryPath = entryPaths.nextElement(); - if (entryPath.endsWith("/")) - { - folders.offer(entryPath); - } - else - { - Class<?> c = getClassFromBundle(entryPath); - if (c != null) - { - return c; - } - } - } - - String folder = folders.poll(); - if (folder == null) - { - return END_OF_DATA; - } - - Bundle bundle = getBundleContext().getBundle(); - entryPaths = bundle.getEntryPaths(folder); - } - } - }; - } - - public String getStateLocation() - { - Bundle bundle = getBundleContext().getBundle(); - return Platform.getStateLocation(bundle).toString(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.collection.AbstractIterator;
+
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.Platform;
+
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Queue;
+
+/**
+ * @author Eike Stepper
+ */
+public class OSGiBundle extends AbstractBundle
+{
+ public OSGiBundle(AbstractPlatform platform, String bundleID, Class<?> accessor)
+ {
+ super(platform, bundleID, accessor);
+ }
+
+ @Override
+ public BundleContext getBundleContext()
+ {
+ return (BundleContext)super.getBundleContext();
+ }
+
+ public URL getBaseURL()
+ {
+ try
+ {
+ URL entry = getBundleContext().getBundle().getEntry("/"); //$NON-NLS-1$
+ URL baseURL = FileLocator.resolve(entry);
+ String str = baseURL.toExternalForm();
+ if (str.endsWith("/./")) //$NON-NLS-1$
+ {
+ baseURL = new URL(str.substring(0, str.length() - 2));
+ }
+
+ return baseURL;
+ }
+ catch (IOException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public Iterator<Class<?>> getClasses()
+ {
+ final Queue<String> folders = new LinkedList<String>();
+ folders.offer("/");
+
+ return new AbstractIterator<Class<?>>()
+ {
+ private Enumeration<String> entryPaths;
+
+ @Override
+ protected Object computeNextElement()
+ {
+ for (;;)
+ {
+ while (entryPaths != null && entryPaths.hasMoreElements())
+ {
+ String entryPath = entryPaths.nextElement();
+ if (entryPath.endsWith("/"))
+ {
+ folders.offer(entryPath);
+ }
+ else
+ {
+ Class<?> c = getClassFromBundle(entryPath);
+ if (c != null)
+ {
+ return c;
+ }
+ }
+ }
+
+ String folder = folders.poll();
+ if (folder == null)
+ {
+ return END_OF_DATA;
+ }
+
+ Bundle bundle = getBundleContext().getBundle();
+ entryPaths = bundle.getEntryPaths(folder);
+ }
+ }
+ };
+ }
+
+ public String getStateLocation()
+ {
+ Bundle bundle = getBundleContext().getBundle();
+ return Platform.getStateLocation(bundle).toString();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java index 22e05b4e4c..e32483f1c9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java @@ -1,109 +1,109 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om; - -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.om.OMBundle; - -import org.eclipse.core.runtime.Platform; -import org.eclipse.osgi.service.debug.DebugOptions; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; - -/** - * @author Eike Stepper - */ -public class OSGiPlatform extends AbstractPlatform -{ - BundleContext systemContext; - - public OSGiPlatform(Object systemContext) - { - this.systemContext = (BundleContext)systemContext; - - try - { - setDebugging(Platform.inDebugMode()); - } - catch (Throwable ignore) - { - } - } - - public boolean isOSGiRunning() - { - return true; - } - - @Override - public String getProperty(String key) - { - return systemContext != null ? systemContext.getProperty(key) : null; - } - - @Override - public String getProperty(String key, String defaultValue) - { - String property = getProperty(key); - return property != null ? property : defaultValue; - } - - public String[] getCommandLineArgs() - { - return Platform.getCommandLineArgs(); - } - - public void setCommandLineArgs(String[] args) - { - throw new UnsupportedOperationException("Set command line arguements inside the OSGi enviorment is not needed."); - } - - @Override - protected OMBundle createBundle(String bundleID, Class<?> accessor) - { - return new OSGiBundle(this, bundleID, accessor); - } - - @Override - protected String getDebugOption(String bundleID, String option) - { - try - { - DebugOptions debugOptions = getDebugOptions(); - return debugOptions.getOption(bundleID + "/" + option); //$NON-NLS-1$ - } - catch (RuntimeException ex) - { - return null; - } - } - - @Override - protected void setDebugOption(String bundleID, String option, String value) - { - try - { - DebugOptions debugOptions = getDebugOptions(); - debugOptions.setOption(bundleID + "/" + option, value); //$NON-NLS-1$ - } - catch (RuntimeException ex) - { - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected DebugOptions getDebugOptions() throws NoClassDefFoundError, NullPointerException - { - ServiceReference ref = systemContext.getServiceReference(DebugOptions.class.getName()); - return (DebugOptions)systemContext.getService(ref); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.om.OMBundle;
+
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.osgi.service.debug.DebugOptions;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+
+/**
+ * @author Eike Stepper
+ */
+public class OSGiPlatform extends AbstractPlatform
+{
+ BundleContext systemContext;
+
+ public OSGiPlatform(Object systemContext)
+ {
+ this.systemContext = (BundleContext)systemContext;
+
+ try
+ {
+ setDebugging(Platform.inDebugMode());
+ }
+ catch (Throwable ignore)
+ {
+ }
+ }
+
+ public boolean isOSGiRunning()
+ {
+ return true;
+ }
+
+ @Override
+ public String getProperty(String key)
+ {
+ return systemContext != null ? systemContext.getProperty(key) : null;
+ }
+
+ @Override
+ public String getProperty(String key, String defaultValue)
+ {
+ String property = getProperty(key);
+ return property != null ? property : defaultValue;
+ }
+
+ public String[] getCommandLineArgs()
+ {
+ return Platform.getCommandLineArgs();
+ }
+
+ public void setCommandLineArgs(String[] args)
+ {
+ throw new UnsupportedOperationException("Set command line arguements inside the OSGi enviorment is not needed.");
+ }
+
+ @Override
+ protected OMBundle createBundle(String bundleID, Class<?> accessor)
+ {
+ return new OSGiBundle(this, bundleID, accessor);
+ }
+
+ @Override
+ protected String getDebugOption(String bundleID, String option)
+ {
+ try
+ {
+ DebugOptions debugOptions = getDebugOptions();
+ return debugOptions.getOption(bundleID + "/" + option); //$NON-NLS-1$
+ }
+ catch (RuntimeException ex)
+ {
+ return null;
+ }
+ }
+
+ @Override
+ protected void setDebugOption(String bundleID, String option, String value)
+ {
+ try
+ {
+ DebugOptions debugOptions = getDebugOptions();
+ debugOptions.setOption(bundleID + "/" + option, value); //$NON-NLS-1$
+ }
+ catch (RuntimeException ex)
+ {
+ }
+ }
+
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ protected DebugOptions getDebugOptions() throws NoClassDefFoundError, NullPointerException
+ {
+ ServiceReference ref = systemContext.getServiceReference(DebugOptions.class.getName());
+ return (DebugOptions)systemContext.getService(ref);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java index 241e61736b..cf413fb9a6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java @@ -1,95 +1,95 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -import org.eclipse.net4j.internal.util.bundle.OM; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; - -/** - * @author Eike Stepper - */ -public final class ArrayPreference extends Preference<String[]> -{ - private static final String SEPARATOR = ","; //$NON-NLS-1$ - - private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ - - public ArrayPreference(Preferences preferences, String name, String[] defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - String[] array = getValue(); - if (array == null || array.length == 0) - { - return null; - } - - StringBuilder builder = new StringBuilder(); - for (String element : array) - { - if (builder.length() != 0) - { - builder.append(SEPARATOR); - builder.append(" "); //$NON-NLS-1$ - } - - try - { - String encoded = URLEncoder.encode(element, UTF_8); - builder.append(encoded); - } - catch (UnsupportedEncodingException ex) - { - OM.LOG.error(ex); - return null; - } - } - - return builder.toString(); - } - - @Override - protected String[] convert(String value) - { - String[] array = value.split(SEPARATOR); - if (array == null || array.length == 0) - { - return Preferences.DEFAULT_ARRAY; - } - - for (int i = 0; i < array.length; i++) - { - try - { - array[i] = URLDecoder.decode(array[i].trim(), UTF_8); - } - catch (UnsupportedEncodingException ex) - { - OM.LOG.error(ex); - return null; - } - } - - return array; - } - - public Type getType() - { - return Type.ARRAY; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+
+/**
+ * @author Eike Stepper
+ */
+public final class ArrayPreference extends Preference<String[]>
+{
+ private static final String SEPARATOR = ","; //$NON-NLS-1$
+
+ private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
+
+ public ArrayPreference(Preferences preferences, String name, String[] defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ String[] array = getValue();
+ if (array == null || array.length == 0)
+ {
+ return null;
+ }
+
+ StringBuilder builder = new StringBuilder();
+ for (String element : array)
+ {
+ if (builder.length() != 0)
+ {
+ builder.append(SEPARATOR);
+ builder.append(" "); //$NON-NLS-1$
+ }
+
+ try
+ {
+ String encoded = URLEncoder.encode(element, UTF_8);
+ builder.append(encoded);
+ }
+ catch (UnsupportedEncodingException ex)
+ {
+ OM.LOG.error(ex);
+ return null;
+ }
+ }
+
+ return builder.toString();
+ }
+
+ @Override
+ protected String[] convert(String value)
+ {
+ String[] array = value.split(SEPARATOR);
+ if (array == null || array.length == 0)
+ {
+ return Preferences.DEFAULT_ARRAY;
+ }
+
+ for (int i = 0; i < array.length; i++)
+ {
+ try
+ {
+ array[i] = URLDecoder.decode(array[i].trim(), UTF_8);
+ }
+ catch (UnsupportedEncodingException ex)
+ {
+ OM.LOG.error(ex);
+ return null;
+ }
+ }
+
+ return array;
+ }
+
+ public Type getType()
+ {
+ return Type.ARRAY;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java index 416447fdd0..1167003eab 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -/** - * @author Eike Stepper - */ -public final class BooleanPreference extends Preference<Boolean> -{ - public BooleanPreference(Preferences preferences, String name, Boolean defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return Boolean.toString(getValue()); - } - - @Override - protected Boolean convert(String value) - { - return Boolean.parseBoolean(value); - } - - public Type getType() - { - return Type.BOOLEAN; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ */
+public final class BooleanPreference extends Preference<Boolean>
+{
+ public BooleanPreference(Preferences preferences, String name, Boolean defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return Boolean.toString(getValue());
+ }
+
+ @Override
+ protected Boolean convert(String value)
+ {
+ return Boolean.parseBoolean(value);
+ }
+
+ public Type getType()
+ {
+ return Type.BOOLEAN;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java index 008daf3e58..bec70ea622 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java @@ -1,41 +1,41 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -import org.eclipse.net4j.util.HexUtil; - -/** - * @author Eike Stepper - */ -public final class BytesPreference extends Preference<byte[]> -{ - public BytesPreference(Preferences preferences, String name, byte[] defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return HexUtil.bytesToHex(getValue()); - } - - @Override - protected byte[] convert(String value) - { - return HexUtil.hexToBytes(value); - } - - public Type getType() - { - return Type.BYTES; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+import org.eclipse.net4j.util.HexUtil;
+
+/**
+ * @author Eike Stepper
+ */
+public final class BytesPreference extends Preference<byte[]>
+{
+ public BytesPreference(Preferences preferences, String name, byte[] defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return HexUtil.bytesToHex(getValue());
+ }
+
+ @Override
+ protected byte[] convert(String value)
+ {
+ return HexUtil.hexToBytes(value);
+ }
+
+ public Type getType()
+ {
+ return Type.BYTES;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java index 324a1872e0..e3d9617f70 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -/** - * @author Eike Stepper - */ -public final class DoublePreference extends Preference<Double> -{ - public DoublePreference(Preferences preferences, String name, Double defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return Double.toString(getValue()); - } - - @Override - protected Double convert(String value) - { - return Double.parseDouble(value); - } - - public Type getType() - { - return Type.DOUBLE; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ */
+public final class DoublePreference extends Preference<Double>
+{
+ public DoublePreference(Preferences preferences, String name, Double defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return Double.toString(getValue());
+ }
+
+ @Override
+ protected Double convert(String value)
+ {
+ return Double.parseDouble(value);
+ }
+
+ public Type getType()
+ {
+ return Type.DOUBLE;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java index 9797b4462a..ae5b951b62 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -/** - * @author Eike Stepper - */ -public final class FloatPreference extends Preference<Float> -{ - public FloatPreference(Preferences preferences, String name, Float defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return Float.toString(getValue()); - } - - @Override - protected Float convert(String value) - { - return Float.parseFloat(value); - } - - public Type getType() - { - return Type.FLOAT; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ */
+public final class FloatPreference extends Preference<Float>
+{
+ public FloatPreference(Preferences preferences, String name, Float defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return Float.toString(getValue());
+ }
+
+ @Override
+ protected Float convert(String value)
+ {
+ return Float.parseFloat(value);
+ }
+
+ public Type getType()
+ {
+ return Type.FLOAT;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java index 97599599e0..bd5fe357ef 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -/** - * @author Eike Stepper - */ -public final class IntegerPreference extends Preference<Integer> -{ - public IntegerPreference(Preferences preferences, String name, Integer defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return Integer.toString(getValue()); - } - - @Override - protected Integer convert(String value) - { - return Integer.parseInt(value); - } - - public Type getType() - { - return Type.INTEGER; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ */
+public final class IntegerPreference extends Preference<Integer>
+{
+ public IntegerPreference(Preferences preferences, String name, Integer defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return Integer.toString(getValue());
+ }
+
+ @Override
+ protected Integer convert(String value)
+ {
+ return Integer.parseInt(value);
+ }
+
+ public Type getType()
+ {
+ return Type.INTEGER;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java index f6c69691b6..6607f71f4b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -/** - * @author Eike Stepper - */ -public final class LongPreference extends Preference<Long> -{ - public LongPreference(Preferences preferences, String name, Long defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return Long.toString(getValue()); - } - - @Override - protected Long convert(String value) - { - return Long.parseLong(value); - } - - public Type getType() - { - return Type.LONG; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ */
+public final class LongPreference extends Preference<Long>
+{
+ public LongPreference(Preferences preferences, String name, Long defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return Long.toString(getValue());
+ }
+
+ @Override
+ protected Long convert(String value)
+ {
+ return Long.parseLong(value);
+ }
+
+ public Type getType()
+ {
+ return Type.LONG;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java index ec84e5aab6..1c7edf0d14 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java @@ -1,121 +1,121 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -import org.eclipse.net4j.util.ObjectUtil; -import org.eclipse.net4j.util.om.pref.OMPreference; - -/** - * @author Eike Stepper - */ -public abstract class Preference<T> implements OMPreference<T> -{ - private Preferences preferences; - - private String name; - - private T defaultValue; - - private T value; - - public Preference(Preferences preferences, String name, T defaultValue) - { - if (defaultValue == null) - { - throw new IllegalArgumentException("defaultValue == null"); //$NON-NLS-1$ - } - - this.preferences = preferences; - this.name = name; - this.defaultValue = defaultValue; - } - - public Preferences getPreferences() - { - return preferences; - } - - public String getName() - { - return name; - } - - public T getDefaultValue() - { - return defaultValue; - } - - public T getValue() - { - load(); - return value; - } - - public T setValue(T value) - { - if (value == null) - { - throw new IllegalArgumentException("value == null"); //$NON-NLS-1$ - } - - load(); - T oldValue = this.value; - if (!equals(oldValue, value)) - { - if (equals(defaultValue, value)) - { - value = defaultValue; - } - - this.value = value; - preferences.fireChangeEvent(this, oldValue, value); - return oldValue; - } - - return null; - } - - public boolean isSet() - { - return !equals(defaultValue, value); - } - - public T unSet() - { - return setValue(defaultValue); - } - - protected boolean equals(T v1, T v2) - { - return ObjectUtil.equals(v1, v2); - } - - protected void init(String value) - { - if (value == null) - { - this.value = defaultValue; - } - else - { - this.value = convert(value); - } - } - - protected abstract T convert(String value); - - protected abstract String getString(); - - private void load() - { - preferences.load(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+import org.eclipse.net4j.util.ObjectUtil;
+import org.eclipse.net4j.util.om.pref.OMPreference;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class Preference<T> implements OMPreference<T>
+{
+ private Preferences preferences;
+
+ private String name;
+
+ private T defaultValue;
+
+ private T value;
+
+ public Preference(Preferences preferences, String name, T defaultValue)
+ {
+ if (defaultValue == null)
+ {
+ throw new IllegalArgumentException("defaultValue == null"); //$NON-NLS-1$
+ }
+
+ this.preferences = preferences;
+ this.name = name;
+ this.defaultValue = defaultValue;
+ }
+
+ public Preferences getPreferences()
+ {
+ return preferences;
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public T getDefaultValue()
+ {
+ return defaultValue;
+ }
+
+ public T getValue()
+ {
+ load();
+ return value;
+ }
+
+ public T setValue(T value)
+ {
+ if (value == null)
+ {
+ throw new IllegalArgumentException("value == null"); //$NON-NLS-1$
+ }
+
+ load();
+ T oldValue = this.value;
+ if (!equals(oldValue, value))
+ {
+ if (equals(defaultValue, value))
+ {
+ value = defaultValue;
+ }
+
+ this.value = value;
+ preferences.fireChangeEvent(this, oldValue, value);
+ return oldValue;
+ }
+
+ return null;
+ }
+
+ public boolean isSet()
+ {
+ return !equals(defaultValue, value);
+ }
+
+ public T unSet()
+ {
+ return setValue(defaultValue);
+ }
+
+ protected boolean equals(T v1, T v2)
+ {
+ return ObjectUtil.equals(v1, v2);
+ }
+
+ protected void init(String value)
+ {
+ if (value == null)
+ {
+ this.value = defaultValue;
+ }
+ else
+ {
+ this.value = convert(value);
+ }
+ }
+
+ protected abstract T convert(String value);
+
+ protected abstract String getString();
+
+ private void load()
+ {
+ preferences.load();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java index c269de82d6..18f650667b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java @@ -1,297 +1,297 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -import org.eclipse.net4j.internal.util.bundle.AbstractBundle; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.Notifier; -import org.eclipse.net4j.util.io.IORunnable; -import org.eclipse.net4j.util.io.IORuntimeException; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.pref.OMPreference; -import org.eclipse.net4j.util.om.pref.OMPreferences; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * @author Eike Stepper - */ -public class Preferences extends Notifier implements OMPreferences -{ - private AbstractBundle bundle; - - private Map<String, Preference<?>> prefs = new HashMap<String, Preference<?>>(); - - private boolean loaded; - - private boolean dirty; - - public Preferences(AbstractBundle bundle) - { - this.bundle = bundle; - } - - public AbstractBundle getBundle() - { - return bundle; - } - - public synchronized void load() - { - if (!loaded) - { - loaded = true; - final Properties properties = new Properties(); - - File file = getFile(); - if (file.exists()) - { - IOUtil.safeInput(file, new IORunnable<FileInputStream>() - { - public void run(FileInputStream io) throws IOException - { - properties.load(io); - } - }); - } - - for (Preference<?> preference : prefs.values()) - { - String name = preference.getName(); - String value = properties.getProperty(name); - preference.init(value); - } - } - } - - public synchronized void save() - { - if (dirty) - { - final Properties properties = new Properties(); - for (Preference<?> preference : prefs.values()) - { - if (preference.isSet()) - { - String name = preference.getName(); - String value = preference.getString(); - if (value != null) - { - properties.put(name, value); - } - } - } - - File file = getFile(); - if (properties.isEmpty()) - { - if (file.exists()) - { - file.delete(); - } - } - else - { - IOUtil.safeOutput(file, new IORunnable<FileOutputStream>() - { - public void run(FileOutputStream io) throws IOException - { - properties.store(io, "Preferences of " + bundle.getBundleID()); //$NON-NLS-1$ - } - }); - } - - dirty = false; - } - } - - public boolean isDirty() - { - return dirty; - } - - public OMPreference<Boolean> init(String name, boolean defaultValue) - { - return init(new BooleanPreference(this, name, defaultValue)); - } - - public OMPreference<Integer> init(String name, int defaultValue) - { - return init(new IntegerPreference(this, name, defaultValue)); - } - - public OMPreference<Long> init(String name, long defaultValue) - { - return init(new LongPreference(this, name, defaultValue)); - } - - public OMPreference<Float> init(String name, float defaultValue) - { - return init(new FloatPreference(this, name, defaultValue)); - } - - public OMPreference<Double> init(String name, double defaultValue) - { - return init(new DoublePreference(this, name, defaultValue)); - } - - public OMPreference<String> init(String name, String defaultValue) - { - return init(new StringPreference(this, name, defaultValue)); - } - - public OMPreference<String[]> init(String name, String[] defaultValue) - { - return init(new ArrayPreference(this, name, defaultValue)); - } - - public OMPreference<byte[]> init(String name, byte[] defaultValue) - { - return init(new BytesPreference(this, name, defaultValue)); - } - - public OMPreference<Boolean> initBoolean(String name) - { - return init(name, DEFAULT_BOOLEAN); - } - - public OMPreference<Integer> initInteger(String name) - { - return init(name, DEFAULT_INTEGER); - } - - public OMPreference<Long> initLong(String name) - { - return init(name, DEFAULT_LONG); - } - - public OMPreference<Float> initFloat(String name) - { - return init(name, DEFAULT_FLOAT); - } - - public OMPreference<Double> initDouble(String name) - { - return init(name, DEFAULT_DOUBLE); - } - - public OMPreference<String> initString(String name) - { - return init(name, DEFAULT_STRING); - } - - public OMPreference<String[]> initArray(String name) - { - return init(name, DEFAULT_ARRAY); - } - - public OMPreference<byte[]> initBytes(String name) - { - return init(name, DEFAULT_BYTES); - } - - public boolean contains(String name) - { - return prefs.containsKey(name); - } - - public OMPreference<?> get(String name) - { - return prefs.get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<Boolean> getBoolean(String name) - { - return (OMPreference<Boolean>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<Integer> getInteger(String name) - { - return (OMPreference<Integer>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<Long> getLong(String name) - { - return (OMPreference<Long>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<Float> getFloat(String name) - { - return (OMPreference<Float>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<Double> getDouble(String name) - { - return (OMPreference<Double>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<String> getString(String name) - { - return (OMPreference<String>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<String[]> getArray(String name) - { - return (OMPreference<String[]>)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference<byte[]> getBytes(String name) - { - return (OMPreference<byte[]>)get(name); - } - - public <T> void fireChangeEvent(Preference<T> preference, T oldValue, T newValue) - { - dirty = true; - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new PreferencesChangeEvent<T>(preference, oldValue, newValue), listeners); - } - } - - private <T> OMPreference<T> init(Preference<T> preference) - { - String name = preference.getName(); - if (prefs.containsKey(name)) - { - throw new IllegalArgumentException("Duplicate name: " + name); //$NON-NLS-1$ - } - - prefs.put(name, preference); - return preference; - } - - private File getFile() - { - File file = new File(bundle.getStateLocation(), ".prefs"); //$NON-NLS-1$ - if (file.exists() && !file.isFile()) - { - throw new IORuntimeException("Not a file: " + file.getAbsolutePath()); //$NON-NLS-1$ - } - - return file; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.Notifier;
+import org.eclipse.net4j.util.io.IORunnable;
+import org.eclipse.net4j.util.io.IORuntimeException;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.pref.OMPreference;
+import org.eclipse.net4j.util.om.pref.OMPreferences;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * @author Eike Stepper
+ */
+public class Preferences extends Notifier implements OMPreferences
+{
+ private AbstractBundle bundle;
+
+ private Map<String, Preference<?>> prefs = new HashMap<String, Preference<?>>();
+
+ private boolean loaded;
+
+ private boolean dirty;
+
+ public Preferences(AbstractBundle bundle)
+ {
+ this.bundle = bundle;
+ }
+
+ public AbstractBundle getBundle()
+ {
+ return bundle;
+ }
+
+ public synchronized void load()
+ {
+ if (!loaded)
+ {
+ loaded = true;
+ final Properties properties = new Properties();
+
+ File file = getFile();
+ if (file.exists())
+ {
+ IOUtil.safeInput(file, new IORunnable<FileInputStream>()
+ {
+ public void run(FileInputStream io) throws IOException
+ {
+ properties.load(io);
+ }
+ });
+ }
+
+ for (Preference<?> preference : prefs.values())
+ {
+ String name = preference.getName();
+ String value = properties.getProperty(name);
+ preference.init(value);
+ }
+ }
+ }
+
+ public synchronized void save()
+ {
+ if (dirty)
+ {
+ final Properties properties = new Properties();
+ for (Preference<?> preference : prefs.values())
+ {
+ if (preference.isSet())
+ {
+ String name = preference.getName();
+ String value = preference.getString();
+ if (value != null)
+ {
+ properties.put(name, value);
+ }
+ }
+ }
+
+ File file = getFile();
+ if (properties.isEmpty())
+ {
+ if (file.exists())
+ {
+ file.delete();
+ }
+ }
+ else
+ {
+ IOUtil.safeOutput(file, new IORunnable<FileOutputStream>()
+ {
+ public void run(FileOutputStream io) throws IOException
+ {
+ properties.store(io, "Preferences of " + bundle.getBundleID()); //$NON-NLS-1$
+ }
+ });
+ }
+
+ dirty = false;
+ }
+ }
+
+ public boolean isDirty()
+ {
+ return dirty;
+ }
+
+ public OMPreference<Boolean> init(String name, boolean defaultValue)
+ {
+ return init(new BooleanPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<Integer> init(String name, int defaultValue)
+ {
+ return init(new IntegerPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<Long> init(String name, long defaultValue)
+ {
+ return init(new LongPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<Float> init(String name, float defaultValue)
+ {
+ return init(new FloatPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<Double> init(String name, double defaultValue)
+ {
+ return init(new DoublePreference(this, name, defaultValue));
+ }
+
+ public OMPreference<String> init(String name, String defaultValue)
+ {
+ return init(new StringPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<String[]> init(String name, String[] defaultValue)
+ {
+ return init(new ArrayPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<byte[]> init(String name, byte[] defaultValue)
+ {
+ return init(new BytesPreference(this, name, defaultValue));
+ }
+
+ public OMPreference<Boolean> initBoolean(String name)
+ {
+ return init(name, DEFAULT_BOOLEAN);
+ }
+
+ public OMPreference<Integer> initInteger(String name)
+ {
+ return init(name, DEFAULT_INTEGER);
+ }
+
+ public OMPreference<Long> initLong(String name)
+ {
+ return init(name, DEFAULT_LONG);
+ }
+
+ public OMPreference<Float> initFloat(String name)
+ {
+ return init(name, DEFAULT_FLOAT);
+ }
+
+ public OMPreference<Double> initDouble(String name)
+ {
+ return init(name, DEFAULT_DOUBLE);
+ }
+
+ public OMPreference<String> initString(String name)
+ {
+ return init(name, DEFAULT_STRING);
+ }
+
+ public OMPreference<String[]> initArray(String name)
+ {
+ return init(name, DEFAULT_ARRAY);
+ }
+
+ public OMPreference<byte[]> initBytes(String name)
+ {
+ return init(name, DEFAULT_BYTES);
+ }
+
+ public boolean contains(String name)
+ {
+ return prefs.containsKey(name);
+ }
+
+ public OMPreference<?> get(String name)
+ {
+ return prefs.get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<Boolean> getBoolean(String name)
+ {
+ return (OMPreference<Boolean>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<Integer> getInteger(String name)
+ {
+ return (OMPreference<Integer>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<Long> getLong(String name)
+ {
+ return (OMPreference<Long>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<Float> getFloat(String name)
+ {
+ return (OMPreference<Float>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<Double> getDouble(String name)
+ {
+ return (OMPreference<Double>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<String> getString(String name)
+ {
+ return (OMPreference<String>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<String[]> getArray(String name)
+ {
+ return (OMPreference<String[]>)get(name);
+ }
+
+ @SuppressWarnings("unchecked")
+ public OMPreference<byte[]> getBytes(String name)
+ {
+ return (OMPreference<byte[]>)get(name);
+ }
+
+ public <T> void fireChangeEvent(Preference<T> preference, T oldValue, T newValue)
+ {
+ dirty = true;
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new PreferencesChangeEvent<T>(preference, oldValue, newValue), listeners);
+ }
+ }
+
+ private <T> OMPreference<T> init(Preference<T> preference)
+ {
+ String name = preference.getName();
+ if (prefs.containsKey(name))
+ {
+ throw new IllegalArgumentException("Duplicate name: " + name); //$NON-NLS-1$
+ }
+
+ prefs.put(name, preference);
+ return preference;
+ }
+
+ private File getFile()
+ {
+ File file = new File(bundle.getStateLocation(), ".prefs"); //$NON-NLS-1$
+ if (file.exists() && !file.isFile())
+ {
+ throw new IORuntimeException("Not a file: " + file.getAbsolutePath()); //$NON-NLS-1$
+ }
+
+ return file;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java index 7040e28ab5..ff56a8291d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -import org.eclipse.net4j.util.event.Event; -import org.eclipse.net4j.util.om.pref.OMPreferencesChangeEvent; - -/** - * @author Eike Stepper - */ -public final class PreferencesChangeEvent<T> extends Event implements OMPreferencesChangeEvent<T> -{ - private static final long serialVersionUID = 1L; - - private Preference<T> preference; - - private T oldValue; - - private T newValue; - - public PreferencesChangeEvent(Preference<T> preference, T oldValue, T newValue) - { - super(preference.getPreferences()); - this.preference = preference; - this.oldValue = oldValue; - this.newValue = newValue; - } - - @Override - public Preferences getSource() - { - return (Preferences)super.getSource(); - } - - public Preference<T> getPreference() - { - return preference; - } - - public T getOldValue() - { - return oldValue; - } - - public T getNewValue() - { - return newValue; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+import org.eclipse.net4j.util.event.Event;
+import org.eclipse.net4j.util.om.pref.OMPreferencesChangeEvent;
+
+/**
+ * @author Eike Stepper
+ */
+public final class PreferencesChangeEvent<T> extends Event implements OMPreferencesChangeEvent<T>
+{
+ private static final long serialVersionUID = 1L;
+
+ private Preference<T> preference;
+
+ private T oldValue;
+
+ private T newValue;
+
+ public PreferencesChangeEvent(Preference<T> preference, T oldValue, T newValue)
+ {
+ super(preference.getPreferences());
+ this.preference = preference;
+ this.oldValue = oldValue;
+ this.newValue = newValue;
+ }
+
+ @Override
+ public Preferences getSource()
+ {
+ return (Preferences)super.getSource();
+ }
+
+ public Preference<T> getPreference()
+ {
+ return preference;
+ }
+
+ public T getOldValue()
+ {
+ return oldValue;
+ }
+
+ public T getNewValue()
+ {
+ return newValue;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java index 133e8f62ec..8038862b37 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.internal.util.om.pref; - -/** - * @author Eike Stepper - */ -public final class StringPreference extends Preference<String> -{ - public StringPreference(Preferences preferences, String name, String defaultValue) - { - super(preferences, name, defaultValue); - } - - @Override - protected String getString() - { - return getValue(); - } - - @Override - protected String convert(String value) - { - return value; - } - - public Type getType() - { - return Type.STRING; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.internal.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ */
+public final class StringPreference extends Preference<String>
+{
+ public StringPreference(Preferences preferences, String name, String defaultValue)
+ {
+ super(preferences, name, defaultValue);
+ }
+
+ @Override
+ protected String getString()
+ {
+ return getValue();
+ }
+
+ @Override
+ protected String convert(String value)
+ {
+ return value;
+ }
+
+ public Type getType()
+ {
+ return Type.STRING;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java index b5363c8438..d7604fa61b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java @@ -1,95 +1,95 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -/** - * Provides a single static {@link #adapt(Object, Class) adapt()} method that conveniently and safely wraps the - * Platform's adaptation framework. - * - * @author Eike Stepper - */ -public final class AdapterUtil -{ - private AdapterUtil() - { - } - - public static <TYPE> TYPE adapt(Object object, Class<TYPE> type) - { - if (object == null) - { - return null; - } - - Object adapter = null; - if (type.isInstance(object)) - { - adapter = object; - } - else - { - try - { - adapter = AdaptableHelper.adapt(object, type); - if (adapter == null) - { - adapter = AdapterManagerHelper.adapt(object, type); - } - } - catch (Throwable ignore) - { - } - } - - @SuppressWarnings("unchecked") - TYPE result = (TYPE)adapter; - return result; - } - - /** - * Nested class to factor out dependencies on org.eclipse.core.runtime - * - * @author Eike Stepper - */ - private static final class AdaptableHelper - { - public static Object adapt(Object object, Class<?> type) - { - if (object instanceof org.eclipse.core.runtime.IAdaptable) - { - return ((org.eclipse.core.runtime.IAdaptable)object).getAdapter(type); - } - - return null; - } - } - - /** - * Nested class to factor out dependencies on org.eclipse.core.runtime - * - * @author Eike Stepper - */ - private static final class AdapterManagerHelper - { - private static org.eclipse.core.runtime.IAdapterManager adapterManager = org.eclipse.core.runtime.Platform - .getAdapterManager(); - - public static Object adapt(Object object, Class<?> type) - { - if (adapterManager != null) - { - return adapterManager.getAdapter(object, type); - } - - return null; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+/**
+ * Provides a single static {@link #adapt(Object, Class) adapt()} method that conveniently and safely wraps the
+ * Platform's adaptation framework.
+ *
+ * @author Eike Stepper
+ */
+public final class AdapterUtil
+{
+ private AdapterUtil()
+ {
+ }
+
+ public static <TYPE> TYPE adapt(Object object, Class<TYPE> type)
+ {
+ if (object == null)
+ {
+ return null;
+ }
+
+ Object adapter = null;
+ if (type.isInstance(object))
+ {
+ adapter = object;
+ }
+ else
+ {
+ try
+ {
+ adapter = AdaptableHelper.adapt(object, type);
+ if (adapter == null)
+ {
+ adapter = AdapterManagerHelper.adapt(object, type);
+ }
+ }
+ catch (Throwable ignore)
+ {
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ TYPE result = (TYPE)adapter;
+ return result;
+ }
+
+ /**
+ * Nested class to factor out dependencies on org.eclipse.core.runtime
+ *
+ * @author Eike Stepper
+ */
+ private static final class AdaptableHelper
+ {
+ public static Object adapt(Object object, Class<?> type)
+ {
+ if (object instanceof org.eclipse.core.runtime.IAdaptable)
+ {
+ return ((org.eclipse.core.runtime.IAdaptable)object).getAdapter(type);
+ }
+
+ return null;
+ }
+ }
+
+ /**
+ * Nested class to factor out dependencies on org.eclipse.core.runtime
+ *
+ * @author Eike Stepper
+ */
+ private static final class AdapterManagerHelper
+ {
+ private static org.eclipse.core.runtime.IAdapterManager adapterManager = org.eclipse.core.runtime.Platform
+ .getAdapterManager();
+
+ public static Object adapt(Object object, Class<?> type)
+ {
+ if (adapterManager != null)
+ {
+ return adapterManager.getAdapter(object, type);
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java index 07c989df4a..bb37bb3984 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java @@ -1,64 +1,64 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -/** - * Provides static methods that check object states and invocation arguments. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public final class CheckUtil -{ - private CheckUtil() - { - } - - public static void checkNull(Object handle, String msg) throws NullPointerException - { - if (handle == null) - { - throw new NullPointerException(msg); - } - } - - public static void checkArg(boolean expr, String msg) throws IllegalArgumentException - { - if (!expr) - { - throw new IllegalArgumentException(msg); - } - } - - public static void checkArg(Object handle, String handleName) throws IllegalArgumentException - { - if (handle == null) - { - throw new IllegalArgumentException(handleName + " is null"); //$NON-NLS-1$ - } - } - - public static void checkState(boolean expr, String msg) throws IllegalStateException - { - if (!expr) - { - throw new IllegalStateException(msg); - } - } - - public static void checkState(Object handle, String handleName) throws IllegalStateException - { - if (handle == null) - { - throw new IllegalStateException(handleName + " is null"); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+/**
+ * Provides static methods that check object states and invocation arguments.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public final class CheckUtil
+{
+ private CheckUtil()
+ {
+ }
+
+ public static void checkNull(Object handle, String msg) throws NullPointerException
+ {
+ if (handle == null)
+ {
+ throw new NullPointerException(msg);
+ }
+ }
+
+ public static void checkArg(boolean expr, String msg) throws IllegalArgumentException
+ {
+ if (!expr)
+ {
+ throw new IllegalArgumentException(msg);
+ }
+ }
+
+ public static void checkArg(Object handle, String handleName) throws IllegalArgumentException
+ {
+ if (handle == null)
+ {
+ throw new IllegalArgumentException(handleName + " is null"); //$NON-NLS-1$
+ }
+ }
+
+ public static void checkState(boolean expr, String msg) throws IllegalStateException
+ {
+ if (!expr)
+ {
+ throw new IllegalStateException(msg);
+ }
+ }
+
+ public static void checkState(Object handle, String handleName) throws IllegalStateException
+ {
+ if (handle == null)
+ {
+ throw new IllegalStateException(handleName + " is null"); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java index 806037e177..e051534586 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java @@ -1,192 +1,192 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -import org.eclipse.net4j.util.io.IORuntimeException; - -import java.io.IOException; - -/** - * Provides static methods that convert to and from hexadecimal string formats. - * - * @author Eike Stepper - */ -public final class HexUtil -{ - public static final char DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', }; - - private HexUtil() - { - } - - /** - * Converts a byte array into a string of lower case hex chars. - * - * @param bs - * A byte array - * @param off - * The index of the first byte to read - * @param length - * The number of bytes to read. - * @return the string of hex chars. - */ - public static String bytesToHex(byte[] bs, int off, int length) - { - if (bs == null) - { - return null; - } - - if (bs.length <= off || bs.length < off + length) - { - throw new IllegalArgumentException(); - } - - StringBuilder sb = new StringBuilder(length * 2); - bytesToHexAppend(bs, off, length, sb); - return sb.toString(); - } - - public static void bytesToHexAppend(byte[] bs, int off, int length, Appendable appendable) - { - if (bs.length <= off || bs.length < off + length) - { - throw new IllegalArgumentException(); - } - - if (appendable instanceof StringBuffer) - { - StringBuffer buffer = (StringBuffer)appendable; - buffer.ensureCapacity(buffer.length() + length * 2); - } - - try - { - for (int i = off; i < off + length; i++) - { - appendable.append(Character.forDigit(bs[i] >>> 4 & 0xf, 16)); - appendable.append(Character.forDigit(bs[i] & 0xf, 16)); - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static String bytesToHex(byte[] bs) - { - if (bs == null) - { - return null; - } - - return bytesToHex(bs, 0, bs.length); - } - - public static byte[] hexToBytes(String s) - { - return hexToBytes(s, 0); - } - - public static byte[] hexToBytes(String s, int off) - { - byte[] bs = new byte[off + (1 + s.length()) / 2]; - hexToBytes(s, bs, off); - return bs; - } - - /** - * Converts a String of hex characters into an array of bytes. - * - * @param s - * A string of hex characters (upper case or lower) of even length. - * @param out - * A byte array of length at least s.length()/2 + off - * @param off - * The first byte to write of the array - */ - public static void hexToBytes(String s, byte[] out, int off) throws NumberFormatException, IndexOutOfBoundsException - { - int slen = s.length(); - if ((slen & 1) == 1) - { - s = '0' + s; - } - - if (out.length < off + (slen >> 1)) - { - throw new IndexOutOfBoundsException("Output buffer too small for input (" + out.length + '<' + off + (slen >> 1) //$NON-NLS-1$ - + ')'); - } - - // Safe to assume the string is even length - byte b1, b2; - for (int i = 0; i < slen; i += 2) - { - b1 = (byte)Character.digit(s.charAt(i), 16); - b2 = (byte)Character.digit(s.charAt(i + 1), 16); - if (b1 < 0 || b2 < 0) - { - throw new NumberFormatException(s); - } - - out[off + i / 2] = (byte)(b1 << 4 | b2); - } - } - - public static String longToHex(long v) - { - final String hex = Long.toHexString(v); - if (hex.length() < 8) - { - return "00000000".substring(hex.length()) + hex; //$NON-NLS-1$ - } - - return hex; - } - - @Deprecated - public static String formatByte(int b) - { - assertByte(b); - return "" + DIGITS[b >> 4] + DIGITS[b & 0xf]; //$NON-NLS-1$ - } - - @Deprecated - public static String formatBytes(byte[] bytes) - { - StringBuilder builder = new StringBuilder(); - for (byte b : bytes) - { - appendHex(builder, b - Byte.MIN_VALUE); - } - - return builder.toString(); - } - - @Deprecated - public static void appendHex(StringBuilder builder, int b) - { - assertByte(b); - builder.append(DIGITS[b >> 4]); - builder.append(DIGITS[b & 0xf]); - } - - @Deprecated - private static void assertByte(int b) - { - if (b < 0 || b > 255) - { - throw new IllegalArgumentException("b=" + b); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+import org.eclipse.net4j.util.io.IORuntimeException;
+
+import java.io.IOException;
+
+/**
+ * Provides static methods that convert to and from hexadecimal string formats.
+ *
+ * @author Eike Stepper
+ */
+public final class HexUtil
+{
+ public static final char DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', };
+
+ private HexUtil()
+ {
+ }
+
+ /**
+ * Converts a byte array into a string of lower case hex chars.
+ *
+ * @param bs
+ * A byte array
+ * @param off
+ * The index of the first byte to read
+ * @param length
+ * The number of bytes to read.
+ * @return the string of hex chars.
+ */
+ public static String bytesToHex(byte[] bs, int off, int length)
+ {
+ if (bs == null)
+ {
+ return null;
+ }
+
+ if (bs.length <= off || bs.length < off + length)
+ {
+ throw new IllegalArgumentException();
+ }
+
+ StringBuilder sb = new StringBuilder(length * 2);
+ bytesToHexAppend(bs, off, length, sb);
+ return sb.toString();
+ }
+
+ public static void bytesToHexAppend(byte[] bs, int off, int length, Appendable appendable)
+ {
+ if (bs.length <= off || bs.length < off + length)
+ {
+ throw new IllegalArgumentException();
+ }
+
+ if (appendable instanceof StringBuffer)
+ {
+ StringBuffer buffer = (StringBuffer)appendable;
+ buffer.ensureCapacity(buffer.length() + length * 2);
+ }
+
+ try
+ {
+ for (int i = off; i < off + length; i++)
+ {
+ appendable.append(Character.forDigit(bs[i] >>> 4 & 0xf, 16));
+ appendable.append(Character.forDigit(bs[i] & 0xf, 16));
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static String bytesToHex(byte[] bs)
+ {
+ if (bs == null)
+ {
+ return null;
+ }
+
+ return bytesToHex(bs, 0, bs.length);
+ }
+
+ public static byte[] hexToBytes(String s)
+ {
+ return hexToBytes(s, 0);
+ }
+
+ public static byte[] hexToBytes(String s, int off)
+ {
+ byte[] bs = new byte[off + (1 + s.length()) / 2];
+ hexToBytes(s, bs, off);
+ return bs;
+ }
+
+ /**
+ * Converts a String of hex characters into an array of bytes.
+ *
+ * @param s
+ * A string of hex characters (upper case or lower) of even length.
+ * @param out
+ * A byte array of length at least s.length()/2 + off
+ * @param off
+ * The first byte to write of the array
+ */
+ public static void hexToBytes(String s, byte[] out, int off) throws NumberFormatException, IndexOutOfBoundsException
+ {
+ int slen = s.length();
+ if ((slen & 1) == 1)
+ {
+ s = '0' + s;
+ }
+
+ if (out.length < off + (slen >> 1))
+ {
+ throw new IndexOutOfBoundsException("Output buffer too small for input (" + out.length + '<' + off + (slen >> 1) //$NON-NLS-1$
+ + ')');
+ }
+
+ // Safe to assume the string is even length
+ byte b1, b2;
+ for (int i = 0; i < slen; i += 2)
+ {
+ b1 = (byte)Character.digit(s.charAt(i), 16);
+ b2 = (byte)Character.digit(s.charAt(i + 1), 16);
+ if (b1 < 0 || b2 < 0)
+ {
+ throw new NumberFormatException(s);
+ }
+
+ out[off + i / 2] = (byte)(b1 << 4 | b2);
+ }
+ }
+
+ public static String longToHex(long v)
+ {
+ final String hex = Long.toHexString(v);
+ if (hex.length() < 8)
+ {
+ return "00000000".substring(hex.length()) + hex; //$NON-NLS-1$
+ }
+
+ return hex;
+ }
+
+ @Deprecated
+ public static String formatByte(int b)
+ {
+ assertByte(b);
+ return "" + DIGITS[b >> 4] + DIGITS[b & 0xf]; //$NON-NLS-1$
+ }
+
+ @Deprecated
+ public static String formatBytes(byte[] bytes)
+ {
+ StringBuilder builder = new StringBuilder();
+ for (byte b : bytes)
+ {
+ appendHex(builder, b - Byte.MIN_VALUE);
+ }
+
+ return builder.toString();
+ }
+
+ @Deprecated
+ public static void appendHex(StringBuilder builder, int b)
+ {
+ assertByte(b);
+ builder.append(DIGITS[b >> 4]);
+ builder.append(DIGITS[b & 0xf]);
+ }
+
+ @Deprecated
+ private static void assertByte(int b)
+ {
+ if (b < 0 || b > 255)
+ {
+ throw new IllegalArgumentException("b=" + b); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java index 36d1d3f56e..2ae7afa3a2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -/** - * A callback interface with a {@link #handleError(Throwable) handleError()} method. - * - * @author Eike Stepper - * @since 2.0 - */ -public interface IErrorHandler -{ - public void handleError(Throwable t); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+/**
+ * A callback interface with a {@link #handleError(Throwable) handleError()} method.
+ *
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface IErrorHandler
+{
+ public void handleError(Throwable t);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java index 1e029361d7..b92523b645 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java @@ -1,42 +1,42 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -/** - * Should not be used anymore in favour of {@link AssertionError}. Likely to be deprecated soon. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class ImplementationError extends Error -{ - private static final long serialVersionUID = 1L; - - public ImplementationError() - { - } - - public ImplementationError(String message) - { - super(message); - } - - public ImplementationError(String message, Throwable cause) - { - super(message, cause); - } - - public ImplementationError(Throwable cause) - { - super(cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+/**
+ * Should not be used anymore in favour of {@link AssertionError}. Likely to be deprecated soon.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class ImplementationError extends Error
+{
+ private static final long serialVersionUID = 1L;
+
+ public ImplementationError()
+ {
+ }
+
+ public ImplementationError(String message)
+ {
+ super(message);
+ }
+
+ public ImplementationError(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+
+ public ImplementationError(Throwable cause)
+ {
+ super(cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java index 2f250612b5..43a51b8dae 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java @@ -1,110 +1,110 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.Map; - -/** - * Various static helper methods. - * - * @author Eike Stepper - */ -public final class ObjectUtil -{ - private ObjectUtil() - { - } - - public static boolean equals(Object o1, Object o2) - { - if (o1 == null) - { - return o2 == null; - } - - return o1.equals(o2); - } - - public static int hashCode(Object o) - { - if (o == null) - { - return 0; - } - - return o.hashCode(); - } - - /** - * A collision-free hash code for small sets (<=4) of small, positive integers (<=128) - * - * @since 3.2 - */ - public static int hashCode(int... values) - { - int hash = 0; - for (int i = 0; i < values.length; i++) - { - hash += values[i]; - hash = (hash << 7) - hash; - } - - return hash; - } - - public static int hashCode(long num) - { - return (int)(num >> 32) ^ (int)(num & 0xffffffff); - } - - @SuppressWarnings("unchecked") - public static <T> T[] appendtoArray(T[] array, T... elements) - { - T[] result = (T[])Array.newInstance(array.getClass().getComponentType(), array.length + elements.length); - System.arraycopy(array, 0, result, 0, array.length); - System.arraycopy(elements, 0, result, array.length, elements.length); - return result; - } - - /** - * @since 3.1 - */ - public static <T> boolean isEmpty(T[] array) - { - return array == null || array.length == 0; - } - - /** - * @since 3.1 - */ - public static <T extends Map<?, ?>> boolean isEmpty(Map<?, ?> map) - { - return map == null || map.isEmpty(); - } - - /** - * @since 3.1 - */ - public static <T extends Collection<?>> boolean isEmpty(Collection<?> collection) - { - return collection == null || collection.isEmpty(); - } - - /** - * @since 3.1 - */ - public static boolean isEmpty(String string) - { - return string == null || string.length() == 0; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+import java.lang.reflect.Array;
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Various static helper methods.
+ *
+ * @author Eike Stepper
+ */
+public final class ObjectUtil
+{
+ private ObjectUtil()
+ {
+ }
+
+ public static boolean equals(Object o1, Object o2)
+ {
+ if (o1 == null)
+ {
+ return o2 == null;
+ }
+
+ return o1.equals(o2);
+ }
+
+ public static int hashCode(Object o)
+ {
+ if (o == null)
+ {
+ return 0;
+ }
+
+ return o.hashCode();
+ }
+
+ /**
+ * A collision-free hash code for small sets (<=4) of small, positive integers (<=128)
+ *
+ * @since 3.2
+ */
+ public static int hashCode(int... values)
+ {
+ int hash = 0;
+ for (int i = 0; i < values.length; i++)
+ {
+ hash += values[i];
+ hash = (hash << 7) - hash;
+ }
+
+ return hash;
+ }
+
+ public static int hashCode(long num)
+ {
+ return (int)(num >> 32) ^ (int)(num & 0xffffffff);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static <T> T[] appendtoArray(T[] array, T... elements)
+ {
+ T[] result = (T[])Array.newInstance(array.getClass().getComponentType(), array.length + elements.length);
+ System.arraycopy(array, 0, result, 0, array.length);
+ System.arraycopy(elements, 0, result, array.length, elements.length);
+ return result;
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static <T> boolean isEmpty(T[] array)
+ {
+ return array == null || array.length == 0;
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static <T extends Map<?, ?>> boolean isEmpty(Map<?, ?> map)
+ {
+ return map == null || map.isEmpty();
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static <T extends Collection<?>> boolean isEmpty(Collection<?> collection)
+ {
+ return collection == null || collection.isEmpty();
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static boolean isEmpty(String string)
+ {
+ return string == null || string.length() == 0;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java index 3dc48958aa..8a7d4f9a08 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java @@ -1,603 +1,603 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.collection.Pair; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.io.PrintStream; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.WeakHashMap; - -/** - * Various static helper methods for dealing with Java reflection. - * - * @author Eike Stepper - */ -public final class ReflectUtil -{ - private static final String NAMESPACE_SEPARATOR = "."; //$NON-NLS-1$ - - public static final Class<Object> ROOT_CLASS = Object.class; - - public static final Class<?>[] NO_PARAMETERS = null; - - public static final Object[] NO_ARGUMENTS = null; - - private static final Method HASH_CODE_METHOD = lookupHashCodeMethod(); - - private static final Map<Object, Long> ids = new WeakHashMap<Object, Long>(); - - public static boolean DUMP_STATICS = false; - - private static long lastID; - - private ReflectUtil() - { - } - - public static Method getMethod(Class<?> c, String methodName, Class<?>... parameterTypes) - { - try - { - try - { - return c.getDeclaredMethod(methodName, parameterTypes); - } - catch (NoSuchMethodException ex) - { - Class<?> superclass = c.getSuperclass(); - if (superclass != null) - { - return getMethod(superclass, methodName, parameterTypes); - } - - throw ex; - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static Object invokeMethod(Method method, Object target, Object... arguments) - { - boolean accessible = method.isAccessible(); - if (!accessible) - { - method.setAccessible(true); - } - - try - { - return method.invoke(target, arguments); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - finally - { - if (!accessible) - { - method.setAccessible(false); - } - } - } - - public static Field getField(Class<?> c, String fieldName) - { - try - { - try - { - return c.getDeclaredField(fieldName); - } - catch (NoSuchFieldException ex) - { - Class<?> superclass = c.getSuperclass(); - if (superclass != null) - { - return getField(superclass, fieldName); - } - - return null; - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void collectFields(Class<?> c, List<Field> fields) - { - if (c == ROOT_CLASS) - { - return; - } - - // Recurse - collectFields(c.getSuperclass(), fields); - - try - { - Field[] declaredFields = c.getDeclaredFields(); - for (Field field : declaredFields) - { - if (field.isSynthetic()) - { - continue; - } - - if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS) - { - continue; - } - - if (field.getAnnotation(ExcludeFromDump.class) != null) - { - continue; - } - - fields.add(field); - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static Object getValue(Field field, Object target) - { - if (!field.isAccessible()) - { - field.setAccessible(true); - } - - try - { - return field.get(target); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void setValue(Field field, Object target, Object value) - { - if (!field.isAccessible()) - { - field.setAccessible(true); - } - - try - { - field.set(target, value); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void printStackTrace(PrintStream out, StackTraceElement[] stackTrace) - { - for (int i = 2; i < stackTrace.length; i++) - { - StackTraceElement stackTraceElement = stackTrace[i]; - out.println("\tat " + stackTraceElement); //$NON-NLS-1$ - } - } - - public static void printStackTrace(StackTraceElement[] stackTrace) - { - printStackTrace(System.err, stackTrace); - } - - public static Integer getHashCode(Object object) - { - try - { - return (Integer)HASH_CODE_METHOD.invoke(object, NO_ARGUMENTS); - } - catch (Exception ex) - { - IOUtil.print(ex); - } - - return 0; - } - - public static synchronized Long getID(Object object) - { - Long id = ids.get(object); - if (id == null) - { - id = ++lastID; - ids.put(object, id); - } - - return id; - } - - public static String getPackageName(Class<? extends Object> c) - { - if (c == null) - { - return null; - } - - return getPackageName(c.getName()); - } - - public static String getPackageName(String className) - { - if (className == null) - { - return null; - } - - int lastDot = className.lastIndexOf('.'); - if (lastDot != -1) - { - className = className.substring(0, lastDot); - } - - return className; - } - - public static String getSimpleName(Class<? extends Object> c) - { - if (c == null) - { - return null; - } - - return c.getSimpleName(); - } - - public static String getSimpleClassName(String name) - { - if (name == null) - { - return null; - } - - int lastDot = name.lastIndexOf('.'); - if (lastDot != -1) - { - name = name.substring(lastDot + 1); - } - - return name.replace('$', '.'); - } - - public static String getSimpleClassName(Object object) - { - if (object == null) - { - return null; - } - - return getSimpleName(object.getClass()); - } - - public static String getLabel(Object object) - { - if (object == null) - { - return null; - } - - String name = object.getClass().getSimpleName(); - if (name.length() == 0) - { - name = "anonymous"; //$NON-NLS-1$ - } - - return name + "@" + getID(object); //$NON-NLS-1$ - } - - public static void dump(Object object) - { - dump(object, ""); //$NON-NLS-1$ - } - - public static void dump(Object object, String prefix) - { - dump(object, prefix, IOUtil.OUT()); - } - - public static void dump(Object object, String prefix, PrintStream out) - { - out.print(toString(object, prefix)); - } - - @SuppressWarnings("unchecked") - public static Pair<Field, Object>[] dumpToArray(Object object) - { - List<Field> fields = new ArrayList<Field>(); - collectFields(object.getClass(), fields); - Pair<Field, Object>[] result = new Pair[fields.size()]; - int i = 0; - for (Field field : fields) - { - Object value = getValue(field, object); - result[i++] = new Pair<Field, Object>(field, value); - } - - return result; - } - - public static Object instantiate(Map<Object, Object> properties, String namespace, String classKey, - ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException - { - if (namespace != null) - { - if (namespace.length() == 0) - { - namespace = null; - } - else if (!namespace.endsWith(NAMESPACE_SEPARATOR)) - { - namespace += NAMESPACE_SEPARATOR; - } - } - - String className = null; - Map<String, Object> values = new HashMap<String, Object>(); - for (Entry<Object, Object> entry : properties.entrySet()) - { - if (entry.getKey() instanceof String) - { - String key = (String)entry.getKey(); - if (namespace != null) - { - if (key.startsWith(namespace)) - { - key = key.substring(namespace.length()); - } - else - { - continue; - } - } - - if (classKey.equals(key)) - { - Object classValue = entry.getValue(); - if (classValue instanceof String) - { - className = (String)classValue; - } - else - { - OM.LOG.warn("Value of classKey " + classKey + " is not a String"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else - { - values.put(key, entry.getValue()); - } - } - } - - if (className == null) - { - throw new IllegalArgumentException("Properties do not contain a valid class name for key " + classKey); //$NON-NLS-1$ - } - - Class<?> c = classLoader.loadClass(className); - Object instance = c.newInstance(); - Method[] methods = c.getMethods(); - for (Method method : methods) - { - if (isSetter(method)) - { - String name = StringUtil.uncap(method.getName().substring(3)); - Object value = values.get(name); - if (value != null) - { - Class<?> type = method.getParameterTypes()[0]; - if (!type.isAssignableFrom(value.getClass())) - { - if (value instanceof String) - { - String str = (String)value; - value = null; - if (type.isAssignableFrom(Boolean.class)) - { - value = Boolean.parseBoolean(str); - } - else if (type.isAssignableFrom(Byte.class)) - { - value = Byte.parseByte(str); - } - else if (type.isAssignableFrom(Short.class)) - { - value = Short.parseShort(str); - } - else if (type.isAssignableFrom(Integer.class)) - { - value = Integer.parseInt(str); - } - else if (type.isAssignableFrom(Long.class)) - { - value = Long.parseLong(str); - } - else if (type.isAssignableFrom(Float.class)) - { - value = Float.parseFloat(str); - } - else if (type.isAssignableFrom(Double.class)) - { - value = Double.parseDouble(str); - } - } - else - { - value = null; - } - } - - if (value == null) - { - throw new IllegalArgumentException("Value of property " + name + " can not be assigned to type " //$NON-NLS-1$ //$NON-NLS-2$ - + type.getName()); - } - - method.invoke(instance, value); - } - } - } - - return instance; - } - - public static boolean isSetter(Method method) - { - return method.getParameterTypes().length == 1 && isSetterName(method.getName()); - } - - public static boolean isSetterName(String name) - { - return name.startsWith("set") && name.length() > 3 && Character.isUpperCase(name.charAt(3)); //$NON-NLS-1$ - } - - public static String toString(Object object) - { - return toString(object, " "); //$NON-NLS-1$ - } - - public static String toString(Object object, String prefix) - { - StringBuilder builder = new StringBuilder(); - builder.append(prefix); - builder.append(getLabel(object)); - builder.append(StringUtil.NL); - toString(object.getClass(), object, prefix, builder); - return builder.toString(); - } - - private static void toString(Class<? extends Object> segment, Object object, String prefix, StringBuilder builder) - { - if (segment == ROOT_CLASS || segment == Lifecycle.class) - { - return; - } - - // Recurse - toString(segment.getSuperclass(), object, prefix, builder); - - String segmentPrefix = segment == object.getClass() ? "" : getSimpleName(segment) + NAMESPACE_SEPARATOR; //$NON-NLS-1$ - for (Field field : segment.getDeclaredFields()) - { - if (field.isSynthetic()) - { - continue; - } - - if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS) - { - continue; - } - - if (field.getAnnotation(ExcludeFromDump.class) != null) - { - continue; - } - - builder.append(prefix); - builder.append(segmentPrefix); - builder.append(field.getName()); - builder.append(" = "); //$NON-NLS-1$ - - Object value = getValue(field, object); - if (value instanceof Map<?, ?>) - { - value = ((Map<?, ?>)value).entrySet(); - } - - if (value instanceof Collection<?>) - { - builder.append(StringUtil.NL); - Collection<?> collection = (Collection<?>)value; - Object[] array = collection.toArray(new Object[collection.size()]); - for (Object element : array) - { - builder.append(" "); //$NON-NLS-1$ - builder.append(element); - builder.append(StringUtil.NL); - } - } - else - { - builder.append(value); - builder.append(StringUtil.NL); - } - } - } - - private static Method lookupHashCodeMethod() - { - Method method; - - try - { - method = ROOT_CLASS.getMethod("hashCode", NO_PARAMETERS); //$NON-NLS-1$ - } - catch (Exception ex) - { - // This can really not happen - throw new AssertionError(); - } - - if (!method.isAccessible()) - { - method.setAccessible(true); - } - - return method; - } - - /** - * Annotates fields that are to be skipped in {@link ReflectUtil#collectFields(Class, List) - * ReflectUtil.collectFields()} and {@link ReflectUtil#toString(Object) ReflectUtil.toString()}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.FIELD) - public @interface ExcludeFromDump - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.collection.Pair;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.io.PrintStream;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.WeakHashMap;
+
+/**
+ * Various static helper methods for dealing with Java reflection.
+ *
+ * @author Eike Stepper
+ */
+public final class ReflectUtil
+{
+ private static final String NAMESPACE_SEPARATOR = "."; //$NON-NLS-1$
+
+ public static final Class<Object> ROOT_CLASS = Object.class;
+
+ public static final Class<?>[] NO_PARAMETERS = null;
+
+ public static final Object[] NO_ARGUMENTS = null;
+
+ private static final Method HASH_CODE_METHOD = lookupHashCodeMethod();
+
+ private static final Map<Object, Long> ids = new WeakHashMap<Object, Long>();
+
+ public static boolean DUMP_STATICS = false;
+
+ private static long lastID;
+
+ private ReflectUtil()
+ {
+ }
+
+ public static Method getMethod(Class<?> c, String methodName, Class<?>... parameterTypes)
+ {
+ try
+ {
+ try
+ {
+ return c.getDeclaredMethod(methodName, parameterTypes);
+ }
+ catch (NoSuchMethodException ex)
+ {
+ Class<?> superclass = c.getSuperclass();
+ if (superclass != null)
+ {
+ return getMethod(superclass, methodName, parameterTypes);
+ }
+
+ throw ex;
+ }
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static Object invokeMethod(Method method, Object target, Object... arguments)
+ {
+ boolean accessible = method.isAccessible();
+ if (!accessible)
+ {
+ method.setAccessible(true);
+ }
+
+ try
+ {
+ return method.invoke(target, arguments);
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ if (!accessible)
+ {
+ method.setAccessible(false);
+ }
+ }
+ }
+
+ public static Field getField(Class<?> c, String fieldName)
+ {
+ try
+ {
+ try
+ {
+ return c.getDeclaredField(fieldName);
+ }
+ catch (NoSuchFieldException ex)
+ {
+ Class<?> superclass = c.getSuperclass();
+ if (superclass != null)
+ {
+ return getField(superclass, fieldName);
+ }
+
+ return null;
+ }
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static void collectFields(Class<?> c, List<Field> fields)
+ {
+ if (c == ROOT_CLASS)
+ {
+ return;
+ }
+
+ // Recurse
+ collectFields(c.getSuperclass(), fields);
+
+ try
+ {
+ Field[] declaredFields = c.getDeclaredFields();
+ for (Field field : declaredFields)
+ {
+ if (field.isSynthetic())
+ {
+ continue;
+ }
+
+ if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS)
+ {
+ continue;
+ }
+
+ if (field.getAnnotation(ExcludeFromDump.class) != null)
+ {
+ continue;
+ }
+
+ fields.add(field);
+ }
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static Object getValue(Field field, Object target)
+ {
+ if (!field.isAccessible())
+ {
+ field.setAccessible(true);
+ }
+
+ try
+ {
+ return field.get(target);
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static void setValue(Field field, Object target, Object value)
+ {
+ if (!field.isAccessible())
+ {
+ field.setAccessible(true);
+ }
+
+ try
+ {
+ field.set(target, value);
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static void printStackTrace(PrintStream out, StackTraceElement[] stackTrace)
+ {
+ for (int i = 2; i < stackTrace.length; i++)
+ {
+ StackTraceElement stackTraceElement = stackTrace[i];
+ out.println("\tat " + stackTraceElement); //$NON-NLS-1$
+ }
+ }
+
+ public static void printStackTrace(StackTraceElement[] stackTrace)
+ {
+ printStackTrace(System.err, stackTrace);
+ }
+
+ public static Integer getHashCode(Object object)
+ {
+ try
+ {
+ return (Integer)HASH_CODE_METHOD.invoke(object, NO_ARGUMENTS);
+ }
+ catch (Exception ex)
+ {
+ IOUtil.print(ex);
+ }
+
+ return 0;
+ }
+
+ public static synchronized Long getID(Object object)
+ {
+ Long id = ids.get(object);
+ if (id == null)
+ {
+ id = ++lastID;
+ ids.put(object, id);
+ }
+
+ return id;
+ }
+
+ public static String getPackageName(Class<? extends Object> c)
+ {
+ if (c == null)
+ {
+ return null;
+ }
+
+ return getPackageName(c.getName());
+ }
+
+ public static String getPackageName(String className)
+ {
+ if (className == null)
+ {
+ return null;
+ }
+
+ int lastDot = className.lastIndexOf('.');
+ if (lastDot != -1)
+ {
+ className = className.substring(0, lastDot);
+ }
+
+ return className;
+ }
+
+ public static String getSimpleName(Class<? extends Object> c)
+ {
+ if (c == null)
+ {
+ return null;
+ }
+
+ return c.getSimpleName();
+ }
+
+ public static String getSimpleClassName(String name)
+ {
+ if (name == null)
+ {
+ return null;
+ }
+
+ int lastDot = name.lastIndexOf('.');
+ if (lastDot != -1)
+ {
+ name = name.substring(lastDot + 1);
+ }
+
+ return name.replace('$', '.');
+ }
+
+ public static String getSimpleClassName(Object object)
+ {
+ if (object == null)
+ {
+ return null;
+ }
+
+ return getSimpleName(object.getClass());
+ }
+
+ public static String getLabel(Object object)
+ {
+ if (object == null)
+ {
+ return null;
+ }
+
+ String name = object.getClass().getSimpleName();
+ if (name.length() == 0)
+ {
+ name = "anonymous"; //$NON-NLS-1$
+ }
+
+ return name + "@" + getID(object); //$NON-NLS-1$
+ }
+
+ public static void dump(Object object)
+ {
+ dump(object, ""); //$NON-NLS-1$
+ }
+
+ public static void dump(Object object, String prefix)
+ {
+ dump(object, prefix, IOUtil.OUT());
+ }
+
+ public static void dump(Object object, String prefix, PrintStream out)
+ {
+ out.print(toString(object, prefix));
+ }
+
+ @SuppressWarnings("unchecked")
+ public static Pair<Field, Object>[] dumpToArray(Object object)
+ {
+ List<Field> fields = new ArrayList<Field>();
+ collectFields(object.getClass(), fields);
+ Pair<Field, Object>[] result = new Pair[fields.size()];
+ int i = 0;
+ for (Field field : fields)
+ {
+ Object value = getValue(field, object);
+ result[i++] = new Pair<Field, Object>(field, value);
+ }
+
+ return result;
+ }
+
+ public static Object instantiate(Map<Object, Object> properties, String namespace, String classKey,
+ ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
+ IllegalArgumentException, InvocationTargetException
+ {
+ if (namespace != null)
+ {
+ if (namespace.length() == 0)
+ {
+ namespace = null;
+ }
+ else if (!namespace.endsWith(NAMESPACE_SEPARATOR))
+ {
+ namespace += NAMESPACE_SEPARATOR;
+ }
+ }
+
+ String className = null;
+ Map<String, Object> values = new HashMap<String, Object>();
+ for (Entry<Object, Object> entry : properties.entrySet())
+ {
+ if (entry.getKey() instanceof String)
+ {
+ String key = (String)entry.getKey();
+ if (namespace != null)
+ {
+ if (key.startsWith(namespace))
+ {
+ key = key.substring(namespace.length());
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ if (classKey.equals(key))
+ {
+ Object classValue = entry.getValue();
+ if (classValue instanceof String)
+ {
+ className = (String)classValue;
+ }
+ else
+ {
+ OM.LOG.warn("Value of classKey " + classKey + " is not a String"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ else
+ {
+ values.put(key, entry.getValue());
+ }
+ }
+ }
+
+ if (className == null)
+ {
+ throw new IllegalArgumentException("Properties do not contain a valid class name for key " + classKey); //$NON-NLS-1$
+ }
+
+ Class<?> c = classLoader.loadClass(className);
+ Object instance = c.newInstance();
+ Method[] methods = c.getMethods();
+ for (Method method : methods)
+ {
+ if (isSetter(method))
+ {
+ String name = StringUtil.uncap(method.getName().substring(3));
+ Object value = values.get(name);
+ if (value != null)
+ {
+ Class<?> type = method.getParameterTypes()[0];
+ if (!type.isAssignableFrom(value.getClass()))
+ {
+ if (value instanceof String)
+ {
+ String str = (String)value;
+ value = null;
+ if (type.isAssignableFrom(Boolean.class))
+ {
+ value = Boolean.parseBoolean(str);
+ }
+ else if (type.isAssignableFrom(Byte.class))
+ {
+ value = Byte.parseByte(str);
+ }
+ else if (type.isAssignableFrom(Short.class))
+ {
+ value = Short.parseShort(str);
+ }
+ else if (type.isAssignableFrom(Integer.class))
+ {
+ value = Integer.parseInt(str);
+ }
+ else if (type.isAssignableFrom(Long.class))
+ {
+ value = Long.parseLong(str);
+ }
+ else if (type.isAssignableFrom(Float.class))
+ {
+ value = Float.parseFloat(str);
+ }
+ else if (type.isAssignableFrom(Double.class))
+ {
+ value = Double.parseDouble(str);
+ }
+ }
+ else
+ {
+ value = null;
+ }
+ }
+
+ if (value == null)
+ {
+ throw new IllegalArgumentException("Value of property " + name + " can not be assigned to type " //$NON-NLS-1$ //$NON-NLS-2$
+ + type.getName());
+ }
+
+ method.invoke(instance, value);
+ }
+ }
+ }
+
+ return instance;
+ }
+
+ public static boolean isSetter(Method method)
+ {
+ return method.getParameterTypes().length == 1 && isSetterName(method.getName());
+ }
+
+ public static boolean isSetterName(String name)
+ {
+ return name.startsWith("set") && name.length() > 3 && Character.isUpperCase(name.charAt(3)); //$NON-NLS-1$
+ }
+
+ public static String toString(Object object)
+ {
+ return toString(object, " "); //$NON-NLS-1$
+ }
+
+ public static String toString(Object object, String prefix)
+ {
+ StringBuilder builder = new StringBuilder();
+ builder.append(prefix);
+ builder.append(getLabel(object));
+ builder.append(StringUtil.NL);
+ toString(object.getClass(), object, prefix, builder);
+ return builder.toString();
+ }
+
+ private static void toString(Class<? extends Object> segment, Object object, String prefix, StringBuilder builder)
+ {
+ if (segment == ROOT_CLASS || segment == Lifecycle.class)
+ {
+ return;
+ }
+
+ // Recurse
+ toString(segment.getSuperclass(), object, prefix, builder);
+
+ String segmentPrefix = segment == object.getClass() ? "" : getSimpleName(segment) + NAMESPACE_SEPARATOR; //$NON-NLS-1$
+ for (Field field : segment.getDeclaredFields())
+ {
+ if (field.isSynthetic())
+ {
+ continue;
+ }
+
+ if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS)
+ {
+ continue;
+ }
+
+ if (field.getAnnotation(ExcludeFromDump.class) != null)
+ {
+ continue;
+ }
+
+ builder.append(prefix);
+ builder.append(segmentPrefix);
+ builder.append(field.getName());
+ builder.append(" = "); //$NON-NLS-1$
+
+ Object value = getValue(field, object);
+ if (value instanceof Map<?, ?>)
+ {
+ value = ((Map<?, ?>)value).entrySet();
+ }
+
+ if (value instanceof Collection<?>)
+ {
+ builder.append(StringUtil.NL);
+ Collection<?> collection = (Collection<?>)value;
+ Object[] array = collection.toArray(new Object[collection.size()]);
+ for (Object element : array)
+ {
+ builder.append(" "); //$NON-NLS-1$
+ builder.append(element);
+ builder.append(StringUtil.NL);
+ }
+ }
+ else
+ {
+ builder.append(value);
+ builder.append(StringUtil.NL);
+ }
+ }
+ }
+
+ private static Method lookupHashCodeMethod()
+ {
+ Method method;
+
+ try
+ {
+ method = ROOT_CLASS.getMethod("hashCode", NO_PARAMETERS); //$NON-NLS-1$
+ }
+ catch (Exception ex)
+ {
+ // This can really not happen
+ throw new AssertionError();
+ }
+
+ if (!method.isAccessible())
+ {
+ method.setAccessible(true);
+ }
+
+ return method;
+ }
+
+ /**
+ * Annotates fields that are to be skipped in {@link ReflectUtil#collectFields(Class, List)
+ * ReflectUtil.collectFields()} and {@link ReflectUtil#toString(Object) ReflectUtil.toString()}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.FIELD)
+ public @interface ExcludeFromDump
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java index 30806f9e02..3fb7bdd0a1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java @@ -1,393 +1,393 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -import org.eclipse.net4j.util.om.OMPlatform; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -/** - * Various static helper methods for dealing with strings. - * - * @author Eike Stepper - */ -public final class StringUtil -{ - public static final String EMPTY = ""; //$NON-NLS-1$ - - public static final String NL = OMPlatform.INSTANCE.getProperty("line.separator"); //$NON-NLS-1$ - - private StringUtil() - { - } - - /** - * @since 2.0 - */ - public static String formatException(Throwable t) - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream s = new PrintStream(baos); - t.printStackTrace(s); - return baos.toString(); - } - - public static String replace(String text, String[] find, String[] replace) - { - for (int i = 0; i < find.length; i++) - { - int end = 0; - for (;;) - { - int start = text.indexOf(find[i], end); - if (start == -1) - { - break; - } - - end = start + find[i].length(); - text = text.substring(0, start) + replace[i] + text.substring(end); - } - } - - return text; - } - - public static String safe(String str) - { - if (str == null) - { - return EMPTY; - } - - return str; - } - - public static int compare(String s1, String s2) - { - if (s1 == null) - { - return s2 == null ? 0 : -1; - } - - if (s2 == null) - { - return 1; - } - - return s1.compareTo(s2); - } - - /** - * @since 3.1 - */ - public static boolean equalsUpperOrLowerCase(String s, String upperOrLowerCase) - { - if (s == null) - { - return upperOrLowerCase == null; - } - - return s.equals(upperOrLowerCase.toLowerCase()) || s.equals(upperOrLowerCase.toUpperCase()); - } - - /** - * @since 2.0 - */ - public static String capAll(String str) - { - if (str == null || str.length() == 0) - { - return str; - } - - boolean inWhiteSpace = true; - StringBuilder builder = new StringBuilder(str); - for (int i = 0; i < builder.length(); i++) - { - char c = builder.charAt(i); - boolean isWhiteSpace = Character.isWhitespace(c); - if (!isWhiteSpace && inWhiteSpace) - { - builder.setCharAt(i, Character.toUpperCase(c)); - } - - inWhiteSpace = isWhiteSpace; - } - - return builder.toString(); - } - - /** - * @since 2.0 - */ - public static String uncapAll(String str) - { - if (str == null || str.length() == 0) - { - return str; - } - - boolean inWhiteSpace = true; - StringBuilder builder = new StringBuilder(str); - for (int i = 0; i < builder.length(); i++) - { - char c = builder.charAt(i); - boolean isWhiteSpace = Character.isWhitespace(c); - if (!isWhiteSpace && inWhiteSpace) - { - builder.setCharAt(i, Character.toLowerCase(c)); - } - - inWhiteSpace = isWhiteSpace; - } - - return builder.toString(); - } - - public static String cap(String str) - { - if (str == null || str.length() == 0) - { - return str; - } - - char first = str.charAt(0); - if (Character.isUpperCase(first)) - { - return str; - } - - if (str.length() == 1) - { - return str.toUpperCase(); - } - - StringBuilder builder = new StringBuilder(str); - builder.setCharAt(0, Character.toUpperCase(first)); - return builder.toString(); - } - - public static String uncap(String str) - { - if (str == null || str.length() == 0) - { - return str; - } - - char first = str.charAt(0); - if (Character.isLowerCase(first)) - { - return str; - } - - if (str.length() == 1) - { - return str.toLowerCase(); - } - - StringBuilder builder = new StringBuilder(str); - builder.setCharAt(0, Character.toLowerCase(first)); - return builder.toString(); - } - - public static int occurrences(String str, char c) - { - int count = 0; - for (int i = 0; (i = str.indexOf(c, i)) != -1; ++i) - { - ++count; - } - - return count; - } - - public static int occurrences(String str, String c) - { - int count = 0; - for (int i = 0; (i = str.indexOf(c, i)) != -1; i += c.length()) - { - ++count; - } - - return count; - } - - public static boolean isEmpty(String str) - { - return ObjectUtil.isEmpty(str); - } - - /** - * Matches a string against a pattern. - * <p> - * Pattern description: - * <ul> - * <li><code>*</code> matches 0 or more characters - * <li><code>?</code> matches a single character - * <li><code>[...]</code> matches a set and/or range of characters - * <li><code>\</code> escapes the following character - * </ul> - * - * @since 2.0 - */ - public static boolean glob(String pattern, String string) - { - return glob(pattern, string, null); - } - - /** - * Matches a string against a pattern and fills an array with the sub-matches. - * <p> - * Pattern description: - * <ul> - * <li><code>*</code> matches 0 or more characters - * <li><code>?</code> matches a single character - * <li><code>[...]</code> matches a set and/or range of characters - * <li><code>\</code> escapes the following character - * </ul> - * - * @since 2.0 - */ - public static boolean glob(String pattern, String string, String[] subStrings) - { - return globRecurse(pattern, 0, string, 0, subStrings, 0); - } - - private static boolean globRecurse(String pattern, int patternIndex, String string, int stringIndex, - String[] subStrings, int subStringsIndex) - { - int patternLength = pattern.length(); - int stringLength = string.length(); - - for (;;) - { - char patternChar = pattern.charAt(patternIndex); - boolean endReached = stringIndex == stringLength; - if (patternIndex == patternLength) - { - return endReached; - } - else if (endReached && patternChar != '*') - { - return false; - } - - switch (patternChar) - { - case '*': - { - int startIndex = stringIndex; - if (++patternIndex >= patternLength) - { - globRemember(string, startIndex, stringLength, subStrings, subStringsIndex); - return true; - } - - for (;;) - { - if (globRecurse(pattern, patternIndex, string, stringIndex, subStrings, subStringsIndex + 1)) - { - globRemember(string, startIndex, stringIndex, subStrings, subStringsIndex); - return true; - } - - if (endReached) - { - return false; - } - - ++stringIndex; - } - } - - case '?': - ++patternIndex; - globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++); - break; - - case '[': - try - { - ++patternIndex; - char stringChar = string.charAt(stringIndex); - char rangeStartChar = patternChar; - - while (true) - { - if (rangeStartChar == ']') - { - return false; - } - - if (rangeStartChar == stringChar) - { - break; - } - - ++patternIndex; - char nextPatternChar = patternChar; - if (nextPatternChar == '-') - { - ++patternIndex; - char rangeEndChar = patternChar; - if (rangeStartChar <= stringChar && stringChar <= rangeEndChar) - { - break; - } - - ++patternIndex; - nextPatternChar = patternChar; - } - - rangeStartChar = nextPatternChar; - } - - patternIndex = pattern.indexOf(']', patternIndex) + 1; - if (patternIndex <= 0) - { - return false; - } - - globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++); - } - catch (StringIndexOutOfBoundsException ex) - { - return false; - } - - break; - - case '\\': - if (++patternIndex >= patternLength) - { - return false; - } - - //$FALL-THROUGH$ - default: - if (patternChar++ != string.charAt(stringIndex++)) - { - return false; - } - } - } - } - - private static void globRemember(String string, int start, int end, String[] subStrings, int subStringsIndex) - { - if (subStrings != null && subStringsIndex < subStrings.length) - { - subStrings[subStringsIndex] = string.substring(start, end); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+import org.eclipse.net4j.util.om.OMPlatform;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+/**
+ * Various static helper methods for dealing with strings.
+ *
+ * @author Eike Stepper
+ */
+public final class StringUtil
+{
+ public static final String EMPTY = ""; //$NON-NLS-1$
+
+ public static final String NL = OMPlatform.INSTANCE.getProperty("line.separator"); //$NON-NLS-1$
+
+ private StringUtil()
+ {
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static String formatException(Throwable t)
+ {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ PrintStream s = new PrintStream(baos);
+ t.printStackTrace(s);
+ return baos.toString();
+ }
+
+ public static String replace(String text, String[] find, String[] replace)
+ {
+ for (int i = 0; i < find.length; i++)
+ {
+ int end = 0;
+ for (;;)
+ {
+ int start = text.indexOf(find[i], end);
+ if (start == -1)
+ {
+ break;
+ }
+
+ end = start + find[i].length();
+ text = text.substring(0, start) + replace[i] + text.substring(end);
+ }
+ }
+
+ return text;
+ }
+
+ public static String safe(String str)
+ {
+ if (str == null)
+ {
+ return EMPTY;
+ }
+
+ return str;
+ }
+
+ public static int compare(String s1, String s2)
+ {
+ if (s1 == null)
+ {
+ return s2 == null ? 0 : -1;
+ }
+
+ if (s2 == null)
+ {
+ return 1;
+ }
+
+ return s1.compareTo(s2);
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static boolean equalsUpperOrLowerCase(String s, String upperOrLowerCase)
+ {
+ if (s == null)
+ {
+ return upperOrLowerCase == null;
+ }
+
+ return s.equals(upperOrLowerCase.toLowerCase()) || s.equals(upperOrLowerCase.toUpperCase());
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static String capAll(String str)
+ {
+ if (str == null || str.length() == 0)
+ {
+ return str;
+ }
+
+ boolean inWhiteSpace = true;
+ StringBuilder builder = new StringBuilder(str);
+ for (int i = 0; i < builder.length(); i++)
+ {
+ char c = builder.charAt(i);
+ boolean isWhiteSpace = Character.isWhitespace(c);
+ if (!isWhiteSpace && inWhiteSpace)
+ {
+ builder.setCharAt(i, Character.toUpperCase(c));
+ }
+
+ inWhiteSpace = isWhiteSpace;
+ }
+
+ return builder.toString();
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static String uncapAll(String str)
+ {
+ if (str == null || str.length() == 0)
+ {
+ return str;
+ }
+
+ boolean inWhiteSpace = true;
+ StringBuilder builder = new StringBuilder(str);
+ for (int i = 0; i < builder.length(); i++)
+ {
+ char c = builder.charAt(i);
+ boolean isWhiteSpace = Character.isWhitespace(c);
+ if (!isWhiteSpace && inWhiteSpace)
+ {
+ builder.setCharAt(i, Character.toLowerCase(c));
+ }
+
+ inWhiteSpace = isWhiteSpace;
+ }
+
+ return builder.toString();
+ }
+
+ public static String cap(String str)
+ {
+ if (str == null || str.length() == 0)
+ {
+ return str;
+ }
+
+ char first = str.charAt(0);
+ if (Character.isUpperCase(first))
+ {
+ return str;
+ }
+
+ if (str.length() == 1)
+ {
+ return str.toUpperCase();
+ }
+
+ StringBuilder builder = new StringBuilder(str);
+ builder.setCharAt(0, Character.toUpperCase(first));
+ return builder.toString();
+ }
+
+ public static String uncap(String str)
+ {
+ if (str == null || str.length() == 0)
+ {
+ return str;
+ }
+
+ char first = str.charAt(0);
+ if (Character.isLowerCase(first))
+ {
+ return str;
+ }
+
+ if (str.length() == 1)
+ {
+ return str.toLowerCase();
+ }
+
+ StringBuilder builder = new StringBuilder(str);
+ builder.setCharAt(0, Character.toLowerCase(first));
+ return builder.toString();
+ }
+
+ public static int occurrences(String str, char c)
+ {
+ int count = 0;
+ for (int i = 0; (i = str.indexOf(c, i)) != -1; ++i)
+ {
+ ++count;
+ }
+
+ return count;
+ }
+
+ public static int occurrences(String str, String c)
+ {
+ int count = 0;
+ for (int i = 0; (i = str.indexOf(c, i)) != -1; i += c.length())
+ {
+ ++count;
+ }
+
+ return count;
+ }
+
+ public static boolean isEmpty(String str)
+ {
+ return ObjectUtil.isEmpty(str);
+ }
+
+ /**
+ * Matches a string against a pattern.
+ * <p>
+ * Pattern description:
+ * <ul>
+ * <li><code>*</code> matches 0 or more characters
+ * <li><code>?</code> matches a single character
+ * <li><code>[...]</code> matches a set and/or range of characters
+ * <li><code>\</code> escapes the following character
+ * </ul>
+ *
+ * @since 2.0
+ */
+ public static boolean glob(String pattern, String string)
+ {
+ return glob(pattern, string, null);
+ }
+
+ /**
+ * Matches a string against a pattern and fills an array with the sub-matches.
+ * <p>
+ * Pattern description:
+ * <ul>
+ * <li><code>*</code> matches 0 or more characters
+ * <li><code>?</code> matches a single character
+ * <li><code>[...]</code> matches a set and/or range of characters
+ * <li><code>\</code> escapes the following character
+ * </ul>
+ *
+ * @since 2.0
+ */
+ public static boolean glob(String pattern, String string, String[] subStrings)
+ {
+ return globRecurse(pattern, 0, string, 0, subStrings, 0);
+ }
+
+ private static boolean globRecurse(String pattern, int patternIndex, String string, int stringIndex,
+ String[] subStrings, int subStringsIndex)
+ {
+ int patternLength = pattern.length();
+ int stringLength = string.length();
+
+ for (;;)
+ {
+ char patternChar = pattern.charAt(patternIndex);
+ boolean endReached = stringIndex == stringLength;
+ if (patternIndex == patternLength)
+ {
+ return endReached;
+ }
+ else if (endReached && patternChar != '*')
+ {
+ return false;
+ }
+
+ switch (patternChar)
+ {
+ case '*':
+ {
+ int startIndex = stringIndex;
+ if (++patternIndex >= patternLength)
+ {
+ globRemember(string, startIndex, stringLength, subStrings, subStringsIndex);
+ return true;
+ }
+
+ for (;;)
+ {
+ if (globRecurse(pattern, patternIndex, string, stringIndex, subStrings, subStringsIndex + 1))
+ {
+ globRemember(string, startIndex, stringIndex, subStrings, subStringsIndex);
+ return true;
+ }
+
+ if (endReached)
+ {
+ return false;
+ }
+
+ ++stringIndex;
+ }
+ }
+
+ case '?':
+ ++patternIndex;
+ globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++);
+ break;
+
+ case '[':
+ try
+ {
+ ++patternIndex;
+ char stringChar = string.charAt(stringIndex);
+ char rangeStartChar = patternChar;
+
+ while (true)
+ {
+ if (rangeStartChar == ']')
+ {
+ return false;
+ }
+
+ if (rangeStartChar == stringChar)
+ {
+ break;
+ }
+
+ ++patternIndex;
+ char nextPatternChar = patternChar;
+ if (nextPatternChar == '-')
+ {
+ ++patternIndex;
+ char rangeEndChar = patternChar;
+ if (rangeStartChar <= stringChar && stringChar <= rangeEndChar)
+ {
+ break;
+ }
+
+ ++patternIndex;
+ nextPatternChar = patternChar;
+ }
+
+ rangeStartChar = nextPatternChar;
+ }
+
+ patternIndex = pattern.indexOf(']', patternIndex) + 1;
+ if (patternIndex <= 0)
+ {
+ return false;
+ }
+
+ globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++);
+ }
+ catch (StringIndexOutOfBoundsException ex)
+ {
+ return false;
+ }
+
+ break;
+
+ case '\\':
+ if (++patternIndex >= patternLength)
+ {
+ return false;
+ }
+
+ //$FALL-THROUGH$
+ default:
+ if (patternChar++ != string.charAt(stringIndex++))
+ {
+ return false;
+ }
+ }
+ }
+ }
+
+ private static void globRemember(String string, int start, int end, String[] subStrings, int subStringsIndex)
+ {
+ if (subStrings != null && subStringsIndex < subStrings.length)
+ {
+ subStrings[subStringsIndex] = string.substring(start, end);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java index 1ac1fa0167..82a1f8e45a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java index 64f09560bf..7ee8967faf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java @@ -1,66 +1,66 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util; - -/** - * An unchecked exception that wraps a checked exception. Wrapping occurs conditionally in the static - * {@link #wrap(Exception, String) wrap()} methods. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - */ -public class WrappedException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - private WrappedException(Exception exception) - { - super(exception); - } - - private WrappedException(String message, Exception exception) - { - super(message, exception); - } - - public Exception exception() - { - return (Exception)getCause(); - } - - /** - * @since 3.1 - */ - public static RuntimeException wrap(Exception exception, String message) - { - return new WrappedException(message, exception); - } - - public static RuntimeException wrap(Exception exception) - { - if (exception instanceof RuntimeException) - { - return (RuntimeException)exception; - } - - return new WrappedException(exception); - } - - public static Exception unwrap(Exception exception) - { - if (exception instanceof WrappedException) - { - return ((WrappedException)exception).exception(); - } - - return exception; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util;
+
+/**
+ * An unchecked exception that wraps a checked exception. Wrapping occurs conditionally in the static
+ * {@link #wrap(Exception, String) wrap()} methods.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ */
+public class WrappedException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ private WrappedException(Exception exception)
+ {
+ super(exception);
+ }
+
+ private WrappedException(String message, Exception exception)
+ {
+ super(message, exception);
+ }
+
+ public Exception exception()
+ {
+ return (Exception)getCause();
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static RuntimeException wrap(Exception exception, String message)
+ {
+ return new WrappedException(message, exception);
+ }
+
+ public static RuntimeException wrap(Exception exception)
+ {
+ if (exception instanceof RuntimeException)
+ {
+ return (RuntimeException)exception;
+ }
+
+ return new WrappedException(exception);
+ }
+
+ public static Exception unwrap(Exception exception)
+ {
+ if (exception instanceof WrappedException)
+ {
+ return ((WrappedException)exception).exception();
+ }
+
+ return exception;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java index 00b6908a0a..c4de6167a0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java @@ -1,108 +1,108 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.concurrent.Worker; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; - -/** - * @author Eike Stepper - */ -public abstract class Cache<E> extends Worker implements ICache -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class); - - private ICacheMonitor cacheMonitor; - - private ICacheProbe cacheProbe; - - private ReferenceQueue<E> referenceQueue = new ReferenceQueue<E>(); - - public Cache() - { - } - - public ICacheMonitor getCacheMonitor() - { - return cacheMonitor; - } - - public void setCacheMonitor(ICacheMonitor cacheMonitor) - { - this.cacheMonitor = cacheMonitor; - } - - protected ICacheProbe getCacheProbe() - { - return cacheProbe; - } - - protected ReferenceQueue<E> getReferenceQueue() - { - return referenceQueue; - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (cacheMonitor == null) - { - throw new IllegalStateException("cacheMonitor == null"); //$NON-NLS-1$ - } - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - cacheProbe = cacheMonitor.registerCache(this); - } - - @Override - protected void doDeactivate() throws Exception - { - cacheMonitor.deregisterCache(this); - cacheProbe = null; - super.doDeactivate(); - } - - @Override - protected void work(WorkContext context) throws Exception - { - Reference<? extends E> reference = referenceQueue.remove(200); - if (reference != null) - { - unreachableElement(reference); - } - } - - protected void unreachableElement(Reference<? extends E> reference) - { - E element = reference.get(); - if (element != null) - { - unreachableElement(element); - } - } - - protected void unreachableElement(E element) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Unreachable: " + element); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.concurrent.Worker;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class Cache<E> extends Worker implements ICache
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class);
+
+ private ICacheMonitor cacheMonitor;
+
+ private ICacheProbe cacheProbe;
+
+ private ReferenceQueue<E> referenceQueue = new ReferenceQueue<E>();
+
+ public Cache()
+ {
+ }
+
+ public ICacheMonitor getCacheMonitor()
+ {
+ return cacheMonitor;
+ }
+
+ public void setCacheMonitor(ICacheMonitor cacheMonitor)
+ {
+ this.cacheMonitor = cacheMonitor;
+ }
+
+ protected ICacheProbe getCacheProbe()
+ {
+ return cacheProbe;
+ }
+
+ protected ReferenceQueue<E> getReferenceQueue()
+ {
+ return referenceQueue;
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (cacheMonitor == null)
+ {
+ throw new IllegalStateException("cacheMonitor == null"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ cacheProbe = cacheMonitor.registerCache(this);
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ cacheMonitor.deregisterCache(this);
+ cacheProbe = null;
+ super.doDeactivate();
+ }
+
+ @Override
+ protected void work(WorkContext context) throws Exception
+ {
+ Reference<? extends E> reference = referenceQueue.remove(200);
+ if (reference != null)
+ {
+ unreachableElement(reference);
+ }
+ }
+
+ protected void unreachableElement(Reference<? extends E> reference)
+ {
+ E element = reference.get();
+ if (element != null)
+ {
+ unreachableElement(element);
+ }
+ }
+
+ protected void unreachableElement(E element)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Unreachable: " + element); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java index 9ad020d686..f4dc24ce36 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java @@ -1,251 +1,251 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.ImplementationError; -import org.eclipse.net4j.util.concurrent.Worker; -import org.eclipse.net4j.util.event.Event; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public class CacheMonitor extends Worker implements ICacheMonitor -{ - // percentFreeAllocated = Round((freeMemory / totalMemory) * 100); - // percentAllocated = Round((totalMemory / maxMemory ) * 100); - - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CacheMonitor.class); - - private static final long DEFAULT_PAUSE_GREEN = 60L * 1000L; // 1 minute - - private static final long DEFAULT_PAUSE_YELLOW = 5L * 1000L; // 5 seconds - - private static final long DEFAULT_PAUSE_RED = 100L; // 100 milliseconds - - private long pauseGREEN = DEFAULT_PAUSE_GREEN; - - private long pauseYELLOW = DEFAULT_PAUSE_YELLOW; - - private long pauseRED = DEFAULT_PAUSE_RED; - - private ConditionPolicy conditionPolicy; - - private Condition condition; - - private Map<ICache, ICacheRegistration> registrations = new HashMap<ICache, ICacheRegistration>(); - - public CacheMonitor() - { - } - - public long getPauseGREEN() - { - return pauseGREEN; - } - - public void setPauseGREEN(long pauseGREEN) - { - this.pauseGREEN = pauseGREEN; - } - - public long getPauseYELLOW() - { - return pauseYELLOW; - } - - public void setPauseYELLOW(long pauseYELLOW) - { - this.pauseYELLOW = pauseYELLOW; - } - - public long getPauseRED() - { - return pauseRED; - } - - public void setPauseRED(long pauseRED) - { - this.pauseRED = pauseRED; - } - - public ConditionPolicy getConditionPolicy() - { - return conditionPolicy; - } - - public void setConditionPolicy(ConditionPolicy conditionPolicy) - { - this.conditionPolicy = conditionPolicy; - } - - public Condition getCondition() - { - return condition; - } - - public ICacheRegistration[] getRegistrations() - { - synchronized (registrations) - { - return registrations.values().toArray(new ICacheRegistration[registrations.size()]); - } - } - - public ICacheRegistration registerCache(ICache cache) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Registering cache " + cache); //$NON-NLS-1$ - } - - ICacheRegistration registration = new CacheRegistration(this, cache); - ICacheRegistration oldRegistration; - synchronized (registrations) - { - oldRegistration = registrations.put(cache, registration); - } - - if (oldRegistration != null) - { - oldRegistration.dispose(); - } - - return registration; - } - - public void deregisterCache(ICache cache) - { - ICacheRegistration registration; - synchronized (registrations) - { - registration = registrations.remove(cache); - } - - if (registration != null) - { - registration.dispose(); - if (TRACER.isEnabled()) - { - TRACER.trace("Deregistered cache " + cache); //$NON-NLS-1$ - } - } - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (conditionPolicy == null) - { - throw new IllegalStateException("conditionPolicy == null"); //$NON-NLS-1$ - } - } - - @Override - protected void doDeactivate() throws Exception - { - for (ICacheRegistration registration : getRegistrations()) - { - registration.dispose(); - } - - registrations.clear(); - super.doDeactivate(); - } - - @Override - protected void work(WorkContext context) throws Exception - { - Condition newCondition = conditionPolicy.getNewCondition(condition); - setCondition(newCondition); - - switch (newCondition) - { - case GREEN: - context.nextWork(pauseGREEN); - break; - - case YELLOW: - context.nextWork(pauseYELLOW); - break; - - case RED: - handleConditionRED(); - context.nextWork(pauseRED); - break; - } - } - - protected void setCondition(Condition newCondition) - { - if (newCondition == null) - { - throw new ImplementationError("newCondition == null"); //$NON-NLS-1$ - } - - Condition oldCondition = condition; - if (newCondition != oldCondition) - { - condition = newCondition; - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new CacheMonitorEvent(oldCondition, newCondition), listeners); - } - } - } - - protected void handleConditionRED() - { - OM.LOG.warn("CONDITION RED"); //$NON-NLS-1$ - } - - /** - * @author Eike Stepper - */ - private final class CacheMonitorEvent extends Event implements ICacheMonitorEvent - { - private static final long serialVersionUID = 1L; - - private Condition oldCondition; - - private Condition newCondition; - - public CacheMonitorEvent(Condition oldCondition, Condition newCondition) - { - super(CacheMonitor.this); - this.oldCondition = oldCondition; - this.newCondition = newCondition; - } - - @Override - public ICacheMonitor getSource() - { - return (ICacheMonitor)super.getSource(); - } - - public Condition getOldCondition() - { - return oldCondition; - } - - public Condition getNewCondition() - { - return newCondition; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.ImplementationError;
+import org.eclipse.net4j.util.concurrent.Worker;
+import org.eclipse.net4j.util.event.Event;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public class CacheMonitor extends Worker implements ICacheMonitor
+{
+ // percentFreeAllocated = Round((freeMemory / totalMemory) * 100);
+ // percentAllocated = Round((totalMemory / maxMemory ) * 100);
+
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CacheMonitor.class);
+
+ private static final long DEFAULT_PAUSE_GREEN = 60L * 1000L; // 1 minute
+
+ private static final long DEFAULT_PAUSE_YELLOW = 5L * 1000L; // 5 seconds
+
+ private static final long DEFAULT_PAUSE_RED = 100L; // 100 milliseconds
+
+ private long pauseGREEN = DEFAULT_PAUSE_GREEN;
+
+ private long pauseYELLOW = DEFAULT_PAUSE_YELLOW;
+
+ private long pauseRED = DEFAULT_PAUSE_RED;
+
+ private ConditionPolicy conditionPolicy;
+
+ private Condition condition;
+
+ private Map<ICache, ICacheRegistration> registrations = new HashMap<ICache, ICacheRegistration>();
+
+ public CacheMonitor()
+ {
+ }
+
+ public long getPauseGREEN()
+ {
+ return pauseGREEN;
+ }
+
+ public void setPauseGREEN(long pauseGREEN)
+ {
+ this.pauseGREEN = pauseGREEN;
+ }
+
+ public long getPauseYELLOW()
+ {
+ return pauseYELLOW;
+ }
+
+ public void setPauseYELLOW(long pauseYELLOW)
+ {
+ this.pauseYELLOW = pauseYELLOW;
+ }
+
+ public long getPauseRED()
+ {
+ return pauseRED;
+ }
+
+ public void setPauseRED(long pauseRED)
+ {
+ this.pauseRED = pauseRED;
+ }
+
+ public ConditionPolicy getConditionPolicy()
+ {
+ return conditionPolicy;
+ }
+
+ public void setConditionPolicy(ConditionPolicy conditionPolicy)
+ {
+ this.conditionPolicy = conditionPolicy;
+ }
+
+ public Condition getCondition()
+ {
+ return condition;
+ }
+
+ public ICacheRegistration[] getRegistrations()
+ {
+ synchronized (registrations)
+ {
+ return registrations.values().toArray(new ICacheRegistration[registrations.size()]);
+ }
+ }
+
+ public ICacheRegistration registerCache(ICache cache)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Registering cache " + cache); //$NON-NLS-1$
+ }
+
+ ICacheRegistration registration = new CacheRegistration(this, cache);
+ ICacheRegistration oldRegistration;
+ synchronized (registrations)
+ {
+ oldRegistration = registrations.put(cache, registration);
+ }
+
+ if (oldRegistration != null)
+ {
+ oldRegistration.dispose();
+ }
+
+ return registration;
+ }
+
+ public void deregisterCache(ICache cache)
+ {
+ ICacheRegistration registration;
+ synchronized (registrations)
+ {
+ registration = registrations.remove(cache);
+ }
+
+ if (registration != null)
+ {
+ registration.dispose();
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Deregistered cache " + cache); //$NON-NLS-1$
+ }
+ }
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (conditionPolicy == null)
+ {
+ throw new IllegalStateException("conditionPolicy == null"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ for (ICacheRegistration registration : getRegistrations())
+ {
+ registration.dispose();
+ }
+
+ registrations.clear();
+ super.doDeactivate();
+ }
+
+ @Override
+ protected void work(WorkContext context) throws Exception
+ {
+ Condition newCondition = conditionPolicy.getNewCondition(condition);
+ setCondition(newCondition);
+
+ switch (newCondition)
+ {
+ case GREEN:
+ context.nextWork(pauseGREEN);
+ break;
+
+ case YELLOW:
+ context.nextWork(pauseYELLOW);
+ break;
+
+ case RED:
+ handleConditionRED();
+ context.nextWork(pauseRED);
+ break;
+ }
+ }
+
+ protected void setCondition(Condition newCondition)
+ {
+ if (newCondition == null)
+ {
+ throw new ImplementationError("newCondition == null"); //$NON-NLS-1$
+ }
+
+ Condition oldCondition = condition;
+ if (newCondition != oldCondition)
+ {
+ condition = newCondition;
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new CacheMonitorEvent(oldCondition, newCondition), listeners);
+ }
+ }
+ }
+
+ protected void handleConditionRED()
+ {
+ OM.LOG.warn("CONDITION RED"); //$NON-NLS-1$
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class CacheMonitorEvent extends Event implements ICacheMonitorEvent
+ {
+ private static final long serialVersionUID = 1L;
+
+ private Condition oldCondition;
+
+ private Condition newCondition;
+
+ public CacheMonitorEvent(Condition oldCondition, Condition newCondition)
+ {
+ super(CacheMonitor.this);
+ this.oldCondition = oldCondition;
+ this.newCondition = newCondition;
+ }
+
+ @Override
+ public ICacheMonitor getSource()
+ {
+ return (ICacheMonitor)super.getSource();
+ }
+
+ public Condition getOldCondition()
+ {
+ return oldCondition;
+ }
+
+ public Condition getNewCondition()
+ {
+ return newCondition;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java index a6b8fe976f..43e5f0edf2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java @@ -1,110 +1,110 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -/** - * @author Eike Stepper - */ -public class CacheRegistration implements ICacheRegistration -{ - public static final float DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR = 0.1f; - - private ICacheMonitor cacheMonitor; - - private ICache cache; - - private int elementCount; - - private long cacheSize; - - private long reconstructionCost; - - public CacheRegistration(ICacheMonitor cacheMonitor, ICache cache) - { - this.cacheMonitor = cacheMonitor; - this.cache = cache; - } - - public void dispose() - { - cacheMonitor = null; - cache = null; - } - - public boolean isDisposed() - { - return cacheMonitor == null || cache == null; - } - - public ICacheMonitor getCacheMonitor() - { - return cacheMonitor; - } - - public ICache getCache() - { - return cache; - } - - public int getElementCount() - { - return elementCount; - } - - public long getCacheSize() - { - return cacheSize; - } - - public long getAverageElementSize() - { - return cacheSize / elementCount; - } - - public long getReconstructionCost() - { - return reconstructionCost; - } - - public void elementCached(int elementSize) - { - checkDisposal(); - ++elementCount; - cacheSize += elementSize; - } - - public void elementEvicted(int elementSize) - { - checkDisposal(); - --elementCount; - cacheSize -= elementSize; - } - - public void elementReconstructed(long reconstructionTime) - { - checkDisposal(); - float decayFactor = getReconstructionCostDecayFactor(); - reconstructionCost = (long)(decayFactor * reconstructionCost + (1 - decayFactor) * reconstructionTime); - } - - protected float getReconstructionCostDecayFactor() - { - return DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR; - } - - private void checkDisposal() - { - if (isDisposed()) - { - throw new IllegalStateException("disposed"); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+/**
+ * @author Eike Stepper
+ */
+public class CacheRegistration implements ICacheRegistration
+{
+ public static final float DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR = 0.1f;
+
+ private ICacheMonitor cacheMonitor;
+
+ private ICache cache;
+
+ private int elementCount;
+
+ private long cacheSize;
+
+ private long reconstructionCost;
+
+ public CacheRegistration(ICacheMonitor cacheMonitor, ICache cache)
+ {
+ this.cacheMonitor = cacheMonitor;
+ this.cache = cache;
+ }
+
+ public void dispose()
+ {
+ cacheMonitor = null;
+ cache = null;
+ }
+
+ public boolean isDisposed()
+ {
+ return cacheMonitor == null || cache == null;
+ }
+
+ public ICacheMonitor getCacheMonitor()
+ {
+ return cacheMonitor;
+ }
+
+ public ICache getCache()
+ {
+ return cache;
+ }
+
+ public int getElementCount()
+ {
+ return elementCount;
+ }
+
+ public long getCacheSize()
+ {
+ return cacheSize;
+ }
+
+ public long getAverageElementSize()
+ {
+ return cacheSize / elementCount;
+ }
+
+ public long getReconstructionCost()
+ {
+ return reconstructionCost;
+ }
+
+ public void elementCached(int elementSize)
+ {
+ checkDisposal();
+ ++elementCount;
+ cacheSize += elementSize;
+ }
+
+ public void elementEvicted(int elementSize)
+ {
+ checkDisposal();
+ --elementCount;
+ cacheSize -= elementSize;
+ }
+
+ public void elementReconstructed(long reconstructionTime)
+ {
+ checkDisposal();
+ float decayFactor = getReconstructionCostDecayFactor();
+ reconstructionCost = (long)(decayFactor * reconstructionCost + (1 - decayFactor) * reconstructionTime);
+ }
+
+ protected float getReconstructionCostDecayFactor()
+ {
+ return DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR;
+ }
+
+ private void checkDisposal()
+ {
+ if (isDisposed())
+ {
+ throw new IllegalStateException("disposed"); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java index d6a6c08c1b..a341c9fe97 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java @@ -1,105 +1,105 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -import org.eclipse.net4j.util.cache.ICacheMonitor.Condition; - -/** - * @author Eike Stepper - */ -public class HysteresisConditionPolicy extends ThresholdConditionPolicy -{ - private long thresholdYellowRed; - - private long thresholdGreenYellow; - - public HysteresisConditionPolicy(long thresholdYellowRed, long thresholdRedYellow, long thresholdGreenYellow, - long thresholdYellowGreen) - { - super(thresholdRedYellow, thresholdYellowGreen); - if (thresholdYellowRed > thresholdRedYellow) - { - throw new IllegalArgumentException("thresholdYellowRed > thresholdRedYellow"); //$NON-NLS-1$ - } - - if (thresholdRedYellow > thresholdGreenYellow) - { - throw new IllegalArgumentException("thresholdRedYellow > thresholdGreenYellow"); //$NON-NLS-1$ - } - - if (thresholdGreenYellow > thresholdYellowGreen) - { - throw new IllegalArgumentException("thresholdGreenYellow > thresholdYellowGreen"); //$NON-NLS-1$ - } - - this.thresholdGreenYellow = thresholdGreenYellow; - this.thresholdYellowRed = thresholdYellowRed; - } - - public long getThresholdYellowRed() - { - return thresholdYellowRed; - } - - public long getThresholdGreenYellow() - { - return thresholdGreenYellow; - } - - @Override - protected Condition getNewCondition(Condition oldCondition, long freeMemory) - { - switch (oldCondition) - { - case GREEN: - if (freeMemory < thresholdYellowRed) - { - return Condition.RED; - } - - if (freeMemory < thresholdGreenYellow) - { - return Condition.YELLOW; - } - - return Condition.GREEN; - - case YELLOW: - if (freeMemory < thresholdYellowRed) - { - return Condition.RED; - } - - if (freeMemory > getThresholdYellowGreen()) - { - return Condition.GREEN; - } - - return Condition.YELLOW; - - case RED: - if (freeMemory > getThresholdYellowGreen()) - { - return Condition.GREEN; - } - - if (freeMemory > getThresholdRedYellow()) - { - return Condition.YELLOW; - } - - return Condition.RED; - - default: - throw new IllegalArgumentException("oldCondition == " + oldCondition); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+import org.eclipse.net4j.util.cache.ICacheMonitor.Condition;
+
+/**
+ * @author Eike Stepper
+ */
+public class HysteresisConditionPolicy extends ThresholdConditionPolicy
+{
+ private long thresholdYellowRed;
+
+ private long thresholdGreenYellow;
+
+ public HysteresisConditionPolicy(long thresholdYellowRed, long thresholdRedYellow, long thresholdGreenYellow,
+ long thresholdYellowGreen)
+ {
+ super(thresholdRedYellow, thresholdYellowGreen);
+ if (thresholdYellowRed > thresholdRedYellow)
+ {
+ throw new IllegalArgumentException("thresholdYellowRed > thresholdRedYellow"); //$NON-NLS-1$
+ }
+
+ if (thresholdRedYellow > thresholdGreenYellow)
+ {
+ throw new IllegalArgumentException("thresholdRedYellow > thresholdGreenYellow"); //$NON-NLS-1$
+ }
+
+ if (thresholdGreenYellow > thresholdYellowGreen)
+ {
+ throw new IllegalArgumentException("thresholdGreenYellow > thresholdYellowGreen"); //$NON-NLS-1$
+ }
+
+ this.thresholdGreenYellow = thresholdGreenYellow;
+ this.thresholdYellowRed = thresholdYellowRed;
+ }
+
+ public long getThresholdYellowRed()
+ {
+ return thresholdYellowRed;
+ }
+
+ public long getThresholdGreenYellow()
+ {
+ return thresholdGreenYellow;
+ }
+
+ @Override
+ protected Condition getNewCondition(Condition oldCondition, long freeMemory)
+ {
+ switch (oldCondition)
+ {
+ case GREEN:
+ if (freeMemory < thresholdYellowRed)
+ {
+ return Condition.RED;
+ }
+
+ if (freeMemory < thresholdGreenYellow)
+ {
+ return Condition.YELLOW;
+ }
+
+ return Condition.GREEN;
+
+ case YELLOW:
+ if (freeMemory < thresholdYellowRed)
+ {
+ return Condition.RED;
+ }
+
+ if (freeMemory > getThresholdYellowGreen())
+ {
+ return Condition.GREEN;
+ }
+
+ return Condition.YELLOW;
+
+ case RED:
+ if (freeMemory > getThresholdYellowGreen())
+ {
+ return Condition.GREEN;
+ }
+
+ if (freeMemory > getThresholdRedYellow())
+ {
+ return Condition.YELLOW;
+ }
+
+ return Condition.RED;
+
+ default:
+ throw new IllegalArgumentException("oldCondition == " + oldCondition); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java index 8fd6c44e8d..43c55009fa 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -/** - * @author Eike Stepper - */ -public interface ICache -{ - public ICacheMonitor getCacheMonitor(); - - /** - * Instructs this cache to evict <b>elementCount</b> elements. - */ - public void evictElements(int elementCount); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICache
+{
+ public ICacheMonitor getCacheMonitor();
+
+ /**
+ * Instructs this cache to evict <b>elementCount</b> elements.
+ */
+ public void evictElements(int elementCount);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java index d795c7bc3a..f8c9aefb6d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java @@ -1,60 +1,60 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -import org.eclipse.net4j.util.event.INotifier; - -/** - * @author Eike Stepper - */ -public interface ICacheMonitor extends INotifier -{ - public ConditionPolicy getConditionPolicy(); - - public Condition getCondition(); - - public ICacheProbe registerCache(ICache cache); - - public void deregisterCache(ICache cache); - - /** - * @author Eike Stepper - */ - public enum Condition - { - /** - * Condition <b>GREEN</b> indicates that the system is operating normally and enough free memory is available so - * that caches are free to cache additional elements. - */ - GREEN, - - /** - * Condition <b>YELLOW</b> indicates that the system is operating normally but free memory is about to go low so - * that caches should stop to cache additional elements. - */ - YELLOW, - - /** - * Condition <b>RED</b> indicates that the system state is critical and free memory is almost exhausted so that - * caches must immediately stop to cache additional elements. Depending of the eviction strategy element eviction is - * ordered. - */ - RED; - } - - /** - * @author Eike Stepper - */ - public interface ConditionPolicy - { - public Condition getNewCondition(Condition oldCondition); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+import org.eclipse.net4j.util.event.INotifier;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICacheMonitor extends INotifier
+{
+ public ConditionPolicy getConditionPolicy();
+
+ public Condition getCondition();
+
+ public ICacheProbe registerCache(ICache cache);
+
+ public void deregisterCache(ICache cache);
+
+ /**
+ * @author Eike Stepper
+ */
+ public enum Condition
+ {
+ /**
+ * Condition <b>GREEN</b> indicates that the system is operating normally and enough free memory is available so
+ * that caches are free to cache additional elements.
+ */
+ GREEN,
+
+ /**
+ * Condition <b>YELLOW</b> indicates that the system is operating normally but free memory is about to go low so
+ * that caches should stop to cache additional elements.
+ */
+ YELLOW,
+
+ /**
+ * Condition <b>RED</b> indicates that the system state is critical and free memory is almost exhausted so that
+ * caches must immediately stop to cache additional elements. Depending of the eviction strategy element eviction is
+ * ordered.
+ */
+ RED;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public interface ConditionPolicy
+ {
+ public Condition getNewCondition(Condition oldCondition);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java index 5f82e55068..9ebebc683e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java @@ -1,30 +1,30 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -import org.eclipse.net4j.util.event.IEvent; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface ICacheMonitorEvent extends IEvent -{ - /** - * @since 3.0 - */ - public ICacheMonitor getSource(); - - public ICacheMonitor.Condition getOldCondition(); - - public ICacheMonitor.Condition getNewCondition(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+import org.eclipse.net4j.util.event.IEvent;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface ICacheMonitorEvent extends IEvent
+{
+ /**
+ * @since 3.0
+ */
+ public ICacheMonitor getSource();
+
+ public ICacheMonitor.Condition getOldCondition();
+
+ public ICacheMonitor.Condition getNewCondition();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java index b2919ed265..e4c9c93074 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java @@ -1,33 +1,33 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -/** - * @author Eike Stepper - */ -public interface ICacheProbe -{ - public boolean isDisposed(); - - public void elementCached(int elementSize); - - public void elementEvicted(int elementSize); - - public void elementReconstructed(long reconstructionTime); - - public int getElementCount(); - - public long getCacheSize(); - - public long getAverageElementSize(); - - public long getReconstructionCost(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICacheProbe
+{
+ public boolean isDisposed();
+
+ public void elementCached(int elementSize);
+
+ public void elementEvicted(int elementSize);
+
+ public void elementReconstructed(long reconstructionTime);
+
+ public int getElementCount();
+
+ public long getCacheSize();
+
+ public long getAverageElementSize();
+
+ public long getReconstructionCost();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java index 3a95717d77..7cc730a3f2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java @@ -1,23 +1,23 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -/** - * @author Eike Stepper - */ -public interface ICacheRegistration extends ICacheProbe -{ - public ICacheMonitor getCacheMonitor(); - - public ICache getCache(); - - public void dispose(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICacheRegistration extends ICacheProbe
+{
+ public ICacheMonitor getCacheMonitor();
+
+ public ICache getCache();
+
+ public void dispose();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java index 2883bb64d8..01a228948d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java @@ -1,64 +1,64 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.cache; - -import org.eclipse.net4j.util.cache.ICacheMonitor.Condition; - -/** - * @author Eike Stepper - */ -public class ThresholdConditionPolicy implements ICacheMonitor.ConditionPolicy -{ - private long thresholdRedYellow; - - private long thresholdYellowGreen; - - public ThresholdConditionPolicy(long thresholdRedYellow, long thresholdYellowGreen) - { - if (thresholdRedYellow > thresholdYellowGreen) - { - throw new IllegalArgumentException("thresholdRedYellow > thresholdYellowGreen"); //$NON-NLS-1$ - } - - this.thresholdRedYellow = thresholdRedYellow; - this.thresholdYellowGreen = thresholdYellowGreen; - } - - public long getThresholdRedYellow() - { - return thresholdRedYellow; - } - - public long getThresholdYellowGreen() - { - return thresholdYellowGreen; - } - - public Condition getNewCondition(Condition oldCondition) - { - return getNewCondition(oldCondition, Runtime.getRuntime().freeMemory()); - } - - protected Condition getNewCondition(Condition oldCondition, long freeMemory) - { - if (freeMemory > thresholdYellowGreen) - { - return Condition.GREEN; - } - - if (freeMemory > thresholdRedYellow) - { - return Condition.YELLOW; - } - - return Condition.RED; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.cache;
+
+import org.eclipse.net4j.util.cache.ICacheMonitor.Condition;
+
+/**
+ * @author Eike Stepper
+ */
+public class ThresholdConditionPolicy implements ICacheMonitor.ConditionPolicy
+{
+ private long thresholdRedYellow;
+
+ private long thresholdYellowGreen;
+
+ public ThresholdConditionPolicy(long thresholdRedYellow, long thresholdYellowGreen)
+ {
+ if (thresholdRedYellow > thresholdYellowGreen)
+ {
+ throw new IllegalArgumentException("thresholdRedYellow > thresholdYellowGreen"); //$NON-NLS-1$
+ }
+
+ this.thresholdRedYellow = thresholdRedYellow;
+ this.thresholdYellowGreen = thresholdYellowGreen;
+ }
+
+ public long getThresholdRedYellow()
+ {
+ return thresholdRedYellow;
+ }
+
+ public long getThresholdYellowGreen()
+ {
+ return thresholdYellowGreen;
+ }
+
+ public Condition getNewCondition(Condition oldCondition)
+ {
+ return getNewCondition(oldCondition, Runtime.getRuntime().freeMemory());
+ }
+
+ protected Condition getNewCondition(Condition oldCondition, long freeMemory)
+ {
+ if (freeMemory > thresholdYellowGreen)
+ {
+ return Condition.GREEN;
+ }
+
+ if (freeMemory > thresholdRedYellow)
+ {
+ return Condition.YELLOW;
+ }
+
+ return Condition.RED;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java index 1049573dce..dc74f11f66 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java index 897a487bb0..37a4ffd0ed 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java index 9f8b282702..c7ecb0b8b9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java @@ -1,72 +1,72 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * An object that iterates over the elements of an array - * - * @author Eike Stepper - * @since 3.0 - */ -public class ArrayIterator<T> implements Iterator<T> -{ - private T[] elements; - - private int index; - - private int lastElement; - - public ArrayIterator(T[] elements) - { - this(elements, 0, elements.length - 1); - } - - public ArrayIterator(T[] elements, int firstElement) - { - this(elements, firstElement, elements.length - 1); - } - - public ArrayIterator(T[] elements, int firstElement, int lastElement) - { - this.elements = elements; - index = firstElement; - this.lastElement = lastElement; - } - - public boolean hasNext() - { - return elements != null && index <= lastElement; - } - - public T next() throws NoSuchElementException - { - if (!hasNext()) - { - throw new NoSuchElementException(); - } - - return elements[index++]; - } - - /** - * Unsupported. - * - * @throws UnsupportedOperationException - * always - */ - public void remove() - { - throw new UnsupportedOperationException(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+
+/**
+ * An object that iterates over the elements of an array
+ *
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public class ArrayIterator<T> implements Iterator<T>
+{
+ private T[] elements;
+
+ private int index;
+
+ private int lastElement;
+
+ public ArrayIterator(T[] elements)
+ {
+ this(elements, 0, elements.length - 1);
+ }
+
+ public ArrayIterator(T[] elements, int firstElement)
+ {
+ this(elements, firstElement, elements.length - 1);
+ }
+
+ public ArrayIterator(T[] elements, int firstElement, int lastElement)
+ {
+ this.elements = elements;
+ index = firstElement;
+ this.lastElement = lastElement;
+ }
+
+ public boolean hasNext()
+ {
+ return elements != null && index <= lastElement;
+ }
+
+ public T next() throws NoSuchElementException
+ {
+ if (!hasNext())
+ {
+ throw new NoSuchElementException();
+ }
+
+ return elements[index++];
+ }
+
+ /**
+ * Unsupported.
+ *
+ * @throws UnsupportedOperationException
+ * always
+ */
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java index 6c5867de5c..8d04d15bff 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java @@ -1,80 +1,80 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.HashMap; -import java.util.Map; - -/** - * @since 2.0 - * @author Eike Stepper - */ -public class BidiMapper<T1, T2> -{ - private Map<T1, T2> map1 = new HashMap<T1, T2>(); - - private Map<T2, T1> map2 = new HashMap<T2, T1>(); - - public BidiMapper() - { - } - - public synchronized void map(T1 v1, T2 v2) - { - map1.put(v1, v2); - map2.put(v2, v1); - } - - public synchronized int size() - { - return map1.size(); - } - - public synchronized void clear() - { - map1.clear(); - map2.clear(); - } - - public synchronized T2 lookup1(T1 v1) - { - return map1.get(v1); - } - - public synchronized T1 lookup2(T2 v2) - { - return map2.get(v2); - } - - public synchronized boolean remove1(T1 v1) - { - T2 v2 = map1.remove(v1); - if (v2 != null) - { - map2.remove(v2); - return true; - } - - return false; - } - - public synchronized boolean remove2(T2 v2) - { - T1 v1 = map2.remove(v2); - if (v1 != null) - { - map1.remove(v1); - return true; - } - - return false; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @since 2.0
+ * @author Eike Stepper
+ */
+public class BidiMapper<T1, T2>
+{
+ private Map<T1, T2> map1 = new HashMap<T1, T2>();
+
+ private Map<T2, T1> map2 = new HashMap<T2, T1>();
+
+ public BidiMapper()
+ {
+ }
+
+ public synchronized void map(T1 v1, T2 v2)
+ {
+ map1.put(v1, v2);
+ map2.put(v2, v1);
+ }
+
+ public synchronized int size()
+ {
+ return map1.size();
+ }
+
+ public synchronized void clear()
+ {
+ map1.clear();
+ map2.clear();
+ }
+
+ public synchronized T2 lookup1(T1 v1)
+ {
+ return map1.get(v1);
+ }
+
+ public synchronized T1 lookup2(T2 v2)
+ {
+ return map2.get(v2);
+ }
+
+ public synchronized boolean remove1(T1 v1)
+ {
+ T2 v2 = map1.remove(v1);
+ if (v2 != null)
+ {
+ map2.remove(v2);
+ return true;
+ }
+
+ return false;
+ }
+
+ public synchronized boolean remove2(T2 v2)
+ {
+ T1 v1 = map2.remove(v2);
+ if (v1 != null)
+ {
+ map1.remove(v1);
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java index 5b0e66f672..cfb6629f7f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java @@ -1,76 +1,76 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.CheckUtil; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -/** - * @author Eike Stepper - * @since 3.2 - */ -public final class ByteArrayWrapper -{ - private final byte[] data; - - public ByteArrayWrapper(byte[] data) - { - CheckUtil.checkArg(data, "data"); - this.data = data; - } - - public byte[] getData() - { - return data; - } - - @Override - public boolean equals(Object other) - { - if (other instanceof ByteArrayWrapper) - { - return Arrays.equals(data, ((ByteArrayWrapper)other).data); - } - - return false; - } - - @Override - public int hashCode() - { - return Arrays.hashCode(data); - } - - @Override - public String toString() - { - return data.toString(); - } - - public static Set<byte[]> toByteArray(Set<ByteArrayWrapper> wrappers) - { - if (wrappers == null) - { - return null; - } - - Set<byte[]> result = new HashSet<byte[]>(); - for (ByteArrayWrapper wrapper : wrappers) - { - result.add(wrapper.getData()); - } - - return result; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.CheckUtil;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public final class ByteArrayWrapper
+{
+ private final byte[] data;
+
+ public ByteArrayWrapper(byte[] data)
+ {
+ CheckUtil.checkArg(data, "data");
+ this.data = data;
+ }
+
+ public byte[] getData()
+ {
+ return data;
+ }
+
+ @Override
+ public boolean equals(Object other)
+ {
+ if (other instanceof ByteArrayWrapper)
+ {
+ return Arrays.equals(data, ((ByteArrayWrapper)other).data);
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Arrays.hashCode(data);
+ }
+
+ @Override
+ public String toString()
+ {
+ return data.toString();
+ }
+
+ public static Set<byte[]> toByteArray(Set<ByteArrayWrapper> wrappers)
+ {
+ if (wrappers == null)
+ {
+ return null;
+ }
+
+ Set<byte[]> result = new HashSet<byte[]>();
+ for (ByteArrayWrapper wrapper : wrappers)
+ {
+ result.add(wrapper.getData());
+ }
+
+ return result;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java index 453e2e451f..2aafff27bd 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java index f6708a338c..1933ca6609 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -/** - * @author Eike Stepper - */ -public interface Closeable -{ - public void close(); - - /** - * @since 2.0 - */ - public boolean isClosed(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+/**
+ * @author Eike Stepper
+ */
+public interface Closeable
+{
+ public void close();
+
+ /**
+ * @since 2.0
+ */
+ public boolean isClosed();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java index 917dd11cc6..6af4c708cc 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.Iterator; - -/** - * A closeable iterator. - * - * @author Eike Stepper - */ -public interface CloseableIterator<E> extends Iterator<E>, Closeable -{ -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.Iterator;
+
+/**
+ * A closeable iterator.
+ *
+ * @author Eike Stepper
+ */
+public interface CloseableIterator<E> extends Iterator<E>, Closeable
+{
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java index 6bd88eba81..4dc217c537 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java @@ -1,203 +1,203 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -/** - * @author Eike Stepper - * @since 3.2 - */ -public abstract class ConcurrentArray<E> -{ - protected E[] elements; - - private final E[] EMPTY = newArray(0); - - public ConcurrentArray() - { - } - - public boolean isEmpty() - { - return elements == null; - } - - /** - * Returns the elements, never <code>null</code>. - */ - public E[] get() - { - return elements == null ? EMPTY : elements; - } - - public synchronized void add(E element) - { - if (!validate(element)) - { - return; - } - - if (elements == null) - { - E[] array = newArray(1); - array[0] = element; - elements = array; - firstElementAdded(); - } - else - { - int length = elements.length; - E[] array = newArray(length + 1); - System.arraycopy(elements, 0, array, 0, length); - array[length] = element; - elements = array; - } - } - - public synchronized boolean remove(E element) - { - if (elements != null) - { - int length = elements.length; - if (length == 1) - { - if (elements[0] == element) - { - elements = null; - lastElementRemoved(); - return true; - } - } - else - { - for (int i = 0; i < length; i++) - { - E e = elements[i]; - if (e == element) - { - E[] array = newArray(length - 1); - - if (i > 0) - { - System.arraycopy(elements, 0, array, 0, i); - } - - if (i + 1 <= length - 1) - { - System.arraycopy(elements, i + 1, array, i, length - 1 - i); - } - - elements = array; - return true; - } - } - } - } - - return false; - } - - protected boolean validate(E element) - { - return true; - } - - protected void firstElementAdded() - { - } - - protected void lastElementRemoved() - { - } - - protected abstract E[] newArray(int length); - - /** - * @author Eike Stepper - */ - public abstract static class Unique<E> extends ConcurrentArray<E> - { - public Unique() - { - } - - @Override - protected boolean validate(E element) - { - if (elements != null) - { - for (int i = 0; i < elements.length; i++) - { - if (equals(element, elements[i])) - { - violatingUniqueness(element); - return false; - } - } - } - - return true; - } - - protected boolean equals(E e1, E e2) - { - return e1 == e2; - } - - protected void violatingUniqueness(E element) - { - } - } - - /** - * @author Eike Stepper - */ - public abstract static class DuplicateCounter<E> extends ConcurrentArray<E> - { - private int maxDuplicates; - - public DuplicateCounter() - { - } - - public final int getMaxDuplicates() - { - return maxDuplicates; - } - - @Override - protected boolean validate(E element) - { - if (elements != null) - { - int duplicates = 0; - for (int i = 0; i < elements.length; i++) - { - if (equals(element, elements[i])) - { - ++duplicates; - } - } - - if (duplicates > maxDuplicates) - { - maxDuplicates = duplicates; - } - } - - return true; - } - - protected boolean equals(E e1, E e2) - { - return e1 == e2; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+/**
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public abstract class ConcurrentArray<E>
+{
+ protected E[] elements;
+
+ private final E[] EMPTY = newArray(0);
+
+ public ConcurrentArray()
+ {
+ }
+
+ public boolean isEmpty()
+ {
+ return elements == null;
+ }
+
+ /**
+ * Returns the elements, never <code>null</code>.
+ */
+ public E[] get()
+ {
+ return elements == null ? EMPTY : elements;
+ }
+
+ public synchronized void add(E element)
+ {
+ if (!validate(element))
+ {
+ return;
+ }
+
+ if (elements == null)
+ {
+ E[] array = newArray(1);
+ array[0] = element;
+ elements = array;
+ firstElementAdded();
+ }
+ else
+ {
+ int length = elements.length;
+ E[] array = newArray(length + 1);
+ System.arraycopy(elements, 0, array, 0, length);
+ array[length] = element;
+ elements = array;
+ }
+ }
+
+ public synchronized boolean remove(E element)
+ {
+ if (elements != null)
+ {
+ int length = elements.length;
+ if (length == 1)
+ {
+ if (elements[0] == element)
+ {
+ elements = null;
+ lastElementRemoved();
+ return true;
+ }
+ }
+ else
+ {
+ for (int i = 0; i < length; i++)
+ {
+ E e = elements[i];
+ if (e == element)
+ {
+ E[] array = newArray(length - 1);
+
+ if (i > 0)
+ {
+ System.arraycopy(elements, 0, array, 0, i);
+ }
+
+ if (i + 1 <= length - 1)
+ {
+ System.arraycopy(elements, i + 1, array, i, length - 1 - i);
+ }
+
+ elements = array;
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ protected boolean validate(E element)
+ {
+ return true;
+ }
+
+ protected void firstElementAdded()
+ {
+ }
+
+ protected void lastElementRemoved()
+ {
+ }
+
+ protected abstract E[] newArray(int length);
+
+ /**
+ * @author Eike Stepper
+ */
+ public abstract static class Unique<E> extends ConcurrentArray<E>
+ {
+ public Unique()
+ {
+ }
+
+ @Override
+ protected boolean validate(E element)
+ {
+ if (elements != null)
+ {
+ for (int i = 0; i < elements.length; i++)
+ {
+ if (equals(element, elements[i]))
+ {
+ violatingUniqueness(element);
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ protected boolean equals(E e1, E e2)
+ {
+ return e1 == e2;
+ }
+
+ protected void violatingUniqueness(E element)
+ {
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public abstract static class DuplicateCounter<E> extends ConcurrentArray<E>
+ {
+ private int maxDuplicates;
+
+ public DuplicateCounter()
+ {
+ }
+
+ public final int getMaxDuplicates()
+ {
+ return maxDuplicates;
+ }
+
+ @Override
+ protected boolean validate(E element)
+ {
+ if (elements != null)
+ {
+ int duplicates = 0;
+ for (int i = 0; i < elements.length; i++)
+ {
+ if (equals(element, elements[i]))
+ {
+ ++duplicates;
+ }
+ }
+
+ if (duplicates > maxDuplicates)
+ {
+ maxDuplicates = duplicates;
+ }
+ }
+
+ return true;
+ }
+
+ protected boolean equals(E e1, E e2)
+ {
+ return e1 == e2;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java index 54ef6c436b..c6b345d73d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java @@ -1,97 +1,97 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class DynamicArray<E> -{ - private Object[] elements = {}; - - public DynamicArray() - { - } - - public int add(E element) - { - int length = elements.length; - for (int i = 0; i < length; i++) - { - if (elements[i] == null) - { - elements[i] = element; - return i; - } - } - - grow(length); - elements[length] = element; - return length; - } - - @SuppressWarnings("unchecked") - public E add(int index, E element) - { - grow(index); - Object old = elements[index]; - elements[index] = element; - return (E)old; - } - - @SuppressWarnings("unchecked") - public E remove(int index) - { - Object old = elements[index]; - if (old != null) - { - elements[index] = null; - shrink(); - } - - return (E)old; - } - - @SuppressWarnings("unchecked") - public E get(int index) - { - return (E)elements[index]; - } - - private void grow(int index) - { - if (index >= elements.length) - { - Object[] newChannels = new Object[index + 1]; - System.arraycopy(elements, 0, newChannels, 0, elements.length); - elements = newChannels; - } - } - - private void shrink() - { - boolean shrink = false; - int lastIndex = elements.length - 1; - while (lastIndex > 0 && (shrink = elements[lastIndex] == null)) - { - --lastIndex; - } - - if (shrink) - { - int newLength = lastIndex + 1; - Object[] newChannels = new Object[newLength]; - System.arraycopy(elements, 0, newChannels, 0, newLength); - elements = newChannels; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class DynamicArray<E>
+{
+ private Object[] elements = {};
+
+ public DynamicArray()
+ {
+ }
+
+ public int add(E element)
+ {
+ int length = elements.length;
+ for (int i = 0; i < length; i++)
+ {
+ if (elements[i] == null)
+ {
+ elements[i] = element;
+ return i;
+ }
+ }
+
+ grow(length);
+ elements[length] = element;
+ return length;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E add(int index, E element)
+ {
+ grow(index);
+ Object old = elements[index];
+ elements[index] = element;
+ return (E)old;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E remove(int index)
+ {
+ Object old = elements[index];
+ if (old != null)
+ {
+ elements[index] = null;
+ shrink();
+ }
+
+ return (E)old;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E get(int index)
+ {
+ return (E)elements[index];
+ }
+
+ private void grow(int index)
+ {
+ if (index >= elements.length)
+ {
+ Object[] newChannels = new Object[index + 1];
+ System.arraycopy(elements, 0, newChannels, 0, elements.length);
+ elements = newChannels;
+ }
+ }
+
+ private void shrink()
+ {
+ boolean shrink = false;
+ int lastIndex = elements.length - 1;
+ while (lastIndex > 0 && (shrink = elements[lastIndex] == null))
+ {
+ --lastIndex;
+ }
+
+ if (shrink)
+ {
+ int newLength = lastIndex + 1;
+ Object[] newChannels = new Object[newLength];
+ System.arraycopy(elements, 0, newChannels, 0, newLength);
+ elements = newChannels;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java index d4cc252669..44faf57b38 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -/** - * @author Eike Stepper - * @since 3.0 - * @deprecated As of 3.2 use {@link ConcurrentArray}. - */ -@Deprecated -public abstract class FastList<E> extends ConcurrentArray<E> -{ -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+/**
+ * @author Eike Stepper
+ * @since 3.0
+ * @deprecated As of 3.2 use {@link ConcurrentArray}.
+ */
+@Deprecated
+public abstract class FastList<E> extends ConcurrentArray<E>
+{
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java index dd22a2a963..8afd492dd4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java @@ -1,186 +1,186 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * @author Eike Stepper - */ -public final class HashBag<T> implements Set<T> -{ - private Map<T, HashBag.Counter> map; - - public HashBag() - { - map = new HashMap<T, Counter>(); - } - - public HashBag(int initialCapacity, float loadFactor) - { - map = new HashMap<T, Counter>(initialCapacity, loadFactor); - } - - public HashBag(int initialCapacity) - { - map = new HashMap<T, Counter>(initialCapacity); - } - - public HashBag(Map<? extends T, ? extends HashBag.Counter> m) - { - map = new HashMap<T, Counter>(m); - } - - /** - * @since 3.0 - */ - public int getCounterFor(T o) - { - Counter counter = map.get(o); - if (counter == null) - { - return 0; - } - - return counter.getValue(); - } - - public boolean add(T o) - { - HashBag.Counter counter = map.get(o); - if (counter == null) - { - counter = new Counter(); - map.put(o, counter); - return true; - } - - counter.incValue(); - return false; - } - - public boolean addAll(Collection<? extends T> c) - { - for (T t : c) - { - add(t); - } - - return true; - } - - public void clear() - { - map.clear(); - } - - public boolean contains(Object o) - { - return map.containsKey(o); - } - - public boolean containsAll(Collection<?> c) - { - return map.keySet().containsAll(c); - } - - public boolean isEmpty() - { - return map.isEmpty(); - } - - public Iterator<T> iterator() - { - return map.keySet().iterator(); - } - - public boolean remove(Object o) - { - HashBag.Counter counter = map.get(o); - if (counter == null) - { - return false; - } - - if (counter.decValue() == 0) - { - map.remove(o); - } - - return true; - } - - public boolean removeAll(Collection<?> c) - { - boolean changed = false; - for (Object object : c) - { - if (remove(object)) - { - changed = true; - } - } - - return changed; - } - - public boolean retainAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - public int size() - { - return map.size(); - } - - public Object[] toArray() - { - return map.keySet().toArray(); - } - - @SuppressWarnings("hiding") - public <T> T[] toArray(T[] a) - { - return map.keySet().toArray(a); - } - - /** - * @author Eike Stepper - */ - private static final class Counter - { - private int value = 1; - - public Counter() - { - } - - public int getValue() - { - return value; - } - - public int incValue() - { - return ++value; - } - - public int decValue() - { - return --value; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Eike Stepper
+ */
+public final class HashBag<T> implements Set<T>
+{
+ private Map<T, HashBag.Counter> map;
+
+ public HashBag()
+ {
+ map = new HashMap<T, Counter>();
+ }
+
+ public HashBag(int initialCapacity, float loadFactor)
+ {
+ map = new HashMap<T, Counter>(initialCapacity, loadFactor);
+ }
+
+ public HashBag(int initialCapacity)
+ {
+ map = new HashMap<T, Counter>(initialCapacity);
+ }
+
+ public HashBag(Map<? extends T, ? extends HashBag.Counter> m)
+ {
+ map = new HashMap<T, Counter>(m);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public int getCounterFor(T o)
+ {
+ Counter counter = map.get(o);
+ if (counter == null)
+ {
+ return 0;
+ }
+
+ return counter.getValue();
+ }
+
+ public boolean add(T o)
+ {
+ HashBag.Counter counter = map.get(o);
+ if (counter == null)
+ {
+ counter = new Counter();
+ map.put(o, counter);
+ return true;
+ }
+
+ counter.incValue();
+ return false;
+ }
+
+ public boolean addAll(Collection<? extends T> c)
+ {
+ for (T t : c)
+ {
+ add(t);
+ }
+
+ return true;
+ }
+
+ public void clear()
+ {
+ map.clear();
+ }
+
+ public boolean contains(Object o)
+ {
+ return map.containsKey(o);
+ }
+
+ public boolean containsAll(Collection<?> c)
+ {
+ return map.keySet().containsAll(c);
+ }
+
+ public boolean isEmpty()
+ {
+ return map.isEmpty();
+ }
+
+ public Iterator<T> iterator()
+ {
+ return map.keySet().iterator();
+ }
+
+ public boolean remove(Object o)
+ {
+ HashBag.Counter counter = map.get(o);
+ if (counter == null)
+ {
+ return false;
+ }
+
+ if (counter.decValue() == 0)
+ {
+ map.remove(o);
+ }
+
+ return true;
+ }
+
+ public boolean removeAll(Collection<?> c)
+ {
+ boolean changed = false;
+ for (Object object : c)
+ {
+ if (remove(object))
+ {
+ changed = true;
+ }
+ }
+
+ return changed;
+ }
+
+ public boolean retainAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public int size()
+ {
+ return map.size();
+ }
+
+ public Object[] toArray()
+ {
+ return map.keySet().toArray();
+ }
+
+ @SuppressWarnings("hiding")
+ public <T> T[] toArray(T[] a)
+ {
+ return map.keySet().toArray(a);
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class Counter
+ {
+ private int value = 1;
+
+ public Counter()
+ {
+ }
+
+ public int getValue()
+ {
+ return value;
+ }
+
+ public int incValue()
+ {
+ return ++value;
+ }
+
+ public int decValue()
+ {
+ return --value;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java index 553422a884..67fc3f5ce0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java @@ -1,217 +1,217 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.Notifier; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * @author Eike Stepper - */ -public class History<T> extends Notifier implements IHistory<T> -{ - protected List<IHistoryElement<T>> elements = new ArrayList<IHistoryElement<T>>(0); - - private boolean loaded; - - public History() - { - } - - public List<IHistoryElement<T>> getElements() - { - lazyLoad(); - return elements; - } - - public void setElements(List<IHistoryElement<T>> newElements) - { - if (newElements == null) - { - newElements = new ArrayList<IHistoryElement<T>>(0); - } - - if (!elements.equals(newElements)) - { - elements = newElements; - changed(); - } - } - - public boolean isEmpty() - { - lazyLoad(); - return elements.isEmpty(); - } - - public int size() - { - lazyLoad(); - return elements.size(); - } - - public int indexOf(T data) - { - lazyLoad(); - for (int i = 0; i < elements.size(); i++) - { - if (elements.get(i).getData().equals(data)) - { - return i; - } - } - - return -1; - } - - public IHistoryElement<T> get(int index) - { - lazyLoad(); - return elements.get(index); - } - - public boolean add(T data) - { - lazyLoad(); - int index = indexOf(data); - IHistoryElement<T> element = index != -1 ? elements.remove(index) : createElement(data); - elements.add(0, element); - - boolean changed = index != 0; - if (changed) - { - changed(); - } - - return changed; - } - - public IHistoryElement<T> remove(int index) - { - lazyLoad(); - IHistoryElement<T> element = elements.remove(index); - if (element != null) - { - changed(); - } - - return element; - } - - public boolean clear() - { - if (elements.isEmpty()) - { - return false; - } - - elements.clear(); - changed(); - return true; - } - - public T getMostRecent() - { - lazyLoad(); - if (isEmpty()) - { - return null; - } - - return elements.get(0).getData(); - } - - @SuppressWarnings("unchecked") - public <D> D[] getData(D[] a) - { - lazyLoad(); - int size = elements.size(); - if (a.length < size) - { - a = (D[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); - } - - for (int i = 0; i < size; i++) - { - a[i] = (D)elements.get(i).getData(); - } - - if (a.length > size) - { - a[size] = null; - } - - return a; - } - - @SuppressWarnings("unchecked") - public IHistoryElement<T>[] toArray() - { - lazyLoad(); - return elements.toArray(new IHistoryElement[elements.size()]); - } - - public Iterator<IHistoryElement<T>> iterator() - { - lazyLoad(); - return elements.iterator(); - } - - @SuppressWarnings("unchecked") - protected IHistoryElement<T> createElement(T data) - { - @SuppressWarnings("rawtypes") - HistoryElement result = new HistoryElement(this, data); - return result; - } - - protected void load() - { - } - - protected void save() - { - } - - protected final void changed() - { - save(); - fireChangedEvent(); - } - - private void lazyLoad() - { - if (!loaded) - { - loaded = true; - load(); - } - } - - private void fireChangedEvent() - { - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new IHistoryChangeEvent() - { - public IHistory<?> getSource() - { - return History.this; - } - }, listeners); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.Notifier;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * @author Eike Stepper
+ */
+public class History<T> extends Notifier implements IHistory<T>
+{
+ protected List<IHistoryElement<T>> elements = new ArrayList<IHistoryElement<T>>(0);
+
+ private boolean loaded;
+
+ public History()
+ {
+ }
+
+ public List<IHistoryElement<T>> getElements()
+ {
+ lazyLoad();
+ return elements;
+ }
+
+ public void setElements(List<IHistoryElement<T>> newElements)
+ {
+ if (newElements == null)
+ {
+ newElements = new ArrayList<IHistoryElement<T>>(0);
+ }
+
+ if (!elements.equals(newElements))
+ {
+ elements = newElements;
+ changed();
+ }
+ }
+
+ public boolean isEmpty()
+ {
+ lazyLoad();
+ return elements.isEmpty();
+ }
+
+ public int size()
+ {
+ lazyLoad();
+ return elements.size();
+ }
+
+ public int indexOf(T data)
+ {
+ lazyLoad();
+ for (int i = 0; i < elements.size(); i++)
+ {
+ if (elements.get(i).getData().equals(data))
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ public IHistoryElement<T> get(int index)
+ {
+ lazyLoad();
+ return elements.get(index);
+ }
+
+ public boolean add(T data)
+ {
+ lazyLoad();
+ int index = indexOf(data);
+ IHistoryElement<T> element = index != -1 ? elements.remove(index) : createElement(data);
+ elements.add(0, element);
+
+ boolean changed = index != 0;
+ if (changed)
+ {
+ changed();
+ }
+
+ return changed;
+ }
+
+ public IHistoryElement<T> remove(int index)
+ {
+ lazyLoad();
+ IHistoryElement<T> element = elements.remove(index);
+ if (element != null)
+ {
+ changed();
+ }
+
+ return element;
+ }
+
+ public boolean clear()
+ {
+ if (elements.isEmpty())
+ {
+ return false;
+ }
+
+ elements.clear();
+ changed();
+ return true;
+ }
+
+ public T getMostRecent()
+ {
+ lazyLoad();
+ if (isEmpty())
+ {
+ return null;
+ }
+
+ return elements.get(0).getData();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <D> D[] getData(D[] a)
+ {
+ lazyLoad();
+ int size = elements.size();
+ if (a.length < size)
+ {
+ a = (D[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
+ }
+
+ for (int i = 0; i < size; i++)
+ {
+ a[i] = (D)elements.get(i).getData();
+ }
+
+ if (a.length > size)
+ {
+ a[size] = null;
+ }
+
+ return a;
+ }
+
+ @SuppressWarnings("unchecked")
+ public IHistoryElement<T>[] toArray()
+ {
+ lazyLoad();
+ return elements.toArray(new IHistoryElement[elements.size()]);
+ }
+
+ public Iterator<IHistoryElement<T>> iterator()
+ {
+ lazyLoad();
+ return elements.iterator();
+ }
+
+ @SuppressWarnings("unchecked")
+ protected IHistoryElement<T> createElement(T data)
+ {
+ @SuppressWarnings("rawtypes")
+ HistoryElement result = new HistoryElement(this, data);
+ return result;
+ }
+
+ protected void load()
+ {
+ }
+
+ protected void save()
+ {
+ }
+
+ protected final void changed()
+ {
+ save();
+ fireChangedEvent();
+ }
+
+ private void lazyLoad()
+ {
+ if (!loaded)
+ {
+ loaded = true;
+ load();
+ }
+ }
+
+ private void fireChangedEvent()
+ {
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new IHistoryChangeEvent()
+ {
+ public IHistory<?> getSource()
+ {
+ return History.this;
+ }
+ }, listeners);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java index 821191ca86..56b6713425 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java @@ -1,74 +1,74 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.ObjectUtil; - -/** - * @author Eike Stepper - */ -public class HistoryElement<T> implements IHistoryElement<T> -{ - private IHistory<IHistoryElement<T>> history; - - private T data; - - public HistoryElement(IHistory<IHistoryElement<T>> history, T data) - { - this.history = history; - this.data = data; - } - - public IHistory<IHistoryElement<T>> getHistory() - { - return history; - } - - public T getData() - { - return data; - } - - public String getText() - { - return data.toString(); - } - - @Override - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (obj instanceof IHistoryElement<?>) - { - @SuppressWarnings("unchecked") - IHistoryElement<T> that = (IHistoryElement<T>)obj; - return ObjectUtil.equals(history, that.getHistory()) && ObjectUtil.equals(data, that.getData()); - } - - return false; - } - - @Override - public int hashCode() - { - return history.hashCode() ^ data.hashCode(); - } - - @Override - public String toString() - { - return getText(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.ObjectUtil;
+
+/**
+ * @author Eike Stepper
+ */
+public class HistoryElement<T> implements IHistoryElement<T>
+{
+ private IHistory<IHistoryElement<T>> history;
+
+ private T data;
+
+ public HistoryElement(IHistory<IHistoryElement<T>> history, T data)
+ {
+ this.history = history;
+ this.data = data;
+ }
+
+ public IHistory<IHistoryElement<T>> getHistory()
+ {
+ return history;
+ }
+
+ public T getData()
+ {
+ return data;
+ }
+
+ public String getText()
+ {
+ return data.toString();
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ if (obj instanceof IHistoryElement<?>)
+ {
+ @SuppressWarnings("unchecked")
+ IHistoryElement<T> that = (IHistoryElement<T>)obj;
+ return ObjectUtil.equals(history, that.getHistory()) && ObjectUtil.equals(data, that.getData());
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return history.hashCode() ^ data.hashCode();
+ }
+
+ @Override
+ public String toString()
+ {
+ return getText();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java index f51f502b31..cd17e499a7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java @@ -1,33 +1,33 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.om.pref.OMPreference; - -/** - * @author Eike Stepper - */ -public final class HistoryUtil -{ - private HistoryUtil() - { - } - - public static IHistory<String> createHistory() - { - return new History<String>(); - } - - public static IHistory<String> createPreferenceHistory(OMPreference<String[]> preference) - { - return new PreferenceHistory(preference); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.om.pref.OMPreference;
+
+/**
+ * @author Eike Stepper
+ */
+public final class HistoryUtil
+{
+ private HistoryUtil()
+ {
+ }
+
+ public static IHistory<String> createHistory()
+ {
+ return new History<String>();
+ }
+
+ public static IHistory<String> createPreferenceHistory(OMPreference<String[]> preference)
+ {
+ return new PreferenceHistory(preference);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java index 9236ecea54..b240ab4b7e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.event.INotifier; - -/** - * @author Eike Stepper - */ -public interface IHistory<T> extends INotifier, Iterable<IHistoryElement<T>> -{ - public boolean isEmpty(); - - public int size(); - - public boolean clear(); - - public int indexOf(T data); - - public boolean add(T data); - - public IHistoryElement<T> remove(int index); - - public IHistoryElement<T> get(int index); - - public T getMostRecent(); - - public <D> D[] getData(D[] a); - - public IHistoryElement<T>[] toArray(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.event.INotifier;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IHistory<T> extends INotifier, Iterable<IHistoryElement<T>>
+{
+ public boolean isEmpty();
+
+ public int size();
+
+ public boolean clear();
+
+ public int indexOf(T data);
+
+ public boolean add(T data);
+
+ public IHistoryElement<T> remove(int index);
+
+ public IHistoryElement<T> get(int index);
+
+ public T getMostRecent();
+
+ public <D> D[] getData(D[] a);
+
+ public IHistoryElement<T>[] toArray();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java index 9f1586313b..d644429c88 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.event.IEvent; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IHistoryChangeEvent extends IEvent -{ - /** - * @since 3.0 - */ - public IHistory<?> getSource(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.event.IEvent;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface IHistoryChangeEvent extends IEvent
+{
+ /**
+ * @since 3.0
+ */
+ public IHistory<?> getSource();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java index 11e9d9bfc1..3481f573bb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java @@ -1,23 +1,23 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -/** - * @author Eike Stepper - */ -public interface IHistoryElement<T> -{ - public IHistory<IHistoryElement<T>> getHistory(); - - public T getData(); - - public String getText(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IHistoryElement<T>
+{
+ public IHistory<IHistoryElement<T>> getHistory();
+
+ public T getData();
+
+ public String getText();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java index c822b54103..791a66ffae 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java @@ -1,280 +1,280 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.NoSuchElementException; - -/** - * @author Eike Stepper - * @since 3.0 - */ -public abstract class IndexedList<E> implements List<E> -{ - public IndexedList() - { - } - - public abstract E get(int index); - - public abstract int size(); - - public boolean isEmpty() - { - return size() == 0; - } - - public boolean contains(Object o) - { - int size = size(); - for (int i = 0; i < size; i++) - { - if (get(i).equals(o)) - { - return true; - } - } - - return false; - } - - public boolean containsAll(Collection<?> c) - { - for (Object object : c) - { - if (!contains(object)) - { - return false; - } - } - - return true; - } - - public int indexOf(Object o) - { - return 0; - } - - public int lastIndexOf(Object o) - { - return 0; - } - - public Iterator<E> iterator() - { - return new IndexedIterator(); - } - - public ListIterator<E> listIterator() - { - return new IndexedListIterator(0); - } - - public ListIterator<E> listIterator(int index) - { - if (index < 0 || index > size()) - { - throw new IndexOutOfBoundsException("Index: " + index); - } - - return new IndexedListIterator(index); - } - - public List<E> subList(int fromIndex, int toIndex) - { - return null; - } - - public Object[] toArray() - { - throw new UnsupportedOperationException(); - } - - public <T> T[] toArray(T[] a) - { - throw new UnsupportedOperationException(); - } - - public boolean add(E o) - { - throw new UnsupportedOperationException(); - } - - public boolean remove(Object o) - { - throw new UnsupportedOperationException(); - } - - public boolean addAll(Collection<? extends E> c) - { - throw new UnsupportedOperationException(); - } - - public boolean addAll(int index, Collection<? extends E> c) - { - throw new UnsupportedOperationException(); - } - - public boolean removeAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - public boolean retainAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - public void clear() - { - throw new UnsupportedOperationException(); - } - - public E set(int index, E element) - { - throw new UnsupportedOperationException(); - } - - public void add(int index, E element) - { - throw new UnsupportedOperationException(); - } - - public E remove(int index) - { - throw new UnsupportedOperationException(); - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("{"); //$NON-NLS-1$ - for (int i = 0; i < size(); i++) - { - if (i != 0) - { - builder.append(", "); //$NON-NLS-1$ - } - - builder.append(get(i).toString()); - } - - builder.append("}"); //$NON-NLS-1$ - return builder.toString(); - } - - /** - * @author Eike Stepper - */ - private class IndexedIterator implements Iterator<E> - { - int pos = 0; - - public boolean hasNext() - { - return pos != size(); - } - - public E next() - { - try - { - return get(pos++); - } - catch (IndexOutOfBoundsException ex) - { - throw new NoSuchElementException(); - } - } - - public void remove() - { - throw new UnsupportedOperationException(); - } - } - - /** - * @author Eike Stepper - */ - private class IndexedListIterator extends IndexedIterator implements ListIterator<E> - { - IndexedListIterator(int index) - { - pos = index; - } - - public boolean hasPrevious() - { - return pos != 0; - } - - public E previous() - { - try - { - return get(--pos); - } - catch (IndexOutOfBoundsException ex) - { - throw new NoSuchElementException(); - } - } - - public int nextIndex() - { - return pos; - } - - public int previousIndex() - { - return pos - 1; - } - - public void set(E o) - { - throw new UnsupportedOperationException(); - } - - public void add(E o) - { - throw new UnsupportedOperationException(); - } - } - - /** - * @author Eike Stepper - */ - public static abstract class ArrayBacked<E> extends IndexedList<E> - { - public ArrayBacked() - { - } - - protected abstract E[] getArray(); - - @Override - public E get(int i) - { - return getArray()[i]; - } - - @Override - public int size() - { - return getArray().length; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+
+/**
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public abstract class IndexedList<E> implements List<E>
+{
+ public IndexedList()
+ {
+ }
+
+ public abstract E get(int index);
+
+ public abstract int size();
+
+ public boolean isEmpty()
+ {
+ return size() == 0;
+ }
+
+ public boolean contains(Object o)
+ {
+ int size = size();
+ for (int i = 0; i < size; i++)
+ {
+ if (get(i).equals(o))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public boolean containsAll(Collection<?> c)
+ {
+ for (Object object : c)
+ {
+ if (!contains(object))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public int indexOf(Object o)
+ {
+ return 0;
+ }
+
+ public int lastIndexOf(Object o)
+ {
+ return 0;
+ }
+
+ public Iterator<E> iterator()
+ {
+ return new IndexedIterator();
+ }
+
+ public ListIterator<E> listIterator()
+ {
+ return new IndexedListIterator(0);
+ }
+
+ public ListIterator<E> listIterator(int index)
+ {
+ if (index < 0 || index > size())
+ {
+ throw new IndexOutOfBoundsException("Index: " + index);
+ }
+
+ return new IndexedListIterator(index);
+ }
+
+ public List<E> subList(int fromIndex, int toIndex)
+ {
+ return null;
+ }
+
+ public Object[] toArray()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public <T> T[] toArray(T[] a)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean add(E o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean remove(Object o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean addAll(Collection<? extends E> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean addAll(int index, Collection<? extends E> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean removeAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean retainAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public E set(int index, E element)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void add(int index, E element)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public E remove(int index)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String toString()
+ {
+ StringBuilder builder = new StringBuilder();
+ builder.append("{"); //$NON-NLS-1$
+ for (int i = 0; i < size(); i++)
+ {
+ if (i != 0)
+ {
+ builder.append(", "); //$NON-NLS-1$
+ }
+
+ builder.append(get(i).toString());
+ }
+
+ builder.append("}"); //$NON-NLS-1$
+ return builder.toString();
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private class IndexedIterator implements Iterator<E>
+ {
+ int pos = 0;
+
+ public boolean hasNext()
+ {
+ return pos != size();
+ }
+
+ public E next()
+ {
+ try
+ {
+ return get(pos++);
+ }
+ catch (IndexOutOfBoundsException ex)
+ {
+ throw new NoSuchElementException();
+ }
+ }
+
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private class IndexedListIterator extends IndexedIterator implements ListIterator<E>
+ {
+ IndexedListIterator(int index)
+ {
+ pos = index;
+ }
+
+ public boolean hasPrevious()
+ {
+ return pos != 0;
+ }
+
+ public E previous()
+ {
+ try
+ {
+ return get(--pos);
+ }
+ catch (IndexOutOfBoundsException ex)
+ {
+ throw new NoSuchElementException();
+ }
+ }
+
+ public int nextIndex()
+ {
+ return pos;
+ }
+
+ public int previousIndex()
+ {
+ return pos - 1;
+ }
+
+ public void set(E o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void add(E o)
+ {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static abstract class ArrayBacked<E> extends IndexedList<E>
+ {
+ public ArrayBacked()
+ {
+ }
+
+ protected abstract E[] getArray();
+
+ @Override
+ public E get(int i)
+ {
+ return getArray()[i];
+ }
+
+ @Override
+ public int size()
+ {
+ return getArray().length;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java index 8600cd05cb..95326270ba 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java @@ -1,84 +1,84 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.ObjectUtil; - -import java.text.MessageFormat; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public class MapEntry<K, V> implements Map.Entry<K, V> -{ - private K key; - - private V value; - - public MapEntry(K key, V value) - { - this.key = key; - this.value = value; - } - - public MapEntry(Map.Entry<K, V> entry) - { - key = entry.getKey(); - value = entry.getValue(); - } - - public K getKey() - { - return key; - } - - public V getValue() - { - return value; - } - - public V setValue(V value) - { - V oldValue = this.value; - this.value = value; - return oldValue; - } - - @Override - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (obj instanceof Map.Entry<?, ?>) - { - Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj; - return ObjectUtil.equals(key, entry.getKey()) && ObjectUtil.equals(value, entry.getValue()); - } - - return false; - } - - @Override - public int hashCode() - { - return ObjectUtil.hashCode(key) ^ ObjectUtil.hashCode(value); - } - - @Override - public String toString() - { - return MessageFormat.format("{0}={1}", key, value); //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.ObjectUtil;
+
+import java.text.MessageFormat;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public class MapEntry<K, V> implements Map.Entry<K, V>
+{
+ private K key;
+
+ private V value;
+
+ public MapEntry(K key, V value)
+ {
+ this.key = key;
+ this.value = value;
+ }
+
+ public MapEntry(Map.Entry<K, V> entry)
+ {
+ key = entry.getKey();
+ value = entry.getValue();
+ }
+
+ public K getKey()
+ {
+ return key;
+ }
+
+ public V getValue()
+ {
+ return value;
+ }
+
+ public V setValue(V value)
+ {
+ V oldValue = this.value;
+ this.value = value;
+ return oldValue;
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ if (obj instanceof Map.Entry<?, ?>)
+ {
+ Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj;
+ return ObjectUtil.equals(key, entry.getKey()) && ObjectUtil.equals(value, entry.getValue());
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return ObjectUtil.hashCode(key) ^ ObjectUtil.hashCode(value);
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("{0}={1}", key, value); //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java index b723d3a4f2..94bb0f0648 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java @@ -1,84 +1,84 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.ArrayList; - -/** - * A list with O(1) effort for random access. - * - * @author Eike Stepper - */ -public class MoveableArrayList<E> extends ArrayList<E> implements MoveableList<E> -{ - private static final long serialVersionUID = 1L; - - public MoveableArrayList(int initialCapacity) - { - super(initialCapacity); - } - - /** - * @since 3.0 - */ - public void move(int newPosition, Object object) - { - move(newPosition, indexOf(object)); - } - - public E move(int targetIndex, int sourceIndex) - { - int size = size(); - if (sourceIndex >= size) - { - throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$ - } - - if (targetIndex >= size) - { - throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$ - } - - E object = get(sourceIndex); - if (targetIndex == sourceIndex) - { - return object; - } - - if (targetIndex < sourceIndex) - { - moveUp1(targetIndex, sourceIndex - targetIndex); - } - else - { - moveDown1(targetIndex, targetIndex - sourceIndex); - } - - set(targetIndex, object); - return object; - } - - private void moveUp1(int index, int count) - { - for (int i = count; i > 0; i--) - { - set(index + i, get(index + i - 1)); - } - } - - private void moveDown1(int index, int count) - { - for (int i = count; i > 0; i--) - { - set(index - i, get(index - i + 1)); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.ArrayList;
+
+/**
+ * A list with O(1) effort for random access.
+ *
+ * @author Eike Stepper
+ */
+public class MoveableArrayList<E> extends ArrayList<E> implements MoveableList<E>
+{
+ private static final long serialVersionUID = 1L;
+
+ public MoveableArrayList(int initialCapacity)
+ {
+ super(initialCapacity);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void move(int newPosition, Object object)
+ {
+ move(newPosition, indexOf(object));
+ }
+
+ public E move(int targetIndex, int sourceIndex)
+ {
+ int size = size();
+ if (sourceIndex >= size)
+ {
+ throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (targetIndex >= size)
+ {
+ throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ E object = get(sourceIndex);
+ if (targetIndex == sourceIndex)
+ {
+ return object;
+ }
+
+ if (targetIndex < sourceIndex)
+ {
+ moveUp1(targetIndex, sourceIndex - targetIndex);
+ }
+ else
+ {
+ moveDown1(targetIndex, targetIndex - sourceIndex);
+ }
+
+ set(targetIndex, object);
+ return object;
+ }
+
+ private void moveUp1(int index, int count)
+ {
+ for (int i = count; i > 0; i--)
+ {
+ set(index + i, get(index + i - 1));
+ }
+ }
+
+ private void moveDown1(int index, int count)
+ {
+ for (int i = count; i > 0; i--)
+ {
+ set(index - i, get(index - i + 1));
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java index 9b77cdb070..4b1751ee3e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import java.util.List; - -/** - * @author Eike Stepper - */ -public interface MoveableList<E> extends List<E> -{ - public E move(int targetIndex, int sourceIndex); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import java.util.List;
+
+/**
+ * @author Eike Stepper
+ */
+public interface MoveableList<E> extends List<E>
+{
+ public E move(int targetIndex, int sourceIndex);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java index 268cc231ea..f025e66147 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java @@ -1,775 +1,775 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.ObjectUtil; - -import java.util.AbstractCollection; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -/** - * @author Eike Stepper - */ -public abstract class MultiMap<K, V> implements Map<K, V> -{ - private transient Entries entries; - - private transient Set<K> keys; - - private transient Collection<V> values; - - public MultiMap() - { - } - - public abstract int getDelegateCount(); - - public Map<K, V> getDelegate(int index) - { - if (0 <= index && index < getDelegateCount()) - { - return doGetDelegate(index); - } - - return null; - } - - /** - * @category WRITE - */ - public void clear() - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - public V put(K key, V value) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - public void putAll(Map<? extends K, ? extends V> t) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - public V remove(Object key) - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - public boolean containsKey(Object key) - { - return containsKey(key, getDelegateCount()); - } - - /** - * @category READ - */ - public boolean containsValue(Object value) - { - for (int i = 0; i < getDelegateCount(); i++) - { - Map<K, V> delegate = getDelegate(i); - if (delegate != null) - { - if (delegate.containsValue(value)) - { - return true; - } - } - } - - return false; - } - - /** - * @category READ - */ - public V get(Object key) - { - for (int i = 0; i < getDelegateCount(); i++) - { - Map<K, V> delegate = getDelegate(i); - if (delegate != null) - { - if (delegate.containsKey(key)) - { - return delegate.get(key); - } - } - } - - return null; - } - - /** - * @category READ - */ - public int size() - { - int size = 0; - Map<K, V> delegate = getDelegate(0); - if (delegate != null) - { - size += delegate.size(); - for (int i = 1; i < getDelegateCount(); i++) - { - delegate = getDelegate(i); - if (delegate != null) - { - Set<K> keySet = delegate.keySet(); - for (K key : keySet) - { - if (!containsKey(key, i)) - { - ++size; - } - } - } - } - } - - return size; - } - - /** - * @category READ - */ - public boolean isEmpty() - { - for (int i = 0; i < getDelegateCount(); i++) - { - Map<K, V> delegate = getDelegate(i); - if (delegate != null) - { - if (!delegate.isEmpty()) - { - return false; - } - } - } - - return true; - } - - public synchronized Set<Map.Entry<K, V>> entrySet() - { - if (entries == null) - { - entries = new Entries(); - } - - return entries; - } - - public synchronized Set<K> keySet() - { - if (keys == null) - { - keys = new Keys(); - } - - return keys; - } - - public synchronized Collection<V> values() - { - if (values == null) - { - values = new Values(); - } - - return values; - } - - protected boolean containsKey(Object key, int delegateCount) - { - for (int i = 0; i < delegateCount; i++) - { - Map<K, V> delegate = getDelegate(i); - if (delegate != null) - { - if (delegate.containsKey(key)) - { - return true; - } - } - } - - return false; - } - - protected abstract Map<K, V> doGetDelegate(int index); - - /** - * @author Eike Stepper - */ - public static class ListBased<K, V> extends MultiMap<K, V> - { - private List<Map<K, V>> delegates; - - public ListBased() - { - } - - public ListBased(List<Map<K, V>> delegates) - { - this.delegates = delegates; - } - - public synchronized List<Map<K, V>> getDelegates() - { - if (delegates == null) - { - delegates = createDelegates(); - } - - return delegates; - } - - public void setDelegates(List<Map<K, V>> delegates) - { - this.delegates = delegates; - } - - @Override - public int getDelegateCount() - { - return getDelegates().size(); - } - - @Override - protected Map<K, V> doGetDelegate(int index) - { - return getDelegates().get(index); - } - - protected List<Map<K, V>> createDelegates() - { - return new ArrayList<Map<K, V>>(); - } - } - - /** - * @author Eike Stepper - */ - private final class Entries extends AbstractSet<Entry<K, V>> - { - public Entries() - { - } - - /** - * @category WRITE - */ - @Override - public boolean add(Entry<K, V> o) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean addAll(Collection<? extends Entry<K, V>> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public void clear() - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean remove(Object o) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean removeAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean retainAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - @Override - public boolean contains(Object o) - { - if (o instanceof Map.Entry<?, ?>) - { - for (int i = 0; i < getDelegateCount(); i++) - { - Map<K, V> delegate = getDelegate(i); - if (delegate != null) - { - @SuppressWarnings("unchecked") - K key = ((Map.Entry<K, V>)o).getKey(); - if (delegate.containsKey(key)) - { - @SuppressWarnings("unchecked") - V value = ((Map.Entry<K, V>)o).getValue(); - if (ObjectUtil.equals(delegate.get(key), value)) - { - return true; - } - } - } - } - } - - return false; - } - - /** - * @category READ - */ - @Override - public boolean isEmpty() - { - return MultiMap.this.isEmpty(); - } - - /** - * @category READ - */ - @Override - public int size() - { - return MultiMap.this.size(); - } - - @Override - public Iterator<Entry<K, V>> iterator() - { - return new Iterator<Entry<K, V>>() - { - private Entry<K, V> next; - - private int delegateIndex = -1; - - private Iterator<Entry<K, V>> delegateIt; - - /** - * @category WRITE - */ - public void remove() - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - public boolean hasNext() - { - next = null; - while (next == null) - { - if (delegateIt == null) - { - Map<K, V> delegate = getDelegate(++delegateIndex); - if (delegate == null) - { - // All delegates have been iterated - break; - } - - delegateIt = delegate.entrySet().iterator(); - } - - if (delegateIt.hasNext()) - { - next = delegateIt.next(); - - // Check if this key has been returned previously - if (containsKey(next.getKey(), delegateIndex)) - { - next = null; - } - } - else - { - // Determine next delegate iterator in next loop - delegateIt = null; - } - } - - return next != null; - } - - /** - * @category READ - */ - public Map.Entry<K, V> next() - { - if (next == null) - { - throw new NoSuchElementException(); - } - - try - { - return next; - } - finally - { - next = null; - } - } - }; - } - } - - /** - * @author Eike Stepper - */ - private final class Keys extends AbstractSet<K> - { - public Keys() - { - } - - /** - * @category WRITE - */ - @Override - public boolean add(K o) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean addAll(Collection<? extends K> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public void clear() - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean remove(Object o) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean removeAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean retainAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - @Override - public boolean contains(Object o) - { - return MultiMap.this.containsKey(o); - } - - /** - * @category READ - */ - @Override - public boolean isEmpty() - { - return MultiMap.this.isEmpty(); - } - - /** - * @category READ - */ - @Override - public int size() - { - return MultiMap.this.size(); - } - - /** - * @category READ - */ - @Override - public Iterator<K> iterator() - { - return new Iterator<K>() - { - private K next; - - private int delegateIndex = -1; - - private Iterator<K> delegateIt; - - /** - * @category WRITE - */ - public void remove() - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - public boolean hasNext() - { - next = null; - while (next == null) - { - if (delegateIt == null) - { - Map<K, V> delegate = getDelegate(++delegateIndex); - if (delegate == null) - { - // All delegates have been iterated - break; - } - - delegateIt = delegate.keySet().iterator(); - } - - if (delegateIt.hasNext()) - { - next = delegateIt.next(); - - // Check if this key has been returned previously - if (containsKey(next, delegateIndex)) - { - next = null; - } - } - else - { - // Determine next delegate iterator in next loop - delegateIt = null; - } - } - - return next != null; - } - - /** - * @category READ - */ - public K next() - { - if (next == null) - { - throw new NoSuchElementException(); - } - - try - { - return next; - } - finally - { - next = null; - } - } - }; - } - } - - /** - * @author Eike Stepper - */ - private final class Values extends AbstractCollection<V> - { - public Values() - { - } - - /** - * @category WRITE - */ - @Override - public boolean add(V o) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean addAll(Collection<? extends V> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public void clear() - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean remove(Object o) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean removeAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category WRITE - */ - @Override - public boolean retainAll(Collection<?> c) - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - @Override - public boolean contains(Object o) - { - return MultiMap.this.containsValue(o); - } - - /** - * @category READ - */ - @Override - public boolean isEmpty() - { - return MultiMap.this.isEmpty(); - } - - /** - * @category READ - */ - @Override - public int size() - { - return MultiMap.this.size(); - } - - /** - * @category READ - */ - @Override - public Iterator<V> iterator() - { - return new Iterator<V>() - { - private Iterator<Entry<K, V>> delegateIt = entrySet().iterator(); - - /** - * @category WRITE - */ - public void remove() - { - throw new UnsupportedOperationException(); - } - - /** - * @category READ - */ - public boolean hasNext() - { - return delegateIt.hasNext(); - } - - /** - * @category READ - */ - public V next() - { - return delegateIt.next().getValue(); - } - }; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.ObjectUtil;
+
+import java.util.AbstractCollection;
+import java.util.AbstractSet;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class MultiMap<K, V> implements Map<K, V>
+{
+ private transient Entries entries;
+
+ private transient Set<K> keys;
+
+ private transient Collection<V> values;
+
+ public MultiMap()
+ {
+ }
+
+ public abstract int getDelegateCount();
+
+ public Map<K, V> getDelegate(int index)
+ {
+ if (0 <= index && index < getDelegateCount())
+ {
+ return doGetDelegate(index);
+ }
+
+ return null;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public V put(K key, V value)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void putAll(Map<? extends K, ? extends V> t)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public V remove(Object key)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean containsKey(Object key)
+ {
+ return containsKey(key, getDelegateCount());
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean containsValue(Object value)
+ {
+ for (int i = 0; i < getDelegateCount(); i++)
+ {
+ Map<K, V> delegate = getDelegate(i);
+ if (delegate != null)
+ {
+ if (delegate.containsValue(value))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @category READ
+ */
+ public V get(Object key)
+ {
+ for (int i = 0; i < getDelegateCount(); i++)
+ {
+ Map<K, V> delegate = getDelegate(i);
+ if (delegate != null)
+ {
+ if (delegate.containsKey(key))
+ {
+ return delegate.get(key);
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * @category READ
+ */
+ public int size()
+ {
+ int size = 0;
+ Map<K, V> delegate = getDelegate(0);
+ if (delegate != null)
+ {
+ size += delegate.size();
+ for (int i = 1; i < getDelegateCount(); i++)
+ {
+ delegate = getDelegate(i);
+ if (delegate != null)
+ {
+ Set<K> keySet = delegate.keySet();
+ for (K key : keySet)
+ {
+ if (!containsKey(key, i))
+ {
+ ++size;
+ }
+ }
+ }
+ }
+ }
+
+ return size;
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean isEmpty()
+ {
+ for (int i = 0; i < getDelegateCount(); i++)
+ {
+ Map<K, V> delegate = getDelegate(i);
+ if (delegate != null)
+ {
+ if (!delegate.isEmpty())
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public synchronized Set<Map.Entry<K, V>> entrySet()
+ {
+ if (entries == null)
+ {
+ entries = new Entries();
+ }
+
+ return entries;
+ }
+
+ public synchronized Set<K> keySet()
+ {
+ if (keys == null)
+ {
+ keys = new Keys();
+ }
+
+ return keys;
+ }
+
+ public synchronized Collection<V> values()
+ {
+ if (values == null)
+ {
+ values = new Values();
+ }
+
+ return values;
+ }
+
+ protected boolean containsKey(Object key, int delegateCount)
+ {
+ for (int i = 0; i < delegateCount; i++)
+ {
+ Map<K, V> delegate = getDelegate(i);
+ if (delegate != null)
+ {
+ if (delegate.containsKey(key))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ protected abstract Map<K, V> doGetDelegate(int index);
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class ListBased<K, V> extends MultiMap<K, V>
+ {
+ private List<Map<K, V>> delegates;
+
+ public ListBased()
+ {
+ }
+
+ public ListBased(List<Map<K, V>> delegates)
+ {
+ this.delegates = delegates;
+ }
+
+ public synchronized List<Map<K, V>> getDelegates()
+ {
+ if (delegates == null)
+ {
+ delegates = createDelegates();
+ }
+
+ return delegates;
+ }
+
+ public void setDelegates(List<Map<K, V>> delegates)
+ {
+ this.delegates = delegates;
+ }
+
+ @Override
+ public int getDelegateCount()
+ {
+ return getDelegates().size();
+ }
+
+ @Override
+ protected Map<K, V> doGetDelegate(int index)
+ {
+ return getDelegates().get(index);
+ }
+
+ protected List<Map<K, V>> createDelegates()
+ {
+ return new ArrayList<Map<K, V>>();
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class Entries extends AbstractSet<Entry<K, V>>
+ {
+ public Entries()
+ {
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean add(Entry<K, V> o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean addAll(Collection<? extends Entry<K, V>> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean remove(Object o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean removeAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean retainAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean contains(Object o)
+ {
+ if (o instanceof Map.Entry<?, ?>)
+ {
+ for (int i = 0; i < getDelegateCount(); i++)
+ {
+ Map<K, V> delegate = getDelegate(i);
+ if (delegate != null)
+ {
+ @SuppressWarnings("unchecked")
+ K key = ((Map.Entry<K, V>)o).getKey();
+ if (delegate.containsKey(key))
+ {
+ @SuppressWarnings("unchecked")
+ V value = ((Map.Entry<K, V>)o).getValue();
+ if (ObjectUtil.equals(delegate.get(key), value))
+ {
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean isEmpty()
+ {
+ return MultiMap.this.isEmpty();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public int size()
+ {
+ return MultiMap.this.size();
+ }
+
+ @Override
+ public Iterator<Entry<K, V>> iterator()
+ {
+ return new Iterator<Entry<K, V>>()
+ {
+ private Entry<K, V> next;
+
+ private int delegateIndex = -1;
+
+ private Iterator<Entry<K, V>> delegateIt;
+
+ /**
+ * @category WRITE
+ */
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean hasNext()
+ {
+ next = null;
+ while (next == null)
+ {
+ if (delegateIt == null)
+ {
+ Map<K, V> delegate = getDelegate(++delegateIndex);
+ if (delegate == null)
+ {
+ // All delegates have been iterated
+ break;
+ }
+
+ delegateIt = delegate.entrySet().iterator();
+ }
+
+ if (delegateIt.hasNext())
+ {
+ next = delegateIt.next();
+
+ // Check if this key has been returned previously
+ if (containsKey(next.getKey(), delegateIndex))
+ {
+ next = null;
+ }
+ }
+ else
+ {
+ // Determine next delegate iterator in next loop
+ delegateIt = null;
+ }
+ }
+
+ return next != null;
+ }
+
+ /**
+ * @category READ
+ */
+ public Map.Entry<K, V> next()
+ {
+ if (next == null)
+ {
+ throw new NoSuchElementException();
+ }
+
+ try
+ {
+ return next;
+ }
+ finally
+ {
+ next = null;
+ }
+ }
+ };
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class Keys extends AbstractSet<K>
+ {
+ public Keys()
+ {
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean add(K o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean addAll(Collection<? extends K> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean remove(Object o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean removeAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean retainAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean contains(Object o)
+ {
+ return MultiMap.this.containsKey(o);
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean isEmpty()
+ {
+ return MultiMap.this.isEmpty();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public int size()
+ {
+ return MultiMap.this.size();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public Iterator<K> iterator()
+ {
+ return new Iterator<K>()
+ {
+ private K next;
+
+ private int delegateIndex = -1;
+
+ private Iterator<K> delegateIt;
+
+ /**
+ * @category WRITE
+ */
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean hasNext()
+ {
+ next = null;
+ while (next == null)
+ {
+ if (delegateIt == null)
+ {
+ Map<K, V> delegate = getDelegate(++delegateIndex);
+ if (delegate == null)
+ {
+ // All delegates have been iterated
+ break;
+ }
+
+ delegateIt = delegate.keySet().iterator();
+ }
+
+ if (delegateIt.hasNext())
+ {
+ next = delegateIt.next();
+
+ // Check if this key has been returned previously
+ if (containsKey(next, delegateIndex))
+ {
+ next = null;
+ }
+ }
+ else
+ {
+ // Determine next delegate iterator in next loop
+ delegateIt = null;
+ }
+ }
+
+ return next != null;
+ }
+
+ /**
+ * @category READ
+ */
+ public K next()
+ {
+ if (next == null)
+ {
+ throw new NoSuchElementException();
+ }
+
+ try
+ {
+ return next;
+ }
+ finally
+ {
+ next = null;
+ }
+ }
+ };
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class Values extends AbstractCollection<V>
+ {
+ public Values()
+ {
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean add(V o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean addAll(Collection<? extends V> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean remove(Object o)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean removeAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category WRITE
+ */
+ @Override
+ public boolean retainAll(Collection<?> c)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean contains(Object o)
+ {
+ return MultiMap.this.containsValue(o);
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean isEmpty()
+ {
+ return MultiMap.this.isEmpty();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public int size()
+ {
+ return MultiMap.this.size();
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public Iterator<V> iterator()
+ {
+ return new Iterator<V>()
+ {
+ private Iterator<Entry<K, V>> delegateIt = entrySet().iterator();
+
+ /**
+ * @category WRITE
+ */
+ public void remove()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean hasNext()
+ {
+ return delegateIt.hasNext();
+ }
+
+ /**
+ * @category READ
+ */
+ public V next()
+ {
+ return delegateIt.next().getValue();
+ }
+ };
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java index e74d5e46ec..f23cbb46cb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java @@ -1,100 +1,100 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.ObjectUtil; - -/** - * @author Eike Stepper - */ -public class Pair<T1, T2> -{ - private T1 element1; - - private T2 element2; - - public Pair() - { - } - - public Pair(T1 element1, T2 element2) - { - this.element1 = element1; - this.element2 = element2; - } - - /** - * @since 2.0 - */ - public Pair(Pair<T1, T2> source) - { - element1 = source.element1; - element2 = source.element2; - } - - public final T1 getElement1() - { - return element1; - } - - public void setElement1(T1 element1) - { - this.element1 = element1; - } - - public final T2 getElement2() - { - return element2; - } - - public void setElement2(T2 element2) - { - this.element2 = element2; - } - - /** - * @since 2.0 - */ - @Override - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - - if (obj instanceof Pair<?, ?>) - { - Pair<?, ?> that = (Pair<?, ?>)obj; - return ObjectUtil.equals(element1, that.getElement1()) && ObjectUtil.equals(element2, that.getElement2()); - } - - return false; - } - - /** - * @since 2.0 - */ - @Override - public int hashCode() - { - return ObjectUtil.hashCode(element1) ^ ObjectUtil.hashCode(element2); - } - - /** - * @since 2.0 - */ - @Override - public String toString() - { - return "Pair[" + element1 + ", " + element2 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.ObjectUtil;
+
+/**
+ * @author Eike Stepper
+ */
+public class Pair<T1, T2>
+{
+ private T1 element1;
+
+ private T2 element2;
+
+ public Pair()
+ {
+ }
+
+ public Pair(T1 element1, T2 element2)
+ {
+ this.element1 = element1;
+ this.element2 = element2;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public Pair(Pair<T1, T2> source)
+ {
+ element1 = source.element1;
+ element2 = source.element2;
+ }
+
+ public final T1 getElement1()
+ {
+ return element1;
+ }
+
+ public void setElement1(T1 element1)
+ {
+ this.element1 = element1;
+ }
+
+ public final T2 getElement2()
+ {
+ return element2;
+ }
+
+ public void setElement2(T2 element2)
+ {
+ this.element2 = element2;
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (this == obj)
+ {
+ return true;
+ }
+
+ if (obj instanceof Pair<?, ?>)
+ {
+ Pair<?, ?> that = (Pair<?, ?>)obj;
+ return ObjectUtil.equals(element1, that.getElement1()) && ObjectUtil.equals(element2, that.getElement2());
+ }
+
+ return false;
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public int hashCode()
+ {
+ return ObjectUtil.hashCode(element1) ^ ObjectUtil.hashCode(element2);
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ public String toString()
+ {
+ return "Pair[" + element1 + ", " + element2 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java index 88c251c9eb..b5cf423284 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java @@ -1,54 +1,54 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.CheckUtil; -import org.eclipse.net4j.util.om.pref.OMPreference; - -/** - * @author Eike Stepper - */ -public class PreferenceHistory extends History<String> -{ - private OMPreference<String[]> preference; - - public PreferenceHistory(OMPreference<String[]> preference) - { - CheckUtil.checkArg(preference, "preference"); - this.preference = preference; - } - - public OMPreference<String[]> getPreference() - { - return preference; - } - - @Override - protected void load() - { - String[] value = preference.getValue(); - if (value != null) - { - for (String data : value) - { - IHistoryElement<String> element = createElement(data); - elements.add(element); - } - } - } - - @Override - protected void save() - { - String[] array = getData(new String[size()]); - preference.setValue(array); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.CheckUtil;
+import org.eclipse.net4j.util.om.pref.OMPreference;
+
+/**
+ * @author Eike Stepper
+ */
+public class PreferenceHistory extends History<String>
+{
+ private OMPreference<String[]> preference;
+
+ public PreferenceHistory(OMPreference<String[]> preference)
+ {
+ CheckUtil.checkArg(preference, "preference");
+ this.preference = preference;
+ }
+
+ public OMPreference<String[]> getPreference()
+ {
+ return preference;
+ }
+
+ @Override
+ protected void load()
+ {
+ String[] value = preference.getValue();
+ if (value != null)
+ {
+ for (String data : value)
+ {
+ IHistoryElement<String> element = createElement(data);
+ elements.add(element);
+ }
+ }
+ }
+
+ @Override
+ protected void save()
+ {
+ String[] array = getData(new String[size()]);
+ preference.setValue(array);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java index 85f7d054e2..508c8d62a1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java @@ -1,368 +1,368 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.ObjectUtil; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class RoundRobinBlockingQueue<E> implements BlockingQueue<E> -{ - private BlockingQueue<Entry<E>> list = new LinkedBlockingQueue<Entry<E>>(); - - public RoundRobinBlockingQueue() - { - } - - public int remainingCapacity() - { - return Integer.MAX_VALUE; - } - - public int size() - { - int size = 0; - synchronized (list) - { - for (Entry<E> entry : list) - { - size += entry.getCount(); - } - } - - return size; - } - - public boolean isEmpty() - { - synchronized (list) - { - return list.isEmpty(); - } - } - - public boolean offer(E e) - { - synchronized (list) - { - for (Entry<E> entry : list) - { - if (ObjectUtil.equals(entry.getElement(), e)) - { - entry.increaseCount(); - return true; - } - } - - return list.add(new Entry<E>(e)); - } - } - - public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException - { - return offer(o); - } - - public void put(E o) throws InterruptedException - { - offer(o); - } - - public boolean add(E o) - { - return offer(o); - } - - public E poll(long timeout, TimeUnit unit) throws InterruptedException - { - synchronized (list) - { - Entry<E> entry = list.poll(timeout, unit); - if (entry == null) - { - return null; - } - - if (entry.decreaseCount() > 0) - { - list.add(entry); - } - - return entry.getElement(); - } - } - - public E poll() - { - synchronized (list) - { - Entry<E> entry = list.poll(); - if (entry == null) - { - return null; - } - - if (entry.decreaseCount() > 0) - { - list.add(entry); - } - - return entry.getElement(); - } - } - - public E take() throws InterruptedException - { - synchronized (list) - { - Entry<E> entry = list.take(); - if (entry.decreaseCount() > 0) - { - list.add(entry); - } - - return entry.getElement(); - } - } - - public E peek() - { - synchronized (list) - { - Entry<E> entry = list.peek(); - if (entry == null) - { - return null; - } - - return entry.getElement(); - } - } - - public E element() - { - synchronized (list) - { - Entry<E> entry = list.element(); - if (entry == null) - { - return null; - } - - return entry.getElement(); - } - } - - public E remove() - { - synchronized (list) - { - Entry<E> entry = list.remove(); - if (entry.decreaseCount() > 0) - { - list.add(entry); - } - - return entry.getElement(); - } - } - - public boolean remove(Object o) - { - synchronized (list) - { - for (Iterator<Entry<E>> it = list.iterator(); it.hasNext();) - { - Entry<E> entry = it.next(); - if (ObjectUtil.equals(entry.getElement(), o)) - { - if (entry.decreaseCount() > 0) - { - it.remove(); - } - - return true; - } - } - } - - return false; - } - - public void clear() - { - synchronized (list) - { - list.clear(); - } - } - - public Iterator<E> iterator() - { - List<E> copy = new ArrayList<E>(); - - synchronized (list) - { - int round = 0; - boolean again; - - do - { - again = false; - for (Entry<E> entry : list) - { - int rest = entry.getCount() - round; - if (rest > 0) - { - copy.add(entry.getElement()); - if (rest > 1) - { - again = true; - } - } - } - - ++round; - } while (again); - } - - return copy.iterator(); - } - - public boolean contains(Object o) - { - synchronized (list) - { - for (Entry<E> entry : list) - { - if (ObjectUtil.equals(entry.getElement(), o)) - { - return true; - } - } - } - - return false; - } - - public Object[] toArray() - { - synchronized (list) - { - return list.toArray(); - } - } - - public <T> T[] toArray(T[] array) - { - synchronized (list) - { - return list.toArray(array); - } - } - - public boolean containsAll(Collection<?> c) - { - // TODO: implement RoundRobinBlockingQueue.containsAll(c) - throw new UnsupportedOperationException(); - } - - public boolean addAll(Collection<? extends E> c) - { - // TODO: implement RoundRobinBlockingQueue.addAll(c) - throw new UnsupportedOperationException(); - } - - public boolean removeAll(Collection<?> c) - { - // TODO: implement RoundRobinBlockingQueue.removeAll(c) - throw new UnsupportedOperationException(); - } - - public boolean retainAll(Collection<?> c) - { - // TODO: implement RoundRobinBlockingQueue.retainAll(c) - throw new UnsupportedOperationException(); - } - - public int drainTo(Collection<? super E> c) - { - // TODO: implement RoundRobinBlockingQueue.drainTo(c) - throw new UnsupportedOperationException(); - } - - public int drainTo(Collection<? super E> c, int maxElements) - { - // TODO: implement RoundRobinBlockingQueue.drainTo(c, maxElements) - throw new UnsupportedOperationException(); - } - - @Override - public String toString() - { - synchronized (list) - { - return list.toString(); - } - } - - /** - * @author Eike Stepper - */ - private static final class Entry<E> - { - private E element; - - private int count; - - public Entry(E element) - { - this.element = element; - count = 1; - } - - public E getElement() - { - return element; - } - - public int getCount() - { - return count; - } - - public int increaseCount() - { - return ++count; - } - - public int decreaseCount() - { - return --count; - } - - @Override - public String toString() - { - return element.toString() + "(" + count + ")"; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.ObjectUtil;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class RoundRobinBlockingQueue<E> implements BlockingQueue<E>
+{
+ private BlockingQueue<Entry<E>> list = new LinkedBlockingQueue<Entry<E>>();
+
+ public RoundRobinBlockingQueue()
+ {
+ }
+
+ public int remainingCapacity()
+ {
+ return Integer.MAX_VALUE;
+ }
+
+ public int size()
+ {
+ int size = 0;
+ synchronized (list)
+ {
+ for (Entry<E> entry : list)
+ {
+ size += entry.getCount();
+ }
+ }
+
+ return size;
+ }
+
+ public boolean isEmpty()
+ {
+ synchronized (list)
+ {
+ return list.isEmpty();
+ }
+ }
+
+ public boolean offer(E e)
+ {
+ synchronized (list)
+ {
+ for (Entry<E> entry : list)
+ {
+ if (ObjectUtil.equals(entry.getElement(), e))
+ {
+ entry.increaseCount();
+ return true;
+ }
+ }
+
+ return list.add(new Entry<E>(e));
+ }
+ }
+
+ public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException
+ {
+ return offer(o);
+ }
+
+ public void put(E o) throws InterruptedException
+ {
+ offer(o);
+ }
+
+ public boolean add(E o)
+ {
+ return offer(o);
+ }
+
+ public E poll(long timeout, TimeUnit unit) throws InterruptedException
+ {
+ synchronized (list)
+ {
+ Entry<E> entry = list.poll(timeout, unit);
+ if (entry == null)
+ {
+ return null;
+ }
+
+ if (entry.decreaseCount() > 0)
+ {
+ list.add(entry);
+ }
+
+ return entry.getElement();
+ }
+ }
+
+ public E poll()
+ {
+ synchronized (list)
+ {
+ Entry<E> entry = list.poll();
+ if (entry == null)
+ {
+ return null;
+ }
+
+ if (entry.decreaseCount() > 0)
+ {
+ list.add(entry);
+ }
+
+ return entry.getElement();
+ }
+ }
+
+ public E take() throws InterruptedException
+ {
+ synchronized (list)
+ {
+ Entry<E> entry = list.take();
+ if (entry.decreaseCount() > 0)
+ {
+ list.add(entry);
+ }
+
+ return entry.getElement();
+ }
+ }
+
+ public E peek()
+ {
+ synchronized (list)
+ {
+ Entry<E> entry = list.peek();
+ if (entry == null)
+ {
+ return null;
+ }
+
+ return entry.getElement();
+ }
+ }
+
+ public E element()
+ {
+ synchronized (list)
+ {
+ Entry<E> entry = list.element();
+ if (entry == null)
+ {
+ return null;
+ }
+
+ return entry.getElement();
+ }
+ }
+
+ public E remove()
+ {
+ synchronized (list)
+ {
+ Entry<E> entry = list.remove();
+ if (entry.decreaseCount() > 0)
+ {
+ list.add(entry);
+ }
+
+ return entry.getElement();
+ }
+ }
+
+ public boolean remove(Object o)
+ {
+ synchronized (list)
+ {
+ for (Iterator<Entry<E>> it = list.iterator(); it.hasNext();)
+ {
+ Entry<E> entry = it.next();
+ if (ObjectUtil.equals(entry.getElement(), o))
+ {
+ if (entry.decreaseCount() > 0)
+ {
+ it.remove();
+ }
+
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public void clear()
+ {
+ synchronized (list)
+ {
+ list.clear();
+ }
+ }
+
+ public Iterator<E> iterator()
+ {
+ List<E> copy = new ArrayList<E>();
+
+ synchronized (list)
+ {
+ int round = 0;
+ boolean again;
+
+ do
+ {
+ again = false;
+ for (Entry<E> entry : list)
+ {
+ int rest = entry.getCount() - round;
+ if (rest > 0)
+ {
+ copy.add(entry.getElement());
+ if (rest > 1)
+ {
+ again = true;
+ }
+ }
+ }
+
+ ++round;
+ } while (again);
+ }
+
+ return copy.iterator();
+ }
+
+ public boolean contains(Object o)
+ {
+ synchronized (list)
+ {
+ for (Entry<E> entry : list)
+ {
+ if (ObjectUtil.equals(entry.getElement(), o))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public Object[] toArray()
+ {
+ synchronized (list)
+ {
+ return list.toArray();
+ }
+ }
+
+ public <T> T[] toArray(T[] array)
+ {
+ synchronized (list)
+ {
+ return list.toArray(array);
+ }
+ }
+
+ public boolean containsAll(Collection<?> c)
+ {
+ // TODO: implement RoundRobinBlockingQueue.containsAll(c)
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean addAll(Collection<? extends E> c)
+ {
+ // TODO: implement RoundRobinBlockingQueue.addAll(c)
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean removeAll(Collection<?> c)
+ {
+ // TODO: implement RoundRobinBlockingQueue.removeAll(c)
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean retainAll(Collection<?> c)
+ {
+ // TODO: implement RoundRobinBlockingQueue.retainAll(c)
+ throw new UnsupportedOperationException();
+ }
+
+ public int drainTo(Collection<? super E> c)
+ {
+ // TODO: implement RoundRobinBlockingQueue.drainTo(c)
+ throw new UnsupportedOperationException();
+ }
+
+ public int drainTo(Collection<? super E> c, int maxElements)
+ {
+ // TODO: implement RoundRobinBlockingQueue.drainTo(c, maxElements)
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String toString()
+ {
+ synchronized (list)
+ {
+ return list.toString();
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class Entry<E>
+ {
+ private E element;
+
+ private int count;
+
+ public Entry(E element)
+ {
+ this.element = element;
+ count = 1;
+ }
+
+ public E getElement()
+ {
+ return element;
+ }
+
+ public int getCount()
+ {
+ return count;
+ }
+
+ public int increaseCount()
+ {
+ return ++count;
+ }
+
+ public int decreaseCount()
+ {
+ return --count;
+ }
+
+ @Override
+ public String toString()
+ {
+ return element.toString() + "(" + count + ")";
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java index 642d55f356..5656c815aa 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java @@ -1,79 +1,79 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Caspar De Groot - initial API and implementation - */ -package org.eclipse.net4j.util.collection; - -import org.eclipse.net4j.util.ObjectUtil; - -/** - * @author Caspar De Groot - * @since 3.0 - */ -public class Triplet<T1, T2, T3> extends Pair<T1, T2> -{ - private T3 element3; - - public Triplet() - { - } - - public Triplet(T1 element1, T2 element2, T3 element3) - { - super(element1, element2); - this.element3 = element3; - } - - public Triplet(Triplet<T1, T2, T3> source) - { - super(source.getElement1(), source.getElement2()); - element3 = source.element3; - } - - public final T3 getElement3() - { - return element3; - } - - public void setElement3(T3 element3) - { - this.element3 = element3; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - - if (obj instanceof Triplet<?, ?, ?>) - { - Triplet<?, ?, ?> that = (Triplet<?, ?, ?>)obj; - return ObjectUtil.equals(getElement1(), that.getElement1()) // - && ObjectUtil.equals(getElement2(), that.getElement2()) // - && ObjectUtil.equals(element3, that.element3); - } - - return false; - } - - @Override - public int hashCode() - { - return ObjectUtil.hashCode(getElement1()) ^ ObjectUtil.hashCode(getElement2()) ^ ObjectUtil.hashCode(element3); - } - - @Override - public String toString() - { - return "Triplet[" + getElement1() + ", " + getElement2() + ", " + element3 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Caspar De Groot - initial API and implementation
+ */
+package org.eclipse.net4j.util.collection;
+
+import org.eclipse.net4j.util.ObjectUtil;
+
+/**
+ * @author Caspar De Groot
+ * @since 3.0
+ */
+public class Triplet<T1, T2, T3> extends Pair<T1, T2>
+{
+ private T3 element3;
+
+ public Triplet()
+ {
+ }
+
+ public Triplet(T1 element1, T2 element2, T3 element3)
+ {
+ super(element1, element2);
+ this.element3 = element3;
+ }
+
+ public Triplet(Triplet<T1, T2, T3> source)
+ {
+ super(source.getElement1(), source.getElement2());
+ element3 = source.element3;
+ }
+
+ public final T3 getElement3()
+ {
+ return element3;
+ }
+
+ public void setElement3(T3 element3)
+ {
+ this.element3 = element3;
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (this == obj)
+ {
+ return true;
+ }
+
+ if (obj instanceof Triplet<?, ?, ?>)
+ {
+ Triplet<?, ?, ?> that = (Triplet<?, ?, ?>)obj;
+ return ObjectUtil.equals(getElement1(), that.getElement1()) //
+ && ObjectUtil.equals(getElement2(), that.getElement2()) //
+ && ObjectUtil.equals(element3, that.element3);
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return ObjectUtil.hashCode(getElement1()) ^ ObjectUtil.hashCode(getElement2()) ^ ObjectUtil.hashCode(element3);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "Triplet[" + getElement1() + ", " + getElement2() + ", " + element3 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java index fe1d9ecea0..effa3c9d67 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java index c83c4ecd68..602621d9e2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java @@ -1,161 +1,161 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ExecutorService; - -/** - * @author Eike Stepper - */ -public class AsynchronousWorkSerializer implements IWorkSerializer, Runnable -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_CONCURRENCY, AsynchronousWorkSerializer.class); - - private ExecutorService executorService; - - private Queue<Runnable> workQueue; - - private Occupation occupation = new Occupation(); - - // private Object newElementLock = new Object(); - - public AsynchronousWorkSerializer(ExecutorService executorService, Queue<Runnable> workQueue) - { - if (executorService == null) - { - throw new IllegalArgumentException("executorService == null"); //$NON-NLS-1$ - } - - this.executorService = executorService; - this.workQueue = workQueue; - } - - public AsynchronousWorkSerializer(ExecutorService executorService) - { - this(executorService, new ConcurrentLinkedQueue<Runnable>()); - } - - public ExecutorService getExecutorService() - { - return executorService; - } - - public boolean addWork(Runnable work) - { - // Need to be a block of execution. Cannot add when doing last check - // XXX synchronized (newElementLock) - { - workQueue.add(work); - - // isOccupied can (and must) be called unsynchronized here - if (!occupation.isOccupied()) - { - synchronized (occupation) - { - occupation.setOccupied(true); - } - - if (TRACER.isEnabled()) - { - TRACER.trace("Notifying executor service"); //$NON-NLS-1$ - } - - executorService.execute(this); - } - } - - return true; - } - - /** - * Executed in the context of the {@link #getExecutorService() executor service}. - * <p> - */ - public void run() - { - // XXX synchronized (occupation) - { - Runnable work; - // for (;;) - { - while (occupation.isOccupied() && (work = workQueue.poll()) != null) - { - try - { - work.run(); - } - catch (RuntimeException ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace(ex); - } - } - } - - // ConcurrencyUtil.sleep(500); - - // Could put the sync in the while loop... but not efficient. - // Doing a last check to make sure that no one added something in the - // queue - // synchronized (newElementLock) - // { - // if (!occupation.isOccupied() || (work = workQueue.peek()) == null) - // { - // occupation.setOccupied(false); - // break; - // } - // } - } - } - } - - public void dispose() - { - if (occupation.isOccupied()) - { - occupation.setOccupied(false); - } - - workQueue.clear(); - workQueue = null; - executorService = null; - } - - @Override - public String toString() - { - return AsynchronousWorkSerializer.class.getSimpleName(); - } - - /** - * @author Eike Stepper - */ - private static final class Occupation - { - private boolean occupied; - - public boolean isOccupied() - { - return occupied; - } - - public void setOccupied(boolean occupied) - { - this.occupied = occupied; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+
+/**
+ * @author Eike Stepper
+ */
+public class AsynchronousWorkSerializer implements IWorkSerializer, Runnable
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_CONCURRENCY, AsynchronousWorkSerializer.class);
+
+ private ExecutorService executorService;
+
+ private Queue<Runnable> workQueue;
+
+ private Occupation occupation = new Occupation();
+
+ // private Object newElementLock = new Object();
+
+ public AsynchronousWorkSerializer(ExecutorService executorService, Queue<Runnable> workQueue)
+ {
+ if (executorService == null)
+ {
+ throw new IllegalArgumentException("executorService == null"); //$NON-NLS-1$
+ }
+
+ this.executorService = executorService;
+ this.workQueue = workQueue;
+ }
+
+ public AsynchronousWorkSerializer(ExecutorService executorService)
+ {
+ this(executorService, new ConcurrentLinkedQueue<Runnable>());
+ }
+
+ public ExecutorService getExecutorService()
+ {
+ return executorService;
+ }
+
+ public boolean addWork(Runnable work)
+ {
+ // Need to be a block of execution. Cannot add when doing last check
+ // XXX synchronized (newElementLock)
+ {
+ workQueue.add(work);
+
+ // isOccupied can (and must) be called unsynchronized here
+ if (!occupation.isOccupied())
+ {
+ synchronized (occupation)
+ {
+ occupation.setOccupied(true);
+ }
+
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Notifying executor service"); //$NON-NLS-1$
+ }
+
+ executorService.execute(this);
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Executed in the context of the {@link #getExecutorService() executor service}.
+ * <p>
+ */
+ public void run()
+ {
+ // XXX synchronized (occupation)
+ {
+ Runnable work;
+ // for (;;)
+ {
+ while (occupation.isOccupied() && (work = workQueue.poll()) != null)
+ {
+ try
+ {
+ work.run();
+ }
+ catch (RuntimeException ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace(ex);
+ }
+ }
+ }
+
+ // ConcurrencyUtil.sleep(500);
+
+ // Could put the sync in the while loop... but not efficient.
+ // Doing a last check to make sure that no one added something in the
+ // queue
+ // synchronized (newElementLock)
+ // {
+ // if (!occupation.isOccupied() || (work = workQueue.peek()) == null)
+ // {
+ // occupation.setOccupied(false);
+ // break;
+ // }
+ // }
+ }
+ }
+ }
+
+ public void dispose()
+ {
+ if (occupation.isOccupied())
+ {
+ occupation.setOccupied(false);
+ }
+
+ workQueue.clear();
+ workQueue = null;
+ executorService = null;
+ }
+
+ @Override
+ public String toString()
+ {
+ return AsynchronousWorkSerializer.class.getSimpleName();
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class Occupation
+ {
+ private boolean occupied;
+
+ public boolean isOccupied()
+ {
+ return occupied;
+ }
+
+ public void setOccupied(boolean occupied)
+ {
+ this.occupied = occupied;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java index 46c77fe122..da46e06ec3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java @@ -1,66 +1,66 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CompletionService; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.Future; - -/** - * @author Eike Stepper - */ -public class CompletionWorkSerializer implements IWorkSerializer -{ - private CompletionService<Object> completionService; - - public CompletionWorkSerializer(CompletionService<Object> completionService) - { - this.completionService = completionService; - } - - public CompletionWorkSerializer(Executor executor, BlockingQueue<Future<Object>> completionQueue) - { - this(new ExecutorCompletionService<Object>(executor, completionQueue)); - } - - public CompletionWorkSerializer(Executor executor) - { - this(new ExecutorCompletionService<Object>(executor)); - } - - public CompletionWorkSerializer() - { - this(new OnePendingExecutor()); - } - - public CompletionService<Object> getCompletionService() - { - return completionService; - } - - public void dispose() - { - } - - public boolean addWork(Runnable work) - { - completionService.submit(work, true); - return true; - } - - @Override - public String toString() - { - return CompletionWorkSerializer.class.getSimpleName(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CompletionService;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.Future;
+
+/**
+ * @author Eike Stepper
+ */
+public class CompletionWorkSerializer implements IWorkSerializer
+{
+ private CompletionService<Object> completionService;
+
+ public CompletionWorkSerializer(CompletionService<Object> completionService)
+ {
+ this.completionService = completionService;
+ }
+
+ public CompletionWorkSerializer(Executor executor, BlockingQueue<Future<Object>> completionQueue)
+ {
+ this(new ExecutorCompletionService<Object>(executor, completionQueue));
+ }
+
+ public CompletionWorkSerializer(Executor executor)
+ {
+ this(new ExecutorCompletionService<Object>(executor));
+ }
+
+ public CompletionWorkSerializer()
+ {
+ this(new OnePendingExecutor());
+ }
+
+ public CompletionService<Object> getCompletionService()
+ {
+ return completionService;
+ }
+
+ public void dispose()
+ {
+ }
+
+ public boolean addWork(Runnable work)
+ {
+ completionService.submit(work, true);
+ return true;
+ }
+
+ @Override
+ public String toString()
+ {
+ return CompletionWorkSerializer.class.getSimpleName();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrencyUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrencyUtil.java index c8a97735c9..c3046072df 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrencyUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrencyUtil.java @@ -1,47 +1,47 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.WrappedException; - -/** - * @author Eike Stepper - */ -public final class ConcurrencyUtil -{ - private ConcurrencyUtil() - { - } - - public static void sleep(long millis) - { - try - { - Thread.sleep(millis); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void sleep(long millis, int nanos) - { - try - { - Thread.sleep(millis, nanos); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.WrappedException;
+
+/**
+ * @author Eike Stepper
+ */
+public final class ConcurrencyUtil
+{
+ private ConcurrencyUtil()
+ {
+ }
+
+ public static void sleep(long millis)
+ {
+ try
+ {
+ Thread.sleep(millis);
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static void sleep(long millis, int nanos)
+ {
+ try
+ {
+ Thread.sleep(millis, nanos);
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrentValue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrentValue.java index b2771e34b0..b0a7b95d27 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrentValue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ConcurrentValue.java @@ -1,110 +1,110 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Simon McDuff - initial API and implementation - * Eike Stepper - maintenance - */ -package org.eclipse.net4j.util.concurrent; - -/** - * Allow synchronization between many threads for a specific value, e.g.: - * - * <pre> - * MainThread cv.set(1); - * Thread1 cv.acquire(3); - * Thread2 cv.acquire(4); - * Thread3 cv.acquire(100); - * Thread4 cv.acquire(new Object() - * { - * public boolean equals(Object other) - * { - * return other.equals(2) || other.equals(3); - * } - * }); - * Thread5 cv.acquire(1); - * ... - * // Thread 1,2,3 and 4 are blocked - * // Thread 5 isn't blocked. - * - * MainThread cv.set(3); - * - * // Thread 1 and 4 are unblocked. - * // Thread 2 and 3 are still blocked. - * </pre> - * - * @author Simon McDuff - * @since 2.0 - */ -public final class ConcurrentValue<T> -{ - private Object notifier = new Notifier(); - - private T value; - - public ConcurrentValue(T value) - { - this.value = value; - } - - public T get() - { - return value; - } - - /** - * Specify the new value. - */ - public void set(T newValue) - { - synchronized (notifier) - { - value = newValue; - notifier.notifyAll(); - } - } - - /** - * Reevaluate the condition. It is only useful if a thread is blocked at {@link #acquire(Object)} and the parameter - * passed changed. {@link #acquire(Object)} generates a reevaluation automatically. - */ - public void reevaluate() - { - synchronized (notifier) - { - notifier.notifyAll(); - } - } - - /** - * Blocking call. - * <p> - * Return when value accept is equal to {@link #get()}. - */ - public void acquire(Object accept) throws InterruptedException - { - if (accept == null) - { - throw new IllegalArgumentException("accept == null"); //$NON-NLS-1$ - } - - synchronized (notifier) - { - while (!accept.equals(value)) - { - notifier.wait(); - } - } - } - - /** - * @author Eike Stepper - */ - private static final class Notifier extends Object - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Simon McDuff - initial API and implementation
+ * Eike Stepper - maintenance
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * Allow synchronization between many threads for a specific value, e.g.:
+ *
+ * <pre>
+ * MainThread cv.set(1);
+ * Thread1 cv.acquire(3);
+ * Thread2 cv.acquire(4);
+ * Thread3 cv.acquire(100);
+ * Thread4 cv.acquire(new Object()
+ * {
+ * public boolean equals(Object other)
+ * {
+ * return other.equals(2) || other.equals(3);
+ * }
+ * });
+ * Thread5 cv.acquire(1);
+ * ...
+ * // Thread 1,2,3 and 4 are blocked
+ * // Thread 5 isn't blocked.
+ *
+ * MainThread cv.set(3);
+ *
+ * // Thread 1 and 4 are unblocked.
+ * // Thread 2 and 3 are still blocked.
+ * </pre>
+ *
+ * @author Simon McDuff
+ * @since 2.0
+ */
+public final class ConcurrentValue<T>
+{
+ private Object notifier = new Notifier();
+
+ private T value;
+
+ public ConcurrentValue(T value)
+ {
+ this.value = value;
+ }
+
+ public T get()
+ {
+ return value;
+ }
+
+ /**
+ * Specify the new value.
+ */
+ public void set(T newValue)
+ {
+ synchronized (notifier)
+ {
+ value = newValue;
+ notifier.notifyAll();
+ }
+ }
+
+ /**
+ * Reevaluate the condition. It is only useful if a thread is blocked at {@link #acquire(Object)} and the parameter
+ * passed changed. {@link #acquire(Object)} generates a reevaluation automatically.
+ */
+ public void reevaluate()
+ {
+ synchronized (notifier)
+ {
+ notifier.notifyAll();
+ }
+ }
+
+ /**
+ * Blocking call.
+ * <p>
+ * Return when value accept is equal to {@link #get()}.
+ */
+ public void acquire(Object accept) throws InterruptedException
+ {
+ if (accept == null)
+ {
+ throw new IllegalArgumentException("accept == null"); //$NON-NLS-1$
+ }
+
+ synchronized (notifier)
+ {
+ while (!accept.equals(value))
+ {
+ notifier.wait();
+ }
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class Notifier extends Object
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ExecutorServiceFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ExecutorServiceFactory.java index d1ac0ef811..80340b9098 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ExecutorServiceFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ExecutorServiceFactory.java @@ -1,122 +1,122 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.container.IManagedContainer; -import org.eclipse.net4j.util.event.EventUtil; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.factory.Factory; -import org.eclipse.net4j.util.lifecycle.ILifecycle; -import org.eclipse.net4j.util.lifecycle.LifecycleException; -import org.eclipse.net4j.util.lifecycle.LifecycleState; -import org.eclipse.net4j.util.lifecycle.LifecycleUtil; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class ExecutorServiceFactory extends Factory -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.executorServices"; //$NON-NLS-1$ - - public static final String TYPE = "default"; //$NON-NLS-1$ - - public static final String DEFAULT_THREAD_GROUP_NAME = "net4j"; //$NON-NLS-1$ - - public ExecutorServiceFactory() - { - super(PRODUCT_GROUP, TYPE); - } - - public ExecutorService create(String threadGroupName) - { - if (threadGroupName == null) - { - threadGroupName = DEFAULT_THREAD_GROUP_NAME; - } - - final ThreadGroup threadGroup = new ThreadGroup(threadGroupName); - ThreadFactory threadFactory = new ThreadFactory() - { - public Thread newThread(Runnable r) - { - Thread thread = new Thread(threadGroup, r); - thread.setDaemon(true); - return thread; - } - }; - - final ExecutorService executorService = Executors.newCachedThreadPool(threadFactory); - return LifecycleUtil.delegateLifecycle(getClass().getClassLoader(), executorService, ExecutorService.class, - new ILifecycle() - { - private boolean active; - - public void activate() throws LifecycleException - { - active = true; - } - - public Exception deactivate() - { - try - { - executorService.shutdown(); - active = false; - return null; - } - catch (Exception ex) - { - return ex; - } - } - - public LifecycleState getLifecycleState() - { - return active ? LifecycleState.ACTIVE : LifecycleState.INACTIVE; - } - - public boolean isActive() - { - return active; - } - - public void addListener(IListener listener) - { - // Do nothing - } - - public void removeListener(IListener listener) - { - // Do nothing - } - - public IListener[] getListeners() - { - return EventUtil.NO_LISTENERS; - } - - public boolean hasListeners() - { - return false; - } - }); - } - - public static ExecutorService get(IManagedContainer container) - { - return (ExecutorService)container.getElement(PRODUCT_GROUP, TYPE, null); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.container.IManagedContainer;
+import org.eclipse.net4j.util.event.EventUtil;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.factory.Factory;
+import org.eclipse.net4j.util.lifecycle.ILifecycle;
+import org.eclipse.net4j.util.lifecycle.LifecycleException;
+import org.eclipse.net4j.util.lifecycle.LifecycleState;
+import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class ExecutorServiceFactory extends Factory
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.executorServices"; //$NON-NLS-1$
+
+ public static final String TYPE = "default"; //$NON-NLS-1$
+
+ public static final String DEFAULT_THREAD_GROUP_NAME = "net4j"; //$NON-NLS-1$
+
+ public ExecutorServiceFactory()
+ {
+ super(PRODUCT_GROUP, TYPE);
+ }
+
+ public ExecutorService create(String threadGroupName)
+ {
+ if (threadGroupName == null)
+ {
+ threadGroupName = DEFAULT_THREAD_GROUP_NAME;
+ }
+
+ final ThreadGroup threadGroup = new ThreadGroup(threadGroupName);
+ ThreadFactory threadFactory = new ThreadFactory()
+ {
+ public Thread newThread(Runnable r)
+ {
+ Thread thread = new Thread(threadGroup, r);
+ thread.setDaemon(true);
+ return thread;
+ }
+ };
+
+ final ExecutorService executorService = Executors.newCachedThreadPool(threadFactory);
+ return LifecycleUtil.delegateLifecycle(getClass().getClassLoader(), executorService, ExecutorService.class,
+ new ILifecycle()
+ {
+ private boolean active;
+
+ public void activate() throws LifecycleException
+ {
+ active = true;
+ }
+
+ public Exception deactivate()
+ {
+ try
+ {
+ executorService.shutdown();
+ active = false;
+ return null;
+ }
+ catch (Exception ex)
+ {
+ return ex;
+ }
+ }
+
+ public LifecycleState getLifecycleState()
+ {
+ return active ? LifecycleState.ACTIVE : LifecycleState.INACTIVE;
+ }
+
+ public boolean isActive()
+ {
+ return active;
+ }
+
+ public void addListener(IListener listener)
+ {
+ // Do nothing
+ }
+
+ public void removeListener(IListener listener)
+ {
+ // Do nothing
+ }
+
+ public IListener[] getListeners()
+ {
+ return EventUtil.NO_LISTENERS;
+ }
+
+ public boolean hasListeners()
+ {
+ return false;
+ }
+ });
+ }
+
+ public static ExecutorService get(IManagedContainer container)
+ {
+ return (ExecutorService)container.getElement(PRODUCT_GROUP, TYPE, null);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java index 43a8415c8e..1a50cc854b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -/** - * @author Eike Stepper - */ -public interface ICorrelator<CORRELATION, VALUE> -{ - public boolean isCorrelated(CORRELATION correlation); - - public VALUE correlate(CORRELATION correlation); - - public VALUE correlateUnique(CORRELATION correlation); - - public VALUE uncorrelate(CORRELATION correlation); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICorrelator<CORRELATION, VALUE>
+{
+ public boolean isCorrelated(CORRELATION correlation);
+
+ public VALUE correlate(CORRELATION correlation);
+
+ public VALUE correlateUnique(CORRELATION correlation);
+
+ public VALUE uncorrelate(CORRELATION correlation);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java index ca75e6e576..75064d4ffe 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java @@ -1,63 +1,63 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.Collection; - -/** - * Support Multiple reads/no write and upgrade lock from read to write. Many context could request - * {@link LockType#WRITE write} lock at the same time. It will privileges first context that has already a - * {@link LockType#READ read} lock. If no one has any read lock, it's "first come first serve". - * - * @author Eike Stepper - * @since 3.0 - */ -public interface IRWLockManager<OBJECT, CONTEXT> -{ - public static final int WAIT = 0; - - public static final int NO_WAIT = 1; - - public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout) - throws InterruptedException; - - public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException; - - /** - * Attempts to release for a given locktype, context and objects. - * - * @throws IllegalMonitorStateException - * Unlocking objects without lock. - */ - public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock); - - /** - * Attempts to release all locks(read and write) for a given context. - */ - public void unlock(CONTEXT context); - - public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock); - - public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock); - - /** - * @author Simon McDuff - */ - public static enum LockType - { - WRITE, READ, - - /** - * @since 3.2 - */ - OPTION - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.Collection;
+
+/**
+ * Support Multiple reads/no write and upgrade lock from read to write. Many context could request
+ * {@link LockType#WRITE write} lock at the same time. It will privileges first context that has already a
+ * {@link LockType#READ read} lock. If no one has any read lock, it's "first come first serve".
+ *
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public interface IRWLockManager<OBJECT, CONTEXT>
+{
+ public static final int WAIT = 0;
+
+ public static final int NO_WAIT = 1;
+
+ public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout)
+ throws InterruptedException;
+
+ public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException;
+
+ /**
+ * Attempts to release for a given locktype, context and objects.
+ *
+ * @throws IllegalMonitorStateException
+ * Unlocking objects without lock.
+ */
+ public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock);
+
+ /**
+ * Attempts to release all locks(read and write) for a given context.
+ */
+ public void unlock(CONTEXT context);
+
+ public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock);
+
+ public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock);
+
+ /**
+ * @author Simon McDuff
+ */
+ public static enum LockType
+ {
+ WRITE, READ,
+
+ /**
+ * @since 3.2
+ */
+ OPTION
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java index 0b033fa40b..53fed6ed48 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Caspar De Groot - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.concurrent.RWOLockManager.LockState; - -import java.util.Collection; -import java.util.List; - -/** - * @author Caspar De Groot - * @since 3.2 - */ -public interface IRWOLockManager<OBJECT, CONTEXT> extends IRWLockManager<OBJECT, CONTEXT> -{ - public List<LockState<OBJECT, CONTEXT>> lock2(LockType type, CONTEXT context, - Collection<? extends OBJECT> objectsToLock, long timeout) throws InterruptedException; - - public List<LockState<OBJECT, CONTEXT>> unlock2(LockType type, CONTEXT context, - Collection<? extends OBJECT> objectsToUnlock); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Caspar De Groot - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.concurrent.RWOLockManager.LockState;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author Caspar De Groot
+ * @since 3.2
+ */
+public interface IRWOLockManager<OBJECT, CONTEXT> extends IRWLockManager<OBJECT, CONTEXT>
+{
+ public List<LockState<OBJECT, CONTEXT>> lock2(LockType type, CONTEXT context,
+ Collection<? extends OBJECT> objectsToLock, long timeout) throws InterruptedException;
+
+ public List<LockState<OBJECT, CONTEXT>> unlock2(LockType type, CONTEXT context,
+ Collection<? extends OBJECT> objectsToUnlock);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java index 0cb0a75db2..02db259b42 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java @@ -1,28 +1,28 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -/** - * Synchronizes a producer and a consumer thread letting the producer pass a value to the consumer. Both producer and - * consumer must have access to this {@link ISynchronizer} and there must only ever exist one consumer for it. Once the - * result value is consumed by the consumer this {@link ISynchronizer} must not be reused. - * <p> - * - * @author Eike Stepper - */ -public interface ISynchronizer<RESULT> -{ - public RESULT get(long timeout); - - public void put(RESULT result); - - public boolean put(RESULT result, long timeout); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * Synchronizes a producer and a consumer thread letting the producer pass a value to the consumer. Both producer and
+ * consumer must have access to this {@link ISynchronizer} and there must only ever exist one consumer for it. Once the
+ * result value is consumed by the consumer this {@link ISynchronizer} must not be reused.
+ * <p>
+ *
+ * @author Eike Stepper
+ */
+public interface ISynchronizer<RESULT>
+{
+ public RESULT get(long timeout);
+
+ public void put(RESULT result);
+
+ public boolean put(RESULT result, long timeout);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java index 5ccc8a6a02..782af3d834 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -/** - * @author Eike Stepper - */ -public interface IWorkSerializer -{ - public boolean addWork(Runnable work); - - public void dispose(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IWorkSerializer
+{
+ public boolean addWork(Runnable work);
+
+ public void dispose();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java index d4f46845c0..79287f00f5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java @@ -1,261 +1,261 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.WrappedException; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class MonitoredThread extends Thread -{ - private MonitoredThread.ThreadMonitor monitor; - - private long timeStamp; - - private boolean shutdown; - - public MonitoredThread(String name, MonitoredThread.ThreadMonitor monitor) - { - super(name); - this.monitor = monitor; - } - - public long getTimeStamp() - { - return timeStamp; - } - - public boolean isIdleTimeoutExpired(long idleTimeOut) - { - if (timeStamp != 0L) // Skip in first loop - { - long idle = System.currentTimeMillis() - timeStamp; - return idle > idleTimeOut; - } - - return false; - } - - public void heartBeat() - { - if (shutdown) - { - throw new ShutdownException(); - } - - timeStamp = System.currentTimeMillis(); - } - - public void shutdown() - { - shutdown = true; - } - - @Override - public void run() - { - monitor.handleStarting(this); - - try - { - doRun(); - } - catch (MonitoredThread.ShutdownException ex) - { - return; - } - catch (Exception ex) - { - OM.LOG.error(ex); - throw WrappedException.wrap(ex); - } - finally - { - monitor.handleFinished(this); - } - } - - protected abstract void doRun() throws Exception; - - /** - * @author Eike Stepper - */ - private static final class ShutdownException extends RuntimeException - { - private static final long serialVersionUID = 1L; - } - - /** - * @author Eike Stepper - */ - public static interface ThreadMonitor - { - public void handleStarting(MonitoredThread thread); - - public void handleFinished(MonitoredThread thread); - } - - /** - * @author Eike Stepper - */ - public static class MultiThreadMonitor implements MonitoredThread.ThreadMonitor, Runnable - { - public static final long SYNCED_START = -1; - - private long idleTimeOut; - - private long startOffset; - - private CountDownLatch startLatch; - - private List<MonitoredThread> threads = new ArrayList<MonitoredThread>(); - - /** - * @param idleTimeOut - * The number of milli seconds one of the threads may be idle (i.e. not having called - * {@link MonitoredThread#heartBeat()}) before {@link #handleTimeoutExpiration(MonitoredThread)} is called. - * @param startOffset - * The number of milli seconds to sleep between threads are started. Zero means not to sleep and - * {@link #SYNCED_START} means that all threads start at the same time by waiting on a shared latch. - */ - public MultiThreadMonitor(long idleTimeOut, long startOffset) - { - this.idleTimeOut = idleTimeOut; - this.startOffset = startOffset; - if (startOffset == SYNCED_START) - { - startLatch = new CountDownLatch(1); - } - } - - /** - * Same as calling <tt>MonitoredThread(idleTimeOut, SYNCED_START)</tt>. - */ - public MultiThreadMonitor(long timeOut) - { - this(timeOut, SYNCED_START); - } - - public long getIdleTimeOut() - { - return idleTimeOut; - } - - public void addThread(MonitoredThread thread) - { - synchronized (threads) - { - threads.add(thread); - } - } - - public void handleStarting(MonitoredThread thread) - { - if (startLatch != null) - { - try - { - startLatch.await(); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } - else if (startOffset > 0L) - { - ConcurrencyUtil.sleep(startOffset); - } - } - - public void handleFinished(MonitoredThread thread) - { - synchronized (threads) - { - threads.remove(thread); - } - } - - public void run() - { - startupThreads(); - - for (;;) - { - List<MonitoredThread> idleThreads = new ArrayList<MonitoredThread>(); - synchronized (threads) - { - if (threads.isEmpty()) - { - break; - } - - for (MonitoredThread thread : threads) - { - if (thread.isIdleTimeoutExpired(idleTimeOut)) - { - idleThreads.add(thread); - } - } - } - - for (MonitoredThread thread : idleThreads) - { - handleTimeoutExpiration(thread); - } - } - - ConcurrencyUtil.sleep(10); - } - - protected void handleTimeoutExpiration(MonitoredThread thread) - { - synchronized (threads) - { - threads.remove(thread); - } - - shutdownThreads(); - throw new RuntimeException("Idle timeout expired: " + thread.getName()); //$NON-NLS-1$ - } - - private void startupThreads() - { - for (MonitoredThread thread : threads) - { - thread.start(); - } - - if (startLatch != null) - { - startLatch.countDown(); - } - } - - private void shutdownThreads() - { - synchronized (threads) - { - for (MonitoredThread t : threads) - { - t.shutdown(); - } - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.WrappedException;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class MonitoredThread extends Thread
+{
+ private MonitoredThread.ThreadMonitor monitor;
+
+ private long timeStamp;
+
+ private boolean shutdown;
+
+ public MonitoredThread(String name, MonitoredThread.ThreadMonitor monitor)
+ {
+ super(name);
+ this.monitor = monitor;
+ }
+
+ public long getTimeStamp()
+ {
+ return timeStamp;
+ }
+
+ public boolean isIdleTimeoutExpired(long idleTimeOut)
+ {
+ if (timeStamp != 0L) // Skip in first loop
+ {
+ long idle = System.currentTimeMillis() - timeStamp;
+ return idle > idleTimeOut;
+ }
+
+ return false;
+ }
+
+ public void heartBeat()
+ {
+ if (shutdown)
+ {
+ throw new ShutdownException();
+ }
+
+ timeStamp = System.currentTimeMillis();
+ }
+
+ public void shutdown()
+ {
+ shutdown = true;
+ }
+
+ @Override
+ public void run()
+ {
+ monitor.handleStarting(this);
+
+ try
+ {
+ doRun();
+ }
+ catch (MonitoredThread.ShutdownException ex)
+ {
+ return;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ monitor.handleFinished(this);
+ }
+ }
+
+ protected abstract void doRun() throws Exception;
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class ShutdownException extends RuntimeException
+ {
+ private static final long serialVersionUID = 1L;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static interface ThreadMonitor
+ {
+ public void handleStarting(MonitoredThread thread);
+
+ public void handleFinished(MonitoredThread thread);
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class MultiThreadMonitor implements MonitoredThread.ThreadMonitor, Runnable
+ {
+ public static final long SYNCED_START = -1;
+
+ private long idleTimeOut;
+
+ private long startOffset;
+
+ private CountDownLatch startLatch;
+
+ private List<MonitoredThread> threads = new ArrayList<MonitoredThread>();
+
+ /**
+ * @param idleTimeOut
+ * The number of milli seconds one of the threads may be idle (i.e. not having called
+ * {@link MonitoredThread#heartBeat()}) before {@link #handleTimeoutExpiration(MonitoredThread)} is called.
+ * @param startOffset
+ * The number of milli seconds to sleep between threads are started. Zero means not to sleep and
+ * {@link #SYNCED_START} means that all threads start at the same time by waiting on a shared latch.
+ */
+ public MultiThreadMonitor(long idleTimeOut, long startOffset)
+ {
+ this.idleTimeOut = idleTimeOut;
+ this.startOffset = startOffset;
+ if (startOffset == SYNCED_START)
+ {
+ startLatch = new CountDownLatch(1);
+ }
+ }
+
+ /**
+ * Same as calling <tt>MonitoredThread(idleTimeOut, SYNCED_START)</tt>.
+ */
+ public MultiThreadMonitor(long timeOut)
+ {
+ this(timeOut, SYNCED_START);
+ }
+
+ public long getIdleTimeOut()
+ {
+ return idleTimeOut;
+ }
+
+ public void addThread(MonitoredThread thread)
+ {
+ synchronized (threads)
+ {
+ threads.add(thread);
+ }
+ }
+
+ public void handleStarting(MonitoredThread thread)
+ {
+ if (startLatch != null)
+ {
+ try
+ {
+ startLatch.await();
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+ else if (startOffset > 0L)
+ {
+ ConcurrencyUtil.sleep(startOffset);
+ }
+ }
+
+ public void handleFinished(MonitoredThread thread)
+ {
+ synchronized (threads)
+ {
+ threads.remove(thread);
+ }
+ }
+
+ public void run()
+ {
+ startupThreads();
+
+ for (;;)
+ {
+ List<MonitoredThread> idleThreads = new ArrayList<MonitoredThread>();
+ synchronized (threads)
+ {
+ if (threads.isEmpty())
+ {
+ break;
+ }
+
+ for (MonitoredThread thread : threads)
+ {
+ if (thread.isIdleTimeoutExpired(idleTimeOut))
+ {
+ idleThreads.add(thread);
+ }
+ }
+ }
+
+ for (MonitoredThread thread : idleThreads)
+ {
+ handleTimeoutExpiration(thread);
+ }
+ }
+
+ ConcurrencyUtil.sleep(10);
+ }
+
+ protected void handleTimeoutExpiration(MonitoredThread thread)
+ {
+ synchronized (threads)
+ {
+ threads.remove(thread);
+ }
+
+ shutdownThreads();
+ throw new RuntimeException("Idle timeout expired: " + thread.getName()); //$NON-NLS-1$
+ }
+
+ private void startupThreads()
+ {
+ for (MonitoredThread thread : threads)
+ {
+ thread.start();
+ }
+
+ if (startLatch != null)
+ {
+ startLatch.countDown();
+ }
+ }
+
+ private void shutdownThreads()
+ {
+ synchronized (threads)
+ {
+ for (MonitoredThread t : threads)
+ {
+ t.shutdown();
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java index 7d4bdc625c..f3048c5864 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java @@ -1,67 +1,67 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author Eike Stepper - */ -public final class NonBlockingIntCounter -{ - private AtomicInteger value; - - public NonBlockingIntCounter() - { - this(0); - } - - public NonBlockingIntCounter(int initialValue) - { - value = new AtomicInteger(initialValue); - } - - public int getValue() - { - return value.get(); - } - - public int increment() - { - int v; - do - { - v = value.get(); - } while (!value.compareAndSet(v, v + 1)); - - return v + 1; - } - - /** - * @since 3.0 - */ - public int decrement() - { - int v; - do - { - v = value.get(); - } while (!value.compareAndSet(v, v - 1)); - - return v - 1; - } - - @Override - public String toString() - { - return Long.toString(getValue()); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * @author Eike Stepper
+ */
+public final class NonBlockingIntCounter
+{
+ private AtomicInteger value;
+
+ public NonBlockingIntCounter()
+ {
+ this(0);
+ }
+
+ public NonBlockingIntCounter(int initialValue)
+ {
+ value = new AtomicInteger(initialValue);
+ }
+
+ public int getValue()
+ {
+ return value.get();
+ }
+
+ public int increment()
+ {
+ int v;
+ do
+ {
+ v = value.get();
+ } while (!value.compareAndSet(v, v + 1));
+
+ return v + 1;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public int decrement()
+ {
+ int v;
+ do
+ {
+ v = value.get();
+ } while (!value.compareAndSet(v, v - 1));
+
+ return v - 1;
+ }
+
+ @Override
+ public String toString()
+ {
+ return Long.toString(getValue());
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java index b90366e7a0..ae65ae9716 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java @@ -1,67 +1,67 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author Eike Stepper - */ -public final class NonBlockingLongCounter -{ - private AtomicLong value; - - public NonBlockingLongCounter() - { - this(0L); - } - - public NonBlockingLongCounter(long initialValue) - { - value = new AtomicLong(initialValue); - } - - public long getValue() - { - return value.get(); - } - - public long increment() - { - long v; - do - { - v = value.get(); - } while (!value.compareAndSet(v, v + 1)); - - return v + 1; - } - - /** - * @since 3.0 - */ - public long decrement() - { - long v; - do - { - v = value.get(); - } while (!value.compareAndSet(v, v - 1)); - - return v - 1; - } - - @Override - public String toString() - { - return Long.toString(getValue()); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * @author Eike Stepper
+ */
+public final class NonBlockingLongCounter
+{
+ private AtomicLong value;
+
+ public NonBlockingLongCounter()
+ {
+ this(0L);
+ }
+
+ public NonBlockingLongCounter(long initialValue)
+ {
+ value = new AtomicLong(initialValue);
+ }
+
+ public long getValue()
+ {
+ return value.get();
+ }
+
+ public long increment()
+ {
+ long v;
+ do
+ {
+ v = value.get();
+ } while (!value.compareAndSet(v, v + 1));
+
+ return v + 1;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public long decrement()
+ {
+ long v;
+ do
+ {
+ v = value.get();
+ } while (!value.compareAndSet(v, v - 1));
+
+ return v - 1;
+ }
+
+ @Override
+ public String toString()
+ {
+ return Long.toString(getValue());
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java index 92a9cf5983..1e40efdb89 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java @@ -1,64 +1,64 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.Executor; - -public class OnePendingExecutor implements Executor -{ - private Runnable command; - - private Thread thread; - - public OnePendingExecutor() - { - } - - public synchronized void execute(Runnable command) - { - if (this.command != null) - { - throw new IllegalStateException("One command already pending"); //$NON-NLS-1$ - } - - this.command = command; - if (thread == null) - { - thread = new Thread() - { - @Override - public void run() - { - for (;;) - { - Runnable command; - synchronized (OnePendingExecutor.this) - { - if (OnePendingExecutor.this.command == null) - { - thread = null; - return; - } - - command = OnePendingExecutor.this.command; - OnePendingExecutor.this.command = null; - } - - command.run(); - } - } - }; - - thread.setDaemon(true); - thread.start(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.Executor;
+
+public class OnePendingExecutor implements Executor
+{
+ private Runnable command;
+
+ private Thread thread;
+
+ public OnePendingExecutor()
+ {
+ }
+
+ public synchronized void execute(Runnable command)
+ {
+ if (this.command != null)
+ {
+ throw new IllegalStateException("One command already pending"); //$NON-NLS-1$
+ }
+
+ this.command = command;
+ if (thread == null)
+ {
+ thread = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ for (;;)
+ {
+ Runnable command;
+ synchronized (OnePendingExecutor.this)
+ {
+ if (OnePendingExecutor.this.command == null)
+ {
+ thread = null;
+ return;
+ }
+
+ command = OnePendingExecutor.this.command;
+ OnePendingExecutor.this.command = null;
+ }
+
+ command.run();
+ }
+ }
+ };
+
+ thread.setDaemon(true);
+ thread.start();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java index eec07be3d6..2d039d8536 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java @@ -1,28 +1,28 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class QueueRunner extends QueueWorker<Runnable> -{ - public QueueRunner() - { - } - - @Override - protected void work(WorkContext context, Runnable runnable) - { - runnable.run(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class QueueRunner extends QueueWorker<Runnable>
+{
+ public QueueRunner()
+ {
+ }
+
+ @Override
+ protected void work(WorkContext context, Runnable runnable)
+ {
+ runnable.run();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java index a835b8dcfa..b4993dd5cd 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java @@ -1,134 +1,134 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class QueueWorker<E> extends Worker -{ - /** - * @since 3.2 - */ - public static final int DEFAULT_POLL_MILLIS = 100; - - private BlockingQueue<E> queue; - - private long pollMillis; - - public QueueWorker() - { - setPollMillis(DEFAULT_POLL_MILLIS); - } - - public long getPollMillis() - { - return pollMillis; - } - - public void setPollMillis(long pollMillis) - { - this.pollMillis = pollMillis; - } - - /** - * @since 3.0 - */ - public void clearQueue() - { - if (queue != null) - { - queue.clear(); - } - } - - public boolean addWork(E element) - { - if (queue != null) - { - return queue.offer(element); - } - - return false; - } - - @Override - protected void work(WorkContext context) throws Exception - { - if (queue == null) - { - context.terminate(); - } - else - { - doWork(context); - } - } - - private void doWork(WorkContext context) throws InterruptedException - { - E element = queue.poll(pollMillis, TimeUnit.MILLISECONDS); - if (element != null) - { - work(context, element); - } - } - - protected abstract void work(WorkContext context, E element); - - protected BlockingQueue<E> createQueue() - { - return new LinkedBlockingQueue<E>(); - } - - /** - * @since 3.1 - */ - protected boolean doRemainingWorkBeforeDeactivate() - { - return false; - } - - @Override - protected void doActivate() throws Exception - { - queue = createQueue(); - super.doActivate(); - } - - @Override - protected void doDeactivate() throws Exception - { - super.doDeactivate(); - if (queue != null) - { - if (doRemainingWorkBeforeDeactivate()) - { - WorkContext context = new WorkContext(); - while (!queue.isEmpty()) - { - doWork(context); - } - } - else - { - queue.clear(); - } - - queue = null; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class QueueWorker<E> extends Worker
+{
+ /**
+ * @since 3.2
+ */
+ public static final int DEFAULT_POLL_MILLIS = 100;
+
+ private BlockingQueue<E> queue;
+
+ private long pollMillis;
+
+ public QueueWorker()
+ {
+ setPollMillis(DEFAULT_POLL_MILLIS);
+ }
+
+ public long getPollMillis()
+ {
+ return pollMillis;
+ }
+
+ public void setPollMillis(long pollMillis)
+ {
+ this.pollMillis = pollMillis;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void clearQueue()
+ {
+ if (queue != null)
+ {
+ queue.clear();
+ }
+ }
+
+ public boolean addWork(E element)
+ {
+ if (queue != null)
+ {
+ return queue.offer(element);
+ }
+
+ return false;
+ }
+
+ @Override
+ protected void work(WorkContext context) throws Exception
+ {
+ if (queue == null)
+ {
+ context.terminate();
+ }
+ else
+ {
+ doWork(context);
+ }
+ }
+
+ private void doWork(WorkContext context) throws InterruptedException
+ {
+ E element = queue.poll(pollMillis, TimeUnit.MILLISECONDS);
+ if (element != null)
+ {
+ work(context, element);
+ }
+ }
+
+ protected abstract void work(WorkContext context, E element);
+
+ protected BlockingQueue<E> createQueue()
+ {
+ return new LinkedBlockingQueue<E>();
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected boolean doRemainingWorkBeforeDeactivate()
+ {
+ return false;
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ queue = createQueue();
+ super.doActivate();
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ super.doDeactivate();
+ if (queue != null)
+ {
+ if (doRemainingWorkBeforeDeactivate())
+ {
+ WorkContext context = new WorkContext();
+ while (!queue.isEmpty())
+ {
+ doWork(context);
+ }
+ }
+ else
+ {
+ queue.clear();
+ }
+
+ queue = null;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java index 51e5748980..de4b985f16 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java @@ -1,30 +1,30 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.lifecycle.LifecycleUtil; -import org.eclipse.net4j.util.om.log.OMLogger; - -/** - * @author Eike Stepper - */ -public class QueueWorkerWorkSerializer extends QueueRunner implements IWorkSerializer -{ - public QueueWorkerWorkSerializer() - { - activate(); - } - - public void dispose() - { - LifecycleUtil.deactivate(this, OMLogger.Level.DEBUG); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
+import org.eclipse.net4j.util.om.log.OMLogger;
+
+/**
+ * @author Eike Stepper
+ */
+public class QueueWorkerWorkSerializer extends QueueRunner implements IWorkSerializer
+{
+ public QueueWorkerWorkSerializer()
+ {
+ activate();
+ }
+
+ public void dispose()
+ {
+ LifecycleUtil.deactivate(this, OMLogger.Level.DEBUG);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java index 6d6f26d6ac..8bf444668d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java @@ -1,112 +1,112 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.WrappedException; - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * @author Eike Stepper - */ -public class RWLock extends ReentrantReadWriteLock -{ - private static final long serialVersionUID = 1L; - - private long timeoutMillis; - - public RWLock(long timeoutMillis) - { - this.timeoutMillis = timeoutMillis; - } - - public RWLock(long timeoutMillis, boolean fair) - { - super(fair); - this.timeoutMillis = timeoutMillis; - } - - public <V> V read(Callable<V> callable) - { - return call(callable, readLock(), timeoutMillis); - } - - public void read(Runnable runnable) - { - run(runnable, readLock(), timeoutMillis); - } - - public <V> V write(Callable<V> callable) - { - return call(callable, writeLock(), timeoutMillis); - } - - public void write(Runnable runnable) - { - run(runnable, writeLock(), timeoutMillis); - } - - public static <V> V call(Callable<V> callable, Lock lock, long timeoutMillis) - { - try - { - boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS); - if (locked) - { - try - { - return callable.call(); - } - finally - { - lock.unlock(); - } - } - - throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void run(Runnable runnable, Lock lock, long timeoutMillis) - { - try - { - boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS); - if (locked) - { - try - { - runnable.run(); - } - finally - { - lock.unlock(); - } - } - else - { - throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.WrappedException;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * @author Eike Stepper
+ */
+public class RWLock extends ReentrantReadWriteLock
+{
+ private static final long serialVersionUID = 1L;
+
+ private long timeoutMillis;
+
+ public RWLock(long timeoutMillis)
+ {
+ this.timeoutMillis = timeoutMillis;
+ }
+
+ public RWLock(long timeoutMillis, boolean fair)
+ {
+ super(fair);
+ this.timeoutMillis = timeoutMillis;
+ }
+
+ public <V> V read(Callable<V> callable)
+ {
+ return call(callable, readLock(), timeoutMillis);
+ }
+
+ public void read(Runnable runnable)
+ {
+ run(runnable, readLock(), timeoutMillis);
+ }
+
+ public <V> V write(Callable<V> callable)
+ {
+ return call(callable, writeLock(), timeoutMillis);
+ }
+
+ public void write(Runnable runnable)
+ {
+ run(runnable, writeLock(), timeoutMillis);
+ }
+
+ public static <V> V call(Callable<V> callable, Lock lock, long timeoutMillis)
+ {
+ try
+ {
+ boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS);
+ if (locked)
+ {
+ try
+ {
+ return callable.call();
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static void run(Runnable runnable, Lock lock, long timeoutMillis)
+ {
+ try
+ {
+ boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS);
+ if (locked)
+ {
+ try
+ {
+ runnable.run();
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+ else
+ {
+ throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java index 257333be4f..50ae00b8af 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java @@ -1,793 +1,793 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Simon McDuff - initial API and implementation - * Eike Stepper - maintenance - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.ObjectUtil; -import org.eclipse.net4j.util.collection.HashBag; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * Support Multiple reads/no write and upgrade lock from read to write. Many context could request - * {@link IRWLockManager.LockType#WRITE write} lock at the same time. It will privileges first context that has already - * a {@link IRWLockManager.LockType#READ read} lock. If no one has any read lock, it's "first come first serve". - * - * @author Simon McDuff - * @since 2.0 - * @deprecated Use {@link RWOLockManager} - */ -@Deprecated -public class RWLockManager<OBJECT, CONTEXT> extends Lifecycle implements IRWLockManager<OBJECT, CONTEXT> -{ - private LockStrategy<OBJECT, CONTEXT> readLockStrategy = new LockStrategy<OBJECT, CONTEXT>() - { - public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.isReadLock(context); - } - - public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.isReadLockByOthers(context); - } - - public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.canObtainReadLock(context); - } - - public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.readLock(context); - } - - public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.readUnlock(context); - } - - @Override - public String toString() - { - return "ReadLockStrategy"; - } - }; - - private LockStrategy<OBJECT, CONTEXT> writeLockStrategy = new LockStrategy<OBJECT, CONTEXT>() - { - public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.isWriteLock(context); - } - - public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.isWriteLockByOthers(context); - } - - public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.canObtainWriteLock(context); - } - - public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.writeLock(context); - } - - public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) - { - return entry.writeUnlock(context); - } - - @Override - public String toString() - { - return "WriteLockStrategy"; - } - }; - - private Map<OBJECT, LockEntry<OBJECT, CONTEXT>> lockEntries = new HashMap<OBJECT, LockEntry<OBJECT, CONTEXT>>(); - - private LockChanged lockChanged = new LockChanged(); - - /** - * @since 3.0 - */ - public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout) - throws InterruptedException - { - LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); - lock(lockingStrategy, context, objectsToLock, timeout); - } - - /** - * @since 3.0 - */ - public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException - { - List<OBJECT> objectsToLock = Collections.singletonList(objectToLock); - lock(type, context, objectsToLock, timeout); - } - - /** - * Attempts to release for a given locktype, context and objects. - * - * @throws IllegalMonitorStateException - * Unlocking objects without lock. - * @since 3.0 - */ - public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock) - { - LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); - unlock(lockingStrategy, context, objectsToUnlock); - } - - /** - * Attempts to release all locks(read and write) for a given context. - */ - public void unlock(CONTEXT context) - { - synchronized (lockChanged) - { - List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); - List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); - - for (Entry<OBJECT, LockEntry<OBJECT, CONTEXT>> entry : lockEntries.entrySet()) - { - LockEntry<OBJECT, CONTEXT> lockedContext = entry.getValue(); - LockEntry<OBJECT, CONTEXT> newEntry = lockedContext.clearLock(context); - if (newEntry == null) - { - lockEntrysToRemove.add(lockedContext); - } - else if (newEntry != entry) - { - lockEntrysToAdd.add(newEntry); - } - } - - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove) - { - OBJECT object = lockEntry.getObject(); - lockEntries.remove(object); - } - - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd) - { - OBJECT object = lockEntry.getObject(); - lockEntries.put(object, lockEntry); - } - - lockChanged.notifyAll(); - } - } - - /** - * @since 3.0 - */ - public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock) - { - LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); - return hasLock(lockingStrategy, context, objectToLock); - } - - /** - * @since 3.0 - */ - public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock) - { - LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); - LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock); - return entry != null && lockingStrategy.isLockedByOthers(entry, context); - } - - /** - * @since 3.1 - */ - protected void handleLockEntries(CONTEXT context, LockEntryHandler<OBJECT, CONTEXT> handler) - { - synchronized (lockChanged) - { - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values()) - { - if (context == null || lockEntry.hasContext(context)) - { - if (!handler.handleLockEntry(lockEntry)) - { - break; - } - } - } - } - } - - /** - * @since 3.1 - */ - protected LockEntry<OBJECT, CONTEXT> getLockEntry(OBJECT objectToLock) - { - synchronized (lockChanged) - { - return lockEntries.get(objectToLock); - } - } - - /** - * @since 3.1 - */ - protected LockStrategy<OBJECT, CONTEXT> getLockingStrategy(LockType type) - { - if (type == LockType.READ) - { - return readLockStrategy; - } - - if (type == LockType.WRITE) - { - return writeLockStrategy; - } - - throw new IllegalArgumentException("Invalid lock type: " + type); - } - - /** - * @since 3.1 - */ - protected void changeContext(CONTEXT oldContext, CONTEXT newContext) - { - synchronized (lockChanged) - { - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values()) - { - lockEntry.changeContext(oldContext, newContext); - } - } - } - - /** - * Attempts to release this lock. - * <p> - * If the number of context is now zero then the lock is made available for write lock attempts. - * - * @throws IllegalMonitorStateException - * Unlocking object not locked. - */ - private void unlock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, - Collection<? extends OBJECT> objectsToLock) - { - synchronized (lockChanged) - { - List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); - List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); - for (OBJECT objectToLock : objectsToLock) - { - LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock); - if (entry == null) - { - throw new IllegalMonitorStateException(); - } - - LockEntry<OBJECT, CONTEXT> newEntry = lockingStrategy.unlock(entry, context); - if (newEntry == null) - { - lockEntrysToRemove.add(entry); - } - else if (newEntry != entry) - { - lockEntrysToAdd.add(newEntry); - } - } - - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove) - { - OBJECT object = lockEntry.getObject(); - lockEntries.remove(object); - } - - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd) - { - OBJECT object = lockEntry.getObject(); - lockEntries.put(object, lockEntry); - } - - lockChanged.notifyAll(); - } - } - - private boolean hasLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, OBJECT objectToLock) - { - LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock); - return entry != null && lockingStrategy.isLocked(entry, context); - } - - private void lock(LockStrategy<OBJECT, CONTEXT> lockStrategy, CONTEXT context, - Collection<? extends OBJECT> objectsToLocks, long timeout) throws InterruptedException - { - long startTime = System.currentTimeMillis(); - while (true) - { - synchronized (lockChanged) - { - OBJECT conflict = obtainLock(lockStrategy, context, objectsToLocks); - if (conflict == null) - { - lockChanged.notifyAll(); - return; - } - - long elapsedTime = System.currentTimeMillis() - startTime; - if (timeout != WAIT && elapsedTime > timeout) - { - throw new TimeoutRuntimeException("Could not lock " + conflict + " within " + timeout + " milli seconds"); //$NON-NLS-1$ - } - - if (timeout == WAIT) - { - lockChanged.wait(); - } - else - { - lockChanged.wait(Math.max(1, timeout - elapsedTime)); - } - } - } - } - - private OBJECT obtainLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, - Collection<? extends OBJECT> objectsToLock) - { - List<LockEntry<OBJECT, CONTEXT>> lockEntrys = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); - for (OBJECT objectToLock : objectsToLock) - { - LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock); - if (entry == null) - { - entry = new NoLockEntry<OBJECT, CONTEXT>(objectToLock); - } - - if (lockingStrategy.canObtainLock(entry, context)) - { - lockEntrys.add(entry); - } - else - { - return objectToLock; - } - } - - for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrys) - { - OBJECT object = lockEntry.getObject(); - LockEntry<OBJECT, CONTEXT> lock = lockingStrategy.lock(lockEntry, context); - lockEntries.put(object, lock); - } - - return null; - } - - /** - * @author Simon McDuff - * @since 3.1 - * @deprecated Use {@link RWOLockManager} - */ - @Deprecated - protected interface LockStrategy<OBJECT, CONTEXT> - { - public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); - - public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); - - public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); - } - - /** - * @author Simon McDuff - * @since 3.1 - * @deprecated Use {@link RWOLockManager} - */ - @Deprecated - protected interface LockEntry<OBJECT, CONTEXT> - { - public OBJECT getObject(); - - public boolean isReadLock(CONTEXT context); - - public boolean isWriteLock(CONTEXT context); - - public boolean isReadLockByOthers(CONTEXT context); - - public boolean isWriteLockByOthers(CONTEXT context); - - public boolean canObtainReadLock(CONTEXT context); - - public boolean canObtainWriteLock(CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context); - - public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context); - - /** - * @since 3.1 - */ - public void changeContext(CONTEXT oldContext, CONTEXT newContext); - - /** - * @since 3.1 - */ - public boolean hasContext(CONTEXT context); - } - - /** - * @author Eike Stepper - * @since 3.1 - * @deprecated Use {@link RWOLockManager} - */ - @Deprecated - protected interface LockEntryHandler<OBJECT, CONTEXT> - { - public boolean handleLockEntry(LockEntry<OBJECT, CONTEXT> lockEntry); - } - - /** - * @author Simon McDuff - */ - private static final class ReadLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT> - { - private OBJECT object; - - private Set<CONTEXT> contexts = new HashBag<CONTEXT>(); - - public ReadLockEntry(OBJECT objectToLock, CONTEXT context) - { - this.object = objectToLock; - contexts.add(context); - } - - public OBJECT getObject() - { - return object; - } - - public boolean isReadLock(CONTEXT context) - { - return contexts.contains(context); - } - - public boolean isWriteLock(CONTEXT context) - { - return false; - } - - public boolean isReadLockByOthers(CONTEXT context) - { - if (contexts.isEmpty()) - { - return false; - } - - return contexts.size() > (isReadLock(context) ? 1 : 0); - } - - public boolean isWriteLockByOthers(CONTEXT context) - { - return false; - } - - public boolean canObtainReadLock(CONTEXT context) - { - return true; - } - - public boolean canObtainWriteLock(CONTEXT context) - { - return contexts.size() == 1 && contexts.contains(context); - } - - public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context) - { - contexts.add(context); - return this; - } - - public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context) - { - return new WriteLockEntry<OBJECT, CONTEXT>(object, context, this); - } - - public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context) - { - contexts.remove(context); - return contexts.isEmpty() ? null : this; - } - - public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context) - { - throw new IllegalMonitorStateException(); - } - - public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context) - { - while (contexts.remove(context)) - { - } - - return contexts.isEmpty() ? null : this; - } - - public void changeContext(CONTEXT oldContext, CONTEXT newContext) - { - if (contexts.remove(oldContext)) - { - contexts.add(newContext); - } - } - - public boolean hasContext(CONTEXT context) - { - return contexts.contains(context); - } - - @Override - public String toString() - { - return MessageFormat.format("ReadLockEntry[object={0}, contexts={1}]", object, contexts); - } - } - - /** - * @author Simon McDuff - */ - private static final class WriteLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT> - { - private OBJECT object; - - private CONTEXT context; - - private int count; - - private ReadLockEntry<OBJECT, CONTEXT> readLock; - - public WriteLockEntry(OBJECT object, CONTEXT context, ReadLockEntry<OBJECT, CONTEXT> readLock) - { - this.object = object; - this.context = context; - this.readLock = readLock; - this.count = 1; - } - - public OBJECT getObject() - { - return object; - } - - public boolean isReadLock(CONTEXT context) - { - return readLock != null ? readLock.isReadLock(context) : false; - } - - public boolean isWriteLock(CONTEXT context) - { - return ObjectUtil.equals(this.context, context); - } - - public boolean isReadLockByOthers(CONTEXT context) - { - return readLock != null ? readLock.isReadLockByOthers(context) : false; - } - - public boolean isWriteLockByOthers(CONTEXT context) - { - return context != this.context; - } - - public boolean canObtainWriteLock(CONTEXT context) - { - return ObjectUtil.equals(this.context, context); - } - - public boolean canObtainReadLock(CONTEXT context) - { - return ObjectUtil.equals(this.context, context); - } - - public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context) - { - ReadLockEntry<OBJECT, CONTEXT> lock = getReadLock(); - lock.readLock(context); - return this; - } - - public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context) - { - count++; - return this; - } - - public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context) - { - if (readLock != null) - { - if (readLock.readUnlock(context) == null) - { - readLock = null; - } - - return this; - } - - throw new IllegalMonitorStateException(); - } - - public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context) - { - return --count <= 0 ? readLock : this; - } - - public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context) - { - if (readLock != null) - { - if (readLock.clearLock(context) == null) - { - readLock = null; - } - } - - return ObjectUtil.equals(this.context, context) ? readLock : this; - } - - public void changeContext(CONTEXT oldContext, CONTEXT newContext) - { - if (ObjectUtil.equals(context, oldContext)) - { - context = newContext; - } - } - - public boolean hasContext(CONTEXT context) - { - return ObjectUtil.equals(this.context, context); - } - - @Override - public String toString() - { - return MessageFormat.format("WriteLockEntry[object={0}, context={1}, count={2}]", object, context, count); - } - - private ReadLockEntry<OBJECT, CONTEXT> getReadLock() - { - if (readLock == null) - { - readLock = new ReadLockEntry<OBJECT, CONTEXT>(object, context); - } - - return readLock; - } - } - - /** - * @author Simon McDuff - */ - private static final class NoLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT> - { - private OBJECT object; - - public NoLockEntry(OBJECT objectToLock) - { - this.object = objectToLock; - } - - public OBJECT getObject() - { - return object; - } - - public boolean isReadLock(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public boolean isWriteLock(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public boolean isReadLockByOthers(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public boolean isWriteLockByOthers(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public boolean canObtainWriteLock(CONTEXT context) - { - return true; - } - - public boolean canObtainReadLock(CONTEXT context) - { - return true; - } - - public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context) - { - return new ReadLockEntry<OBJECT, CONTEXT>(object, context); - } - - public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context) - { - return new WriteLockEntry<OBJECT, CONTEXT>(object, context, null); - } - - public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context) - { - throw new UnsupportedOperationException(); - } - - public void changeContext(CONTEXT oldContext, CONTEXT newContext) - { - // Do nothing - } - - public boolean hasContext(CONTEXT context) - { - return false; - } - - @Override - public String toString() - { - return MessageFormat.format("NoLockEntry[object={0}]", object); - } - } - - /** - * @author Eike Stepper - */ - private static final class LockChanged - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Simon McDuff - initial API and implementation
+ * Eike Stepper - maintenance
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.ObjectUtil;
+import org.eclipse.net4j.util.collection.HashBag;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+/**
+ * Support Multiple reads/no write and upgrade lock from read to write. Many context could request
+ * {@link IRWLockManager.LockType#WRITE write} lock at the same time. It will privileges first context that has already
+ * a {@link IRWLockManager.LockType#READ read} lock. If no one has any read lock, it's "first come first serve".
+ *
+ * @author Simon McDuff
+ * @since 2.0
+ * @deprecated Use {@link RWOLockManager}
+ */
+@Deprecated
+public class RWLockManager<OBJECT, CONTEXT> extends Lifecycle implements IRWLockManager<OBJECT, CONTEXT>
+{
+ private LockStrategy<OBJECT, CONTEXT> readLockStrategy = new LockStrategy<OBJECT, CONTEXT>()
+ {
+ public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.isReadLock(context);
+ }
+
+ public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.isReadLockByOthers(context);
+ }
+
+ public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.canObtainReadLock(context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.readLock(context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.readUnlock(context);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "ReadLockStrategy";
+ }
+ };
+
+ private LockStrategy<OBJECT, CONTEXT> writeLockStrategy = new LockStrategy<OBJECT, CONTEXT>()
+ {
+ public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.isWriteLock(context);
+ }
+
+ public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.isWriteLockByOthers(context);
+ }
+
+ public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.canObtainWriteLock(context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.writeLock(context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
+ {
+ return entry.writeUnlock(context);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "WriteLockStrategy";
+ }
+ };
+
+ private Map<OBJECT, LockEntry<OBJECT, CONTEXT>> lockEntries = new HashMap<OBJECT, LockEntry<OBJECT, CONTEXT>>();
+
+ private LockChanged lockChanged = new LockChanged();
+
+ /**
+ * @since 3.0
+ */
+ public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout)
+ throws InterruptedException
+ {
+ LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
+ lock(lockingStrategy, context, objectsToLock, timeout);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException
+ {
+ List<OBJECT> objectsToLock = Collections.singletonList(objectToLock);
+ lock(type, context, objectsToLock, timeout);
+ }
+
+ /**
+ * Attempts to release for a given locktype, context and objects.
+ *
+ * @throws IllegalMonitorStateException
+ * Unlocking objects without lock.
+ * @since 3.0
+ */
+ public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock)
+ {
+ LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
+ unlock(lockingStrategy, context, objectsToUnlock);
+ }
+
+ /**
+ * Attempts to release all locks(read and write) for a given context.
+ */
+ public void unlock(CONTEXT context)
+ {
+ synchronized (lockChanged)
+ {
+ List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
+ List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
+
+ for (Entry<OBJECT, LockEntry<OBJECT, CONTEXT>> entry : lockEntries.entrySet())
+ {
+ LockEntry<OBJECT, CONTEXT> lockedContext = entry.getValue();
+ LockEntry<OBJECT, CONTEXT> newEntry = lockedContext.clearLock(context);
+ if (newEntry == null)
+ {
+ lockEntrysToRemove.add(lockedContext);
+ }
+ else if (newEntry != entry)
+ {
+ lockEntrysToAdd.add(newEntry);
+ }
+ }
+
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove)
+ {
+ OBJECT object = lockEntry.getObject();
+ lockEntries.remove(object);
+ }
+
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd)
+ {
+ OBJECT object = lockEntry.getObject();
+ lockEntries.put(object, lockEntry);
+ }
+
+ lockChanged.notifyAll();
+ }
+ }
+
+ /**
+ * @since 3.0
+ */
+ public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock)
+ {
+ LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
+ return hasLock(lockingStrategy, context, objectToLock);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock)
+ {
+ LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
+ LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock);
+ return entry != null && lockingStrategy.isLockedByOthers(entry, context);
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected void handleLockEntries(CONTEXT context, LockEntryHandler<OBJECT, CONTEXT> handler)
+ {
+ synchronized (lockChanged)
+ {
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values())
+ {
+ if (context == null || lockEntry.hasContext(context))
+ {
+ if (!handler.handleLockEntry(lockEntry))
+ {
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected LockEntry<OBJECT, CONTEXT> getLockEntry(OBJECT objectToLock)
+ {
+ synchronized (lockChanged)
+ {
+ return lockEntries.get(objectToLock);
+ }
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected LockStrategy<OBJECT, CONTEXT> getLockingStrategy(LockType type)
+ {
+ if (type == LockType.READ)
+ {
+ return readLockStrategy;
+ }
+
+ if (type == LockType.WRITE)
+ {
+ return writeLockStrategy;
+ }
+
+ throw new IllegalArgumentException("Invalid lock type: " + type);
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected void changeContext(CONTEXT oldContext, CONTEXT newContext)
+ {
+ synchronized (lockChanged)
+ {
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values())
+ {
+ lockEntry.changeContext(oldContext, newContext);
+ }
+ }
+ }
+
+ /**
+ * Attempts to release this lock.
+ * <p>
+ * If the number of context is now zero then the lock is made available for write lock attempts.
+ *
+ * @throws IllegalMonitorStateException
+ * Unlocking object not locked.
+ */
+ private void unlock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context,
+ Collection<? extends OBJECT> objectsToLock)
+ {
+ synchronized (lockChanged)
+ {
+ List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
+ List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
+ for (OBJECT objectToLock : objectsToLock)
+ {
+ LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock);
+ if (entry == null)
+ {
+ throw new IllegalMonitorStateException();
+ }
+
+ LockEntry<OBJECT, CONTEXT> newEntry = lockingStrategy.unlock(entry, context);
+ if (newEntry == null)
+ {
+ lockEntrysToRemove.add(entry);
+ }
+ else if (newEntry != entry)
+ {
+ lockEntrysToAdd.add(newEntry);
+ }
+ }
+
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove)
+ {
+ OBJECT object = lockEntry.getObject();
+ lockEntries.remove(object);
+ }
+
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd)
+ {
+ OBJECT object = lockEntry.getObject();
+ lockEntries.put(object, lockEntry);
+ }
+
+ lockChanged.notifyAll();
+ }
+ }
+
+ private boolean hasLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, OBJECT objectToLock)
+ {
+ LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock);
+ return entry != null && lockingStrategy.isLocked(entry, context);
+ }
+
+ private void lock(LockStrategy<OBJECT, CONTEXT> lockStrategy, CONTEXT context,
+ Collection<? extends OBJECT> objectsToLocks, long timeout) throws InterruptedException
+ {
+ long startTime = System.currentTimeMillis();
+ while (true)
+ {
+ synchronized (lockChanged)
+ {
+ OBJECT conflict = obtainLock(lockStrategy, context, objectsToLocks);
+ if (conflict == null)
+ {
+ lockChanged.notifyAll();
+ return;
+ }
+
+ long elapsedTime = System.currentTimeMillis() - startTime;
+ if (timeout != WAIT && elapsedTime > timeout)
+ {
+ throw new TimeoutRuntimeException("Could not lock " + conflict + " within " + timeout + " milli seconds"); //$NON-NLS-1$
+ }
+
+ if (timeout == WAIT)
+ {
+ lockChanged.wait();
+ }
+ else
+ {
+ lockChanged.wait(Math.max(1, timeout - elapsedTime));
+ }
+ }
+ }
+ }
+
+ private OBJECT obtainLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context,
+ Collection<? extends OBJECT> objectsToLock)
+ {
+ List<LockEntry<OBJECT, CONTEXT>> lockEntrys = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
+ for (OBJECT objectToLock : objectsToLock)
+ {
+ LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock);
+ if (entry == null)
+ {
+ entry = new NoLockEntry<OBJECT, CONTEXT>(objectToLock);
+ }
+
+ if (lockingStrategy.canObtainLock(entry, context))
+ {
+ lockEntrys.add(entry);
+ }
+ else
+ {
+ return objectToLock;
+ }
+ }
+
+ for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrys)
+ {
+ OBJECT object = lockEntry.getObject();
+ LockEntry<OBJECT, CONTEXT> lock = lockingStrategy.lock(lockEntry, context);
+ lockEntries.put(object, lock);
+ }
+
+ return null;
+ }
+
+ /**
+ * @author Simon McDuff
+ * @since 3.1
+ * @deprecated Use {@link RWOLockManager}
+ */
+ @Deprecated
+ protected interface LockStrategy<OBJECT, CONTEXT>
+ {
+ public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
+
+ public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
+
+ public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
+ }
+
+ /**
+ * @author Simon McDuff
+ * @since 3.1
+ * @deprecated Use {@link RWOLockManager}
+ */
+ @Deprecated
+ protected interface LockEntry<OBJECT, CONTEXT>
+ {
+ public OBJECT getObject();
+
+ public boolean isReadLock(CONTEXT context);
+
+ public boolean isWriteLock(CONTEXT context);
+
+ public boolean isReadLockByOthers(CONTEXT context);
+
+ public boolean isWriteLockByOthers(CONTEXT context);
+
+ public boolean canObtainReadLock(CONTEXT context);
+
+ public boolean canObtainWriteLock(CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context);
+
+ public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context);
+
+ /**
+ * @since 3.1
+ */
+ public void changeContext(CONTEXT oldContext, CONTEXT newContext);
+
+ /**
+ * @since 3.1
+ */
+ public boolean hasContext(CONTEXT context);
+ }
+
+ /**
+ * @author Eike Stepper
+ * @since 3.1
+ * @deprecated Use {@link RWOLockManager}
+ */
+ @Deprecated
+ protected interface LockEntryHandler<OBJECT, CONTEXT>
+ {
+ public boolean handleLockEntry(LockEntry<OBJECT, CONTEXT> lockEntry);
+ }
+
+ /**
+ * @author Simon McDuff
+ */
+ private static final class ReadLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT>
+ {
+ private OBJECT object;
+
+ private Set<CONTEXT> contexts = new HashBag<CONTEXT>();
+
+ public ReadLockEntry(OBJECT objectToLock, CONTEXT context)
+ {
+ this.object = objectToLock;
+ contexts.add(context);
+ }
+
+ public OBJECT getObject()
+ {
+ return object;
+ }
+
+ public boolean isReadLock(CONTEXT context)
+ {
+ return contexts.contains(context);
+ }
+
+ public boolean isWriteLock(CONTEXT context)
+ {
+ return false;
+ }
+
+ public boolean isReadLockByOthers(CONTEXT context)
+ {
+ if (contexts.isEmpty())
+ {
+ return false;
+ }
+
+ return contexts.size() > (isReadLock(context) ? 1 : 0);
+ }
+
+ public boolean isWriteLockByOthers(CONTEXT context)
+ {
+ return false;
+ }
+
+ public boolean canObtainReadLock(CONTEXT context)
+ {
+ return true;
+ }
+
+ public boolean canObtainWriteLock(CONTEXT context)
+ {
+ return contexts.size() == 1 && contexts.contains(context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context)
+ {
+ contexts.add(context);
+ return this;
+ }
+
+ public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context)
+ {
+ return new WriteLockEntry<OBJECT, CONTEXT>(object, context, this);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context)
+ {
+ contexts.remove(context);
+ return contexts.isEmpty() ? null : this;
+ }
+
+ public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context)
+ {
+ throw new IllegalMonitorStateException();
+ }
+
+ public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context)
+ {
+ while (contexts.remove(context))
+ {
+ }
+
+ return contexts.isEmpty() ? null : this;
+ }
+
+ public void changeContext(CONTEXT oldContext, CONTEXT newContext)
+ {
+ if (contexts.remove(oldContext))
+ {
+ contexts.add(newContext);
+ }
+ }
+
+ public boolean hasContext(CONTEXT context)
+ {
+ return contexts.contains(context);
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("ReadLockEntry[object={0}, contexts={1}]", object, contexts);
+ }
+ }
+
+ /**
+ * @author Simon McDuff
+ */
+ private static final class WriteLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT>
+ {
+ private OBJECT object;
+
+ private CONTEXT context;
+
+ private int count;
+
+ private ReadLockEntry<OBJECT, CONTEXT> readLock;
+
+ public WriteLockEntry(OBJECT object, CONTEXT context, ReadLockEntry<OBJECT, CONTEXT> readLock)
+ {
+ this.object = object;
+ this.context = context;
+ this.readLock = readLock;
+ this.count = 1;
+ }
+
+ public OBJECT getObject()
+ {
+ return object;
+ }
+
+ public boolean isReadLock(CONTEXT context)
+ {
+ return readLock != null ? readLock.isReadLock(context) : false;
+ }
+
+ public boolean isWriteLock(CONTEXT context)
+ {
+ return ObjectUtil.equals(this.context, context);
+ }
+
+ public boolean isReadLockByOthers(CONTEXT context)
+ {
+ return readLock != null ? readLock.isReadLockByOthers(context) : false;
+ }
+
+ public boolean isWriteLockByOthers(CONTEXT context)
+ {
+ return context != this.context;
+ }
+
+ public boolean canObtainWriteLock(CONTEXT context)
+ {
+ return ObjectUtil.equals(this.context, context);
+ }
+
+ public boolean canObtainReadLock(CONTEXT context)
+ {
+ return ObjectUtil.equals(this.context, context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context)
+ {
+ ReadLockEntry<OBJECT, CONTEXT> lock = getReadLock();
+ lock.readLock(context);
+ return this;
+ }
+
+ public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context)
+ {
+ count++;
+ return this;
+ }
+
+ public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context)
+ {
+ if (readLock != null)
+ {
+ if (readLock.readUnlock(context) == null)
+ {
+ readLock = null;
+ }
+
+ return this;
+ }
+
+ throw new IllegalMonitorStateException();
+ }
+
+ public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context)
+ {
+ return --count <= 0 ? readLock : this;
+ }
+
+ public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context)
+ {
+ if (readLock != null)
+ {
+ if (readLock.clearLock(context) == null)
+ {
+ readLock = null;
+ }
+ }
+
+ return ObjectUtil.equals(this.context, context) ? readLock : this;
+ }
+
+ public void changeContext(CONTEXT oldContext, CONTEXT newContext)
+ {
+ if (ObjectUtil.equals(context, oldContext))
+ {
+ context = newContext;
+ }
+ }
+
+ public boolean hasContext(CONTEXT context)
+ {
+ return ObjectUtil.equals(this.context, context);
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("WriteLockEntry[object={0}, context={1}, count={2}]", object, context, count);
+ }
+
+ private ReadLockEntry<OBJECT, CONTEXT> getReadLock()
+ {
+ if (readLock == null)
+ {
+ readLock = new ReadLockEntry<OBJECT, CONTEXT>(object, context);
+ }
+
+ return readLock;
+ }
+ }
+
+ /**
+ * @author Simon McDuff
+ */
+ private static final class NoLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT>
+ {
+ private OBJECT object;
+
+ public NoLockEntry(OBJECT objectToLock)
+ {
+ this.object = objectToLock;
+ }
+
+ public OBJECT getObject()
+ {
+ return object;
+ }
+
+ public boolean isReadLock(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isWriteLock(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isReadLockByOthers(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isWriteLockByOthers(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean canObtainWriteLock(CONTEXT context)
+ {
+ return true;
+ }
+
+ public boolean canObtainReadLock(CONTEXT context)
+ {
+ return true;
+ }
+
+ public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context)
+ {
+ return new ReadLockEntry<OBJECT, CONTEXT>(object, context);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context)
+ {
+ return new WriteLockEntry<OBJECT, CONTEXT>(object, context, null);
+ }
+
+ public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void changeContext(CONTEXT oldContext, CONTEXT newContext)
+ {
+ // Do nothing
+ }
+
+ public boolean hasContext(CONTEXT context)
+ {
+ return false;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("NoLockEntry[object={0}]", object);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class LockChanged
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWOLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWOLockManager.java index 286abe77bf..a2d0014c9c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWOLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWOLockManager.java @@ -1,749 +1,749 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Caspar De Groot - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.CheckUtil; -import org.eclipse.net4j.util.ObjectUtil; -import org.eclipse.net4j.util.collection.HashBag; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Keeps track of locks on objects. Locks are owned by contexts. A particular combination of locks and their owners, for - * a given object, is represented by instances of the {@link LockState} class. This class is also repsonsible for - * deciding whether or not a new lock can be granted, based on the locks already present. - * - * @author Caspar De Groot - * @since 3.2 - */ -public class RWOLockManager<OBJECT, CONTEXT> extends Lifecycle implements IRWOLockManager<OBJECT, CONTEXT> -{ - private final List<LockState<OBJECT, CONTEXT>> EMPTY_RESULT = Collections.emptyList(); - - private final Map<OBJECT, LockState<OBJECT, CONTEXT>> objectToLockStateMap = createObjectToLocksMap(); - - /** - * A mapping of contexts (owners of locks) to the lock states that they are involved in. Here, an 'involvement' means - * that the context owns at least one lock on the object that the lock state is for. To determine exactly what kind of - * lock, the lock state object obtained from this map must be queried. - * <p> - * This map is a performance optimization to avoid having to scan all lock states. - */ - private final Map<CONTEXT, Set<LockState<OBJECT, CONTEXT>>> contextToLockStates = createContextToLocksMap(); - - public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout) - throws InterruptedException - { - lock2(type, context, objectsToLock, timeout); - } - - public List<LockState<OBJECT, CONTEXT>> lock2(LockType type, CONTEXT context, - Collection<? extends OBJECT> objectsToLock, long timeout) throws InterruptedException - { - if (objectsToLock.isEmpty()) - { - return EMPTY_RESULT; - } - - // Must come before the synchronized block! - long startTime = timeout == WAIT ? 0L : currentTimeMillis(); - - // Do not synchronize the entire method as it would corrupt the timeout! - synchronized (this) - { - int count = objectsToLock.size(); - List<LockState<OBJECT, CONTEXT>> lockStates = new ArrayList<LockState<OBJECT, CONTEXT>>(count); - - for (;;) - { - if (canLockInContext(type, context, objectsToLock, lockStates)) - { - for (int i = 0; i < count; i++) - { - LockState<OBJECT, CONTEXT> lockState = lockStates.get(i); - lockState.lock(type, context); - addContextToLockStateMapping(context, lockState); - } - - return lockStates; - } - - wait(startTime, timeout); - } - } - } - - public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException - { - // Do not synchronize the entire method as it would corrupt the timeout! - lock(type, context, Collections.singleton(objectToLock), timeout); - } - - public synchronized void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock) - { - unlock2(type, context, objectsToUnlock); - } - - public synchronized List<LockState<OBJECT, CONTEXT>> unlock2(LockType type, CONTEXT context, - Collection<? extends OBJECT> objectsToUnlock) - { - if (objectsToUnlock.isEmpty()) - { - return EMPTY_RESULT; - } - - List<LockState<OBJECT, CONTEXT>> lockStates = new LinkedList<LockState<OBJECT, CONTEXT>>(); - - Iterator<? extends OBJECT> it = objectsToUnlock.iterator(); - while (it.hasNext()) - { - OBJECT o = it.next(); - LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(o); - if (lockState == null || !lockState.canUnlock(type, context)) - { - throw new IllegalMonitorStateException(); - } - - lockStates.add(lockState); - } - - for (LockState<OBJECT, CONTEXT> lockState : lockStates) - { - lockState.unlock(type, context); - if (!lockState.hasLocks(context)) - { - removeLockStateForContext(context, lockState); - } - - if (lockState.hasNoLocks()) - { - objectToLockStateMap.remove(lockState.getLockedObject()); - } - } - - notifyAll(); - - return lockStates; - } - - public synchronized void unlock(CONTEXT context) - { - unlock2(context); - } - - public synchronized List<LockState<OBJECT, CONTEXT>> unlock2(CONTEXT context) - { - Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.get(context); - if (lockStates == null) - { - return EMPTY_RESULT; - } - - List<OBJECT> objectsWithoutLocks = new LinkedList<OBJECT>(); - - for (LockState<OBJECT, CONTEXT> lockState : lockStates) - { - for (LockType lockType : LockType.values()) - { - if (lockState.hasLock(lockType, context, false)) - { - lockState.unlock(lockType, context); - } - } - - if (lockState.hasNoLocks()) - { - OBJECT o = lockState.getLockedObject(); - objectsWithoutLocks.add(o); - } - } - - contextToLockStates.remove(context); - - // This must be done outside the above iteration, in order to avoid ConcurrentModEx - for (OBJECT o : objectsWithoutLocks) - { - objectToLockStateMap.remove(o); - } - - notifyAll(); - - return toList(lockStates); - } - - @SuppressWarnings("unchecked") - private List<LockState<OBJECT, CONTEXT>> toList(Set<LockState<OBJECT, CONTEXT>> lockStates) - { - if (lockStates instanceof List) - { - return (List<LockState<OBJECT, CONTEXT>>)lockStates; - } - - List<LockState<OBJECT, CONTEXT>> list = new LinkedList<LockState<OBJECT, CONTEXT>>(); - for (LockState<OBJECT, CONTEXT> lockState : lockStates) - { - list.add(lockState); - } - - return list; - } - - public synchronized boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock) - { - LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(objectToLock); - return lockState != null && lockState.hasLock(type, context, false); - } - - public synchronized boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock) - { - LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(objectToLock); - return lockState != null && lockState.hasLock(type, context, true); - } - - protected synchronized void changeContext(CONTEXT oldContext, CONTEXT newContext) - { - for (LockState<OBJECT, CONTEXT> lockState : objectToLockStateMap.values()) - { - lockState.replaceContext(oldContext, newContext); - } - - Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.remove(oldContext); - if (lockStates != null) - { - contextToLockStates.put(newContext, lockStates); - } - } - - protected long currentTimeMillis() - { - return System.currentTimeMillis(); - } - - protected Map<OBJECT, LockState<OBJECT, CONTEXT>> createObjectToLocksMap() - { - return new HashMap<OBJECT, LockState<OBJECT, CONTEXT>>(); - } - - protected Map<CONTEXT, Set<LockState<OBJECT, CONTEXT>>> createContextToLocksMap() - { - return new HashMap<CONTEXT, Set<LockState<OBJECT, CONTEXT>>>(); - } - - /** - * All access to the returned map must be properly synchronized on this {@link RWOLockManager}. - */ - protected final Map<OBJECT, LockState<OBJECT, CONTEXT>> getObjectToLocksMap() - { - return objectToLockStateMap; - } - - /** - * All access to the returned map must be properly synchronized on this {@link RWOLockManager}. - */ - protected final Map<CONTEXT, Set<LockState<OBJECT, CONTEXT>>> getContextToLocksMap() - { - return contextToLockStates; - } - - public LockState<OBJECT, CONTEXT> getLockState(OBJECT key) - { - return objectToLockStateMap.get(key); - } - - public synchronized void setLockState(OBJECT key, LockState<OBJECT, CONTEXT> lockState) - { - objectToLockStateMap.put(key, lockState); - - for (CONTEXT readLockOwner : lockState.getReadLockOwners()) - { - addContextToLockStateMapping(readLockOwner, lockState); - } - CONTEXT writeLockOwner = lockState.getWriteLockOwner(); - if (writeLockOwner != null) - { - addContextToLockStateMapping(writeLockOwner, lockState); - } - CONTEXT writeOptionOwner = lockState.getWriteOptionOwner(); - if (writeOptionOwner != null) - { - addContextToLockStateMapping(writeOptionOwner, lockState); - } - } - - private LockState<OBJECT, CONTEXT> getOrCreateLockState(OBJECT o) - { - LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(o); - if (lockState == null) - { - lockState = new LockState<OBJECT, CONTEXT>(o); - objectToLockStateMap.put(o, lockState); - } - - return lockState; - } - - private boolean canLockInContext(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, - List<LockState<OBJECT, CONTEXT>> lockStatesToFill) - { - Iterator<? extends OBJECT> it = objectsToLock.iterator(); - for (int i = 0; i < objectsToLock.size(); i++) - { - OBJECT o = it.next(); - LockState<OBJECT, CONTEXT> lockState = getOrCreateLockState(o); - if (!lockState.canLock(type, context)) - { - return false; - } - - lockStatesToFill.add(lockState); - } - - return true; - } - - private void addContextToLockStateMapping(CONTEXT context, LockState<OBJECT, CONTEXT> lockState) - { - Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.get(context); - if (lockStates == null) - { - lockStates = new HashSet<LockState<OBJECT, CONTEXT>>(); - contextToLockStates.put(context, lockStates); - } - - lockStates.add(lockState); - } - - /** - * Removes a lockState from the set of all lockStates that the given context is involved in. If the lockState being - * removed is the last one for the given context, then the set becomes empty, and is therefore removed from the - * contextToLockStates mp. - */ - private void removeLockStateForContext(CONTEXT context, LockState<OBJECT, CONTEXT> lockState) - { - Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.get(context); - lockStates.remove(lockState); - if (lockStates.isEmpty()) - { - contextToLockStates.remove(context); - } - } - - private void wait(long startTime, long timeout) throws InterruptedException - { - if (timeout == WAIT) - { - wait(); - } - else - { - long elapsedTime = currentTimeMillis() - startTime; - long waitTime = timeout - elapsedTime; - if (waitTime < 1) - { - throw new TimeoutRuntimeException("Could not lock objects within " + timeout + " milli seconds"); - } - - wait(waitTime); - } - } - - /** - * Represents a combination of locks for one OBJECT. The different lock types are represented by the values of the - * enum {@link IRWLockManager.LockType} - * <p> - * The locking semantics established by this class are as follows: - * <li>a read lock prevents a write lock by another, but allows read locks by others and allows a write option by - * another, and is therefore <b>non-exclusive</b></li> - * <li>a write lock prevents read locks by others, a write lock by another, and a write option by another, and is - * therefore <b>exclusive</b></li> - * <li>a write option prevents write locks by others and a write option by another, but allows read locks by others, - * and is therefore <b>exclusive</b></li> - * <p> - * - * @author Caspar De Groot - * @since 3.2 - */ - public static class LockState<OBJECT, CONTEXT> - { - private final OBJECT lockedObject; - - private final HashBag<CONTEXT> readLockOwners = new HashBag<CONTEXT>(); - - private CONTEXT writeLockOwner; - - private CONTEXT writeOptionOwner; - - private int writeLockCounter; - - LockState(OBJECT lockedObject) - { - CheckUtil.checkArg(lockedObject, "lockedObject"); - this.lockedObject = lockedObject; - } - - public OBJECT getLockedObject() - { - return lockedObject; - } - - public boolean hasLock(org.eclipse.net4j.util.concurrent.IRWLockManager.LockType type, CONTEXT view, - boolean byOthers) - { - CheckUtil.checkArg(view, "view"); - - switch (type) - { - case READ: - if (byOthers) - { - return readLockOwners.size() > 1 || readLockOwners.size() == 1 && !readLockOwners.contains(view); - } - - return readLockOwners.contains(view); - - case WRITE: - if (byOthers) - { - return writeLockOwner != null && writeLockOwner != view; - } - - return writeLockOwner == view; - - case OPTION: - if (byOthers) - { - return writeOptionOwner != null && writeOptionOwner != view; - } - - return writeOptionOwner == view; - } - - return false; - } - - public boolean hasLock(org.eclipse.net4j.util.concurrent.IRWLockManager.LockType type) - { - switch (type) - { - case READ: - return readLockOwners.size() > 0; - - case WRITE: - return writeLockOwner != null; - - case OPTION: - return writeOptionOwner != null; - } - - return false; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder("LockState[target="); - builder.append(lockedObject); - - if (readLockOwners.size() > 0) - { - builder.append(", read="); - boolean first = true; - for (CONTEXT view : readLockOwners) - { - if (first) - { - first = false; - } - else - { - builder.append(", "); - } - - builder.append(view); - } - - builder.deleteCharAt(builder.length() - 1); - } - - if (writeLockOwner != null) - { - builder.append(", write="); - builder.append(writeLockOwner); - } - - if (writeOptionOwner != null) - { - builder.append(", option="); - builder.append(writeOptionOwner); - } - - builder.append(']'); - return builder.toString(); - } - - void lock(LockType type, CONTEXT context) - { - CheckUtil.checkArg(context, "context"); - switch (type) - { - case READ: - doReadLock(context); - return; - - case WRITE: - doWriteLock(context); - return; - - case OPTION: - doWriteOption(context); - return; - } - - throw new AssertionError("Unknown lock type " + type); - } - - boolean canLock(LockType type, CONTEXT context) - { - CheckUtil.checkArg(context, "context"); - switch (type) - { - case READ: - return canReadLock(context); - - case WRITE: - return canWriteLock(context); - - case OPTION: - return canWriteOption(context); - } - - throw new AssertionError("Unknown lock type " + type); - } - - boolean canUnlock(LockType type, CONTEXT context) - { - CheckUtil.checkArg(context, "context"); - switch (type) - { - case READ: - return canReadUnlock(context); - - case WRITE: - return canWriteUnlock(context); - - case OPTION: - return canWriteUnoption(context); - } - - throw new AssertionError("Unknown lock type " + type); - } - - void unlock(LockType type, CONTEXT context) - { - CheckUtil.checkArg(context, "context"); - switch (type) - { - case READ: - doReadUnlock(context); - return; - - case WRITE: - doWriteUnlock(context); - return; - - case OPTION: - doWriteUnoption(context); - return; - } - - throw new AssertionError("Unknown lock type " + type); - } - - void replaceContext(CONTEXT oldContext, CONTEXT newContext) - { - int readLocksOwnedByOldView = readLockOwners.getCounterFor(oldContext); - if (readLocksOwnedByOldView > 0) - { - for (int i = 0; i < readLocksOwnedByOldView; i++) - { - readLockOwners.remove(oldContext); - readLockOwners.add(newContext); - } - } - - if (ObjectUtil.equals(writeLockOwner, oldContext)) - { - writeLockOwner = newContext; - } - - if (ObjectUtil.equals(writeOptionOwner, oldContext)) - { - writeOptionOwner = newContext; - } - } - - boolean hasNoLocks() - { - return readLockOwners.isEmpty() && writeLockOwner == null && writeOptionOwner == null; - } - - boolean hasLocks(CONTEXT context) - { - return readLockOwners.contains(context) || writeLockOwner == context || writeOptionOwner == context; - } - - private boolean canReadLock(CONTEXT context) - { - if (writeLockOwner != null && writeLockOwner != context) - { - return false; - } - - return true; - } - - private void doReadLock(CONTEXT context) - { - readLockOwners.add(context); - } - - private boolean canWriteLock(CONTEXT context) - { - // If another context owns a writeLock, we can't write-lock - if (writeLockOwner != null && writeLockOwner != context) - { - return false; - } - - // If another context owns a writeOption, we can't write-lock - if (writeOptionOwner != null && writeOptionOwner != context) - { - return false; - } - - // If another context owns a readLock, we can't write-lock - if (readLockOwners.size() > 1) - { - return false; - } - - if (readLockOwners.size() == 1) - { - if (!readLockOwners.contains(context)) - { - return false; - } - } - - return true; - } - - private void doWriteLock(CONTEXT context) - { - writeLockOwner = context; - writeLockCounter++; - } - - private boolean canWriteOption(CONTEXT context) - { - if (writeOptionOwner != null && writeOptionOwner != context) - { - return false; - } - - if (writeLockOwner != null && writeLockOwner != context) - { - return false; - } - - return true; - } - - private void doWriteOption(CONTEXT context) - { - writeOptionOwner = context; - } - - private boolean canReadUnlock(CONTEXT context) - { - if (!readLockOwners.contains(context)) - { - return false; - } - - return true; - } - - private void doReadUnlock(CONTEXT context) - { - readLockOwners.remove(context); - } - - private boolean canWriteUnlock(CONTEXT context) - { - if (writeLockOwner != context) - { - return false; - } - - return true; - } - - private void doWriteUnlock(CONTEXT context) - { - writeLockCounter--; - if (writeLockCounter == 0) - { - writeLockOwner = null; - } - } - - private boolean canWriteUnoption(CONTEXT context) - { - if (writeOptionOwner != context) - { - return false; - } - - return true; - } - - private void doWriteUnoption(CONTEXT context) - { - writeOptionOwner = null; - } - - public Set<CONTEXT> getReadLockOwners() - { - return Collections.unmodifiableSet(readLockOwners); - } - - public CONTEXT getWriteLockOwner() - { - return writeLockOwner; - } - - public CONTEXT getWriteOptionOwner() - { - return writeOptionOwner; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Caspar De Groot - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.CheckUtil;
+import org.eclipse.net4j.util.ObjectUtil;
+import org.eclipse.net4j.util.collection.HashBag;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Keeps track of locks on objects. Locks are owned by contexts. A particular combination of locks and their owners, for
+ * a given object, is represented by instances of the {@link LockState} class. This class is also repsonsible for
+ * deciding whether or not a new lock can be granted, based on the locks already present.
+ *
+ * @author Caspar De Groot
+ * @since 3.2
+ */
+public class RWOLockManager<OBJECT, CONTEXT> extends Lifecycle implements IRWOLockManager<OBJECT, CONTEXT>
+{
+ private final List<LockState<OBJECT, CONTEXT>> EMPTY_RESULT = Collections.emptyList();
+
+ private final Map<OBJECT, LockState<OBJECT, CONTEXT>> objectToLockStateMap = createObjectToLocksMap();
+
+ /**
+ * A mapping of contexts (owners of locks) to the lock states that they are involved in. Here, an 'involvement' means
+ * that the context owns at least one lock on the object that the lock state is for. To determine exactly what kind of
+ * lock, the lock state object obtained from this map must be queried.
+ * <p>
+ * This map is a performance optimization to avoid having to scan all lock states.
+ */
+ private final Map<CONTEXT, Set<LockState<OBJECT, CONTEXT>>> contextToLockStates = createContextToLocksMap();
+
+ public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout)
+ throws InterruptedException
+ {
+ lock2(type, context, objectsToLock, timeout);
+ }
+
+ public List<LockState<OBJECT, CONTEXT>> lock2(LockType type, CONTEXT context,
+ Collection<? extends OBJECT> objectsToLock, long timeout) throws InterruptedException
+ {
+ if (objectsToLock.isEmpty())
+ {
+ return EMPTY_RESULT;
+ }
+
+ // Must come before the synchronized block!
+ long startTime = timeout == WAIT ? 0L : currentTimeMillis();
+
+ // Do not synchronize the entire method as it would corrupt the timeout!
+ synchronized (this)
+ {
+ int count = objectsToLock.size();
+ List<LockState<OBJECT, CONTEXT>> lockStates = new ArrayList<LockState<OBJECT, CONTEXT>>(count);
+
+ for (;;)
+ {
+ if (canLockInContext(type, context, objectsToLock, lockStates))
+ {
+ for (int i = 0; i < count; i++)
+ {
+ LockState<OBJECT, CONTEXT> lockState = lockStates.get(i);
+ lockState.lock(type, context);
+ addContextToLockStateMapping(context, lockState);
+ }
+
+ return lockStates;
+ }
+
+ wait(startTime, timeout);
+ }
+ }
+ }
+
+ public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException
+ {
+ // Do not synchronize the entire method as it would corrupt the timeout!
+ lock(type, context, Collections.singleton(objectToLock), timeout);
+ }
+
+ public synchronized void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock)
+ {
+ unlock2(type, context, objectsToUnlock);
+ }
+
+ public synchronized List<LockState<OBJECT, CONTEXT>> unlock2(LockType type, CONTEXT context,
+ Collection<? extends OBJECT> objectsToUnlock)
+ {
+ if (objectsToUnlock.isEmpty())
+ {
+ return EMPTY_RESULT;
+ }
+
+ List<LockState<OBJECT, CONTEXT>> lockStates = new LinkedList<LockState<OBJECT, CONTEXT>>();
+
+ Iterator<? extends OBJECT> it = objectsToUnlock.iterator();
+ while (it.hasNext())
+ {
+ OBJECT o = it.next();
+ LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(o);
+ if (lockState == null || !lockState.canUnlock(type, context))
+ {
+ throw new IllegalMonitorStateException();
+ }
+
+ lockStates.add(lockState);
+ }
+
+ for (LockState<OBJECT, CONTEXT> lockState : lockStates)
+ {
+ lockState.unlock(type, context);
+ if (!lockState.hasLocks(context))
+ {
+ removeLockStateForContext(context, lockState);
+ }
+
+ if (lockState.hasNoLocks())
+ {
+ objectToLockStateMap.remove(lockState.getLockedObject());
+ }
+ }
+
+ notifyAll();
+
+ return lockStates;
+ }
+
+ public synchronized void unlock(CONTEXT context)
+ {
+ unlock2(context);
+ }
+
+ public synchronized List<LockState<OBJECT, CONTEXT>> unlock2(CONTEXT context)
+ {
+ Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.get(context);
+ if (lockStates == null)
+ {
+ return EMPTY_RESULT;
+ }
+
+ List<OBJECT> objectsWithoutLocks = new LinkedList<OBJECT>();
+
+ for (LockState<OBJECT, CONTEXT> lockState : lockStates)
+ {
+ for (LockType lockType : LockType.values())
+ {
+ if (lockState.hasLock(lockType, context, false))
+ {
+ lockState.unlock(lockType, context);
+ }
+ }
+
+ if (lockState.hasNoLocks())
+ {
+ OBJECT o = lockState.getLockedObject();
+ objectsWithoutLocks.add(o);
+ }
+ }
+
+ contextToLockStates.remove(context);
+
+ // This must be done outside the above iteration, in order to avoid ConcurrentModEx
+ for (OBJECT o : objectsWithoutLocks)
+ {
+ objectToLockStateMap.remove(o);
+ }
+
+ notifyAll();
+
+ return toList(lockStates);
+ }
+
+ @SuppressWarnings("unchecked")
+ private List<LockState<OBJECT, CONTEXT>> toList(Set<LockState<OBJECT, CONTEXT>> lockStates)
+ {
+ if (lockStates instanceof List)
+ {
+ return (List<LockState<OBJECT, CONTEXT>>)lockStates;
+ }
+
+ List<LockState<OBJECT, CONTEXT>> list = new LinkedList<LockState<OBJECT, CONTEXT>>();
+ for (LockState<OBJECT, CONTEXT> lockState : lockStates)
+ {
+ list.add(lockState);
+ }
+
+ return list;
+ }
+
+ public synchronized boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock)
+ {
+ LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(objectToLock);
+ return lockState != null && lockState.hasLock(type, context, false);
+ }
+
+ public synchronized boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock)
+ {
+ LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(objectToLock);
+ return lockState != null && lockState.hasLock(type, context, true);
+ }
+
+ protected synchronized void changeContext(CONTEXT oldContext, CONTEXT newContext)
+ {
+ for (LockState<OBJECT, CONTEXT> lockState : objectToLockStateMap.values())
+ {
+ lockState.replaceContext(oldContext, newContext);
+ }
+
+ Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.remove(oldContext);
+ if (lockStates != null)
+ {
+ contextToLockStates.put(newContext, lockStates);
+ }
+ }
+
+ protected long currentTimeMillis()
+ {
+ return System.currentTimeMillis();
+ }
+
+ protected Map<OBJECT, LockState<OBJECT, CONTEXT>> createObjectToLocksMap()
+ {
+ return new HashMap<OBJECT, LockState<OBJECT, CONTEXT>>();
+ }
+
+ protected Map<CONTEXT, Set<LockState<OBJECT, CONTEXT>>> createContextToLocksMap()
+ {
+ return new HashMap<CONTEXT, Set<LockState<OBJECT, CONTEXT>>>();
+ }
+
+ /**
+ * All access to the returned map must be properly synchronized on this {@link RWOLockManager}.
+ */
+ protected final Map<OBJECT, LockState<OBJECT, CONTEXT>> getObjectToLocksMap()
+ {
+ return objectToLockStateMap;
+ }
+
+ /**
+ * All access to the returned map must be properly synchronized on this {@link RWOLockManager}.
+ */
+ protected final Map<CONTEXT, Set<LockState<OBJECT, CONTEXT>>> getContextToLocksMap()
+ {
+ return contextToLockStates;
+ }
+
+ public LockState<OBJECT, CONTEXT> getLockState(OBJECT key)
+ {
+ return objectToLockStateMap.get(key);
+ }
+
+ public synchronized void setLockState(OBJECT key, LockState<OBJECT, CONTEXT> lockState)
+ {
+ objectToLockStateMap.put(key, lockState);
+
+ for (CONTEXT readLockOwner : lockState.getReadLockOwners())
+ {
+ addContextToLockStateMapping(readLockOwner, lockState);
+ }
+ CONTEXT writeLockOwner = lockState.getWriteLockOwner();
+ if (writeLockOwner != null)
+ {
+ addContextToLockStateMapping(writeLockOwner, lockState);
+ }
+ CONTEXT writeOptionOwner = lockState.getWriteOptionOwner();
+ if (writeOptionOwner != null)
+ {
+ addContextToLockStateMapping(writeOptionOwner, lockState);
+ }
+ }
+
+ private LockState<OBJECT, CONTEXT> getOrCreateLockState(OBJECT o)
+ {
+ LockState<OBJECT, CONTEXT> lockState = objectToLockStateMap.get(o);
+ if (lockState == null)
+ {
+ lockState = new LockState<OBJECT, CONTEXT>(o);
+ objectToLockStateMap.put(o, lockState);
+ }
+
+ return lockState;
+ }
+
+ private boolean canLockInContext(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock,
+ List<LockState<OBJECT, CONTEXT>> lockStatesToFill)
+ {
+ Iterator<? extends OBJECT> it = objectsToLock.iterator();
+ for (int i = 0; i < objectsToLock.size(); i++)
+ {
+ OBJECT o = it.next();
+ LockState<OBJECT, CONTEXT> lockState = getOrCreateLockState(o);
+ if (!lockState.canLock(type, context))
+ {
+ return false;
+ }
+
+ lockStatesToFill.add(lockState);
+ }
+
+ return true;
+ }
+
+ private void addContextToLockStateMapping(CONTEXT context, LockState<OBJECT, CONTEXT> lockState)
+ {
+ Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.get(context);
+ if (lockStates == null)
+ {
+ lockStates = new HashSet<LockState<OBJECT, CONTEXT>>();
+ contextToLockStates.put(context, lockStates);
+ }
+
+ lockStates.add(lockState);
+ }
+
+ /**
+ * Removes a lockState from the set of all lockStates that the given context is involved in. If the lockState being
+ * removed is the last one for the given context, then the set becomes empty, and is therefore removed from the
+ * contextToLockStates mp.
+ */
+ private void removeLockStateForContext(CONTEXT context, LockState<OBJECT, CONTEXT> lockState)
+ {
+ Set<LockState<OBJECT, CONTEXT>> lockStates = contextToLockStates.get(context);
+ lockStates.remove(lockState);
+ if (lockStates.isEmpty())
+ {
+ contextToLockStates.remove(context);
+ }
+ }
+
+ private void wait(long startTime, long timeout) throws InterruptedException
+ {
+ if (timeout == WAIT)
+ {
+ wait();
+ }
+ else
+ {
+ long elapsedTime = currentTimeMillis() - startTime;
+ long waitTime = timeout - elapsedTime;
+ if (waitTime < 1)
+ {
+ throw new TimeoutRuntimeException("Could not lock objects within " + timeout + " milli seconds");
+ }
+
+ wait(waitTime);
+ }
+ }
+
+ /**
+ * Represents a combination of locks for one OBJECT. The different lock types are represented by the values of the
+ * enum {@link IRWLockManager.LockType}
+ * <p>
+ * The locking semantics established by this class are as follows:
+ * <li>a read lock prevents a write lock by another, but allows read locks by others and allows a write option by
+ * another, and is therefore <b>non-exclusive</b></li>
+ * <li>a write lock prevents read locks by others, a write lock by another, and a write option by another, and is
+ * therefore <b>exclusive</b></li>
+ * <li>a write option prevents write locks by others and a write option by another, but allows read locks by others,
+ * and is therefore <b>exclusive</b></li>
+ * <p>
+ *
+ * @author Caspar De Groot
+ * @since 3.2
+ */
+ public static class LockState<OBJECT, CONTEXT>
+ {
+ private final OBJECT lockedObject;
+
+ private final HashBag<CONTEXT> readLockOwners = new HashBag<CONTEXT>();
+
+ private CONTEXT writeLockOwner;
+
+ private CONTEXT writeOptionOwner;
+
+ private int writeLockCounter;
+
+ LockState(OBJECT lockedObject)
+ {
+ CheckUtil.checkArg(lockedObject, "lockedObject");
+ this.lockedObject = lockedObject;
+ }
+
+ public OBJECT getLockedObject()
+ {
+ return lockedObject;
+ }
+
+ public boolean hasLock(org.eclipse.net4j.util.concurrent.IRWLockManager.LockType type, CONTEXT view,
+ boolean byOthers)
+ {
+ CheckUtil.checkArg(view, "view");
+
+ switch (type)
+ {
+ case READ:
+ if (byOthers)
+ {
+ return readLockOwners.size() > 1 || readLockOwners.size() == 1 && !readLockOwners.contains(view);
+ }
+
+ return readLockOwners.contains(view);
+
+ case WRITE:
+ if (byOthers)
+ {
+ return writeLockOwner != null && writeLockOwner != view;
+ }
+
+ return writeLockOwner == view;
+
+ case OPTION:
+ if (byOthers)
+ {
+ return writeOptionOwner != null && writeOptionOwner != view;
+ }
+
+ return writeOptionOwner == view;
+ }
+
+ return false;
+ }
+
+ public boolean hasLock(org.eclipse.net4j.util.concurrent.IRWLockManager.LockType type)
+ {
+ switch (type)
+ {
+ case READ:
+ return readLockOwners.size() > 0;
+
+ case WRITE:
+ return writeLockOwner != null;
+
+ case OPTION:
+ return writeOptionOwner != null;
+ }
+
+ return false;
+ }
+
+ @Override
+ public String toString()
+ {
+ StringBuilder builder = new StringBuilder("LockState[target=");
+ builder.append(lockedObject);
+
+ if (readLockOwners.size() > 0)
+ {
+ builder.append(", read=");
+ boolean first = true;
+ for (CONTEXT view : readLockOwners)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ builder.append(", ");
+ }
+
+ builder.append(view);
+ }
+
+ builder.deleteCharAt(builder.length() - 1);
+ }
+
+ if (writeLockOwner != null)
+ {
+ builder.append(", write=");
+ builder.append(writeLockOwner);
+ }
+
+ if (writeOptionOwner != null)
+ {
+ builder.append(", option=");
+ builder.append(writeOptionOwner);
+ }
+
+ builder.append(']');
+ return builder.toString();
+ }
+
+ void lock(LockType type, CONTEXT context)
+ {
+ CheckUtil.checkArg(context, "context");
+ switch (type)
+ {
+ case READ:
+ doReadLock(context);
+ return;
+
+ case WRITE:
+ doWriteLock(context);
+ return;
+
+ case OPTION:
+ doWriteOption(context);
+ return;
+ }
+
+ throw new AssertionError("Unknown lock type " + type);
+ }
+
+ boolean canLock(LockType type, CONTEXT context)
+ {
+ CheckUtil.checkArg(context, "context");
+ switch (type)
+ {
+ case READ:
+ return canReadLock(context);
+
+ case WRITE:
+ return canWriteLock(context);
+
+ case OPTION:
+ return canWriteOption(context);
+ }
+
+ throw new AssertionError("Unknown lock type " + type);
+ }
+
+ boolean canUnlock(LockType type, CONTEXT context)
+ {
+ CheckUtil.checkArg(context, "context");
+ switch (type)
+ {
+ case READ:
+ return canReadUnlock(context);
+
+ case WRITE:
+ return canWriteUnlock(context);
+
+ case OPTION:
+ return canWriteUnoption(context);
+ }
+
+ throw new AssertionError("Unknown lock type " + type);
+ }
+
+ void unlock(LockType type, CONTEXT context)
+ {
+ CheckUtil.checkArg(context, "context");
+ switch (type)
+ {
+ case READ:
+ doReadUnlock(context);
+ return;
+
+ case WRITE:
+ doWriteUnlock(context);
+ return;
+
+ case OPTION:
+ doWriteUnoption(context);
+ return;
+ }
+
+ throw new AssertionError("Unknown lock type " + type);
+ }
+
+ void replaceContext(CONTEXT oldContext, CONTEXT newContext)
+ {
+ int readLocksOwnedByOldView = readLockOwners.getCounterFor(oldContext);
+ if (readLocksOwnedByOldView > 0)
+ {
+ for (int i = 0; i < readLocksOwnedByOldView; i++)
+ {
+ readLockOwners.remove(oldContext);
+ readLockOwners.add(newContext);
+ }
+ }
+
+ if (ObjectUtil.equals(writeLockOwner, oldContext))
+ {
+ writeLockOwner = newContext;
+ }
+
+ if (ObjectUtil.equals(writeOptionOwner, oldContext))
+ {
+ writeOptionOwner = newContext;
+ }
+ }
+
+ boolean hasNoLocks()
+ {
+ return readLockOwners.isEmpty() && writeLockOwner == null && writeOptionOwner == null;
+ }
+
+ boolean hasLocks(CONTEXT context)
+ {
+ return readLockOwners.contains(context) || writeLockOwner == context || writeOptionOwner == context;
+ }
+
+ private boolean canReadLock(CONTEXT context)
+ {
+ if (writeLockOwner != null && writeLockOwner != context)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void doReadLock(CONTEXT context)
+ {
+ readLockOwners.add(context);
+ }
+
+ private boolean canWriteLock(CONTEXT context)
+ {
+ // If another context owns a writeLock, we can't write-lock
+ if (writeLockOwner != null && writeLockOwner != context)
+ {
+ return false;
+ }
+
+ // If another context owns a writeOption, we can't write-lock
+ if (writeOptionOwner != null && writeOptionOwner != context)
+ {
+ return false;
+ }
+
+ // If another context owns a readLock, we can't write-lock
+ if (readLockOwners.size() > 1)
+ {
+ return false;
+ }
+
+ if (readLockOwners.size() == 1)
+ {
+ if (!readLockOwners.contains(context))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private void doWriteLock(CONTEXT context)
+ {
+ writeLockOwner = context;
+ writeLockCounter++;
+ }
+
+ private boolean canWriteOption(CONTEXT context)
+ {
+ if (writeOptionOwner != null && writeOptionOwner != context)
+ {
+ return false;
+ }
+
+ if (writeLockOwner != null && writeLockOwner != context)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void doWriteOption(CONTEXT context)
+ {
+ writeOptionOwner = context;
+ }
+
+ private boolean canReadUnlock(CONTEXT context)
+ {
+ if (!readLockOwners.contains(context))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void doReadUnlock(CONTEXT context)
+ {
+ readLockOwners.remove(context);
+ }
+
+ private boolean canWriteUnlock(CONTEXT context)
+ {
+ if (writeLockOwner != context)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void doWriteUnlock(CONTEXT context)
+ {
+ writeLockCounter--;
+ if (writeLockCounter == 0)
+ {
+ writeLockOwner = null;
+ }
+ }
+
+ private boolean canWriteUnoption(CONTEXT context)
+ {
+ if (writeOptionOwner != context)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ private void doWriteUnoption(CONTEXT context)
+ {
+ writeOptionOwner = null;
+ }
+
+ public Set<CONTEXT> getReadLockOwners()
+ {
+ return Collections.unmodifiableSet(readLockOwners);
+ }
+
+ public CONTEXT getWriteLockOwner()
+ {
+ return writeLockOwner;
+ }
+
+ public CONTEXT getWriteOptionOwner()
+ {
+ return writeOptionOwner;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java index 0d67d4a935..c723cd87b1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java @@ -1,98 +1,98 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.WrappedException; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * @author Eike Stepper - */ -public final class ResultSynchronizer<RESULT> implements ISynchronizer<RESULT> -{ - private RESULT result; - - private Object consumerLock = new Object(); - - private CountDownLatch producerLatch = new CountDownLatch(1); - - public ResultSynchronizer() - { - } - - public RESULT get(long timeout) - { - try - { - final long stop = System.currentTimeMillis() + timeout; - synchronized (consumerLock) - { - while (result == null) - { - try - { - final long remaining = stop - System.currentTimeMillis(); - if (remaining <= 0) - { - return null; - } - - consumerLock.wait(Math.min(remaining, 100L)); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } - - return result; - } - } - finally - { - producerLatch.countDown(); - } - } - - public void put(RESULT result) - { - synchronized (consumerLock) - { - this.result = result; - consumerLock.notifyAll(); - } - } - - public boolean put(RESULT result, long timeout) - { - synchronized (consumerLock) - { - this.result = result; - consumerLock.notifyAll(); - } - - try - { - if (!producerLatch.await(timeout, TimeUnit.MILLISECONDS)) - { - return false; - } - } - catch (InterruptedException ex) - { - return false; - } - - return true; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.WrappedException;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Eike Stepper
+ */
+public final class ResultSynchronizer<RESULT> implements ISynchronizer<RESULT>
+{
+ private RESULT result;
+
+ private Object consumerLock = new Object();
+
+ private CountDownLatch producerLatch = new CountDownLatch(1);
+
+ public ResultSynchronizer()
+ {
+ }
+
+ public RESULT get(long timeout)
+ {
+ try
+ {
+ final long stop = System.currentTimeMillis() + timeout;
+ synchronized (consumerLock)
+ {
+ while (result == null)
+ {
+ try
+ {
+ final long remaining = stop - System.currentTimeMillis();
+ if (remaining <= 0)
+ {
+ return null;
+ }
+
+ consumerLock.wait(Math.min(remaining, 100L));
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ return result;
+ }
+ }
+ finally
+ {
+ producerLatch.countDown();
+ }
+ }
+
+ public void put(RESULT result)
+ {
+ synchronized (consumerLock)
+ {
+ this.result = result;
+ consumerLock.notifyAll();
+ }
+ }
+
+ public boolean put(RESULT result, long timeout)
+ {
+ synchronized (consumerLock)
+ {
+ this.result = result;
+ consumerLock.notifyAll();
+ }
+
+ try
+ {
+ if (!producerLatch.await(timeout, TimeUnit.MILLISECONDS))
+ {
+ return false;
+ }
+ }
+ catch (InterruptedException ex)
+ {
+ return false;
+ }
+
+ return true;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java index 9862afc85b..7884e1296e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java @@ -1,512 +1,512 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * @author Eike Stepper - */ -public final class RoundRobinList<E> extends LinkedList<E> -{ - private static final long serialVersionUID = 1L; - - private ReadWriteLock lock = new ReentrantReadWriteLock(); - - private Iterator<E> it; - - public RoundRobinList() - { - } - - public RoundRobinList(Collection<? extends E> c) - { - super(c); - } - - public void executeReads(Runnable runnable) - { - try - { - lock.readLock().lock(); - runnable.run(); - } - finally - { - lock.readLock().unlock(); - } - } - - public void executeWrites(Runnable runnable) - { - try - { - lock.writeLock().lock(); - runnable.run(); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public void add(int index, E element) - { - try - { - lock.writeLock().lock(); - super.add(index, element); - it = null; - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public boolean add(E o) - { - try - { - lock.writeLock().lock(); - it = null; - return super.add(o); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public boolean addAll(Collection<? extends E> c) - { - try - { - lock.writeLock().lock(); - it = null; - return super.addAll(c); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public boolean addAll(int index, Collection<? extends E> c) - { - try - { - lock.writeLock().lock(); - it = null; - return super.addAll(index, c); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public void addFirst(E o) - { - try - { - lock.writeLock().lock(); - it = null; - super.addFirst(o); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public void addLast(E o) - { - try - { - lock.writeLock().lock(); - it = null; - super.addLast(o); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public void clear() - { - try - { - lock.writeLock().lock(); - it = null; - super.clear(); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public Object clone() - { - try - { - lock.readLock().lock(); - return super.clone(); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public boolean contains(Object o) - { - try - { - lock.readLock().lock(); - return super.contains(o); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public boolean containsAll(Collection<?> c) - { - try - { - lock.readLock().lock(); - return super.containsAll(c); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public E element() - { - try - { - lock.readLock().lock(); - if (isEmpty()) - { - return null; - } - - if (it == null || !it.hasNext()) - { - it = iterator(); - } - - return it.next(); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public E get(int index) - { - try - { - lock.readLock().lock(); - return super.get(index); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public E getFirst() - { - try - { - lock.readLock().lock(); - return super.getFirst(); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public E getLast() - { - try - { - lock.readLock().lock(); - return super.getLast(); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public int indexOf(Object o) - { - try - { - lock.readLock().lock(); - return super.indexOf(o); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public int lastIndexOf(Object o) - { - try - { - lock.readLock().lock(); - return super.lastIndexOf(o); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public boolean offer(E o) - { - try - { - lock.writeLock().lock(); - it = null; - return super.offer(o); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public E peek() - { - try - { - lock.readLock().lock(); - return super.peek(); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public E poll() - { - try - { - lock.writeLock().lock(); - it = null; - return super.poll(); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public E remove() - { - try - { - lock.writeLock().lock(); - it = null; - return super.remove(); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public E remove(int index) - { - try - { - lock.writeLock().lock(); - it = null; - return super.remove(index); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public boolean remove(Object o) - { - try - { - lock.writeLock().lock(); - it = null; - return super.remove(o); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public boolean removeAll(Collection<?> c) - { - try - { - lock.writeLock().lock(); - it = null; - return super.removeAll(c); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public E removeFirst() - { - try - { - lock.writeLock().lock(); - it = null; - return super.removeFirst(); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public E removeLast() - { - try - { - lock.writeLock().lock(); - it = null; - return super.removeLast(); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public boolean retainAll(Collection<?> c) - { - try - { - lock.writeLock().lock(); - it = null; - return super.retainAll(c); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public E set(int index, E element) - { - try - { - lock.writeLock().lock(); - it = null; - return super.set(index, element); - } - finally - { - lock.writeLock().unlock(); - } - } - - @Override - public List<E> subList(int fromIndex, int toIndex) - { - try - { - lock.readLock().lock(); - return super.subList(fromIndex, toIndex); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public Object[] toArray() - { - try - { - lock.readLock().lock(); - return super.toArray(); - } - finally - { - lock.readLock().unlock(); - } - } - - @Override - public <T> T[] toArray(T[] a) - { - try - { - lock.readLock().lock(); - return super.toArray(a); - } - finally - { - lock.readLock().unlock(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * @author Eike Stepper
+ */
+public final class RoundRobinList<E> extends LinkedList<E>
+{
+ private static final long serialVersionUID = 1L;
+
+ private ReadWriteLock lock = new ReentrantReadWriteLock();
+
+ private Iterator<E> it;
+
+ public RoundRobinList()
+ {
+ }
+
+ public RoundRobinList(Collection<? extends E> c)
+ {
+ super(c);
+ }
+
+ public void executeReads(Runnable runnable)
+ {
+ try
+ {
+ lock.readLock().lock();
+ runnable.run();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ public void executeWrites(Runnable runnable)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ runnable.run();
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public void add(int index, E element)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ super.add(index, element);
+ it = null;
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean add(E o)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.add(o);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean addAll(Collection<? extends E> c)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.addAll(c);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean addAll(int index, Collection<? extends E> c)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.addAll(index, c);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public void addFirst(E o)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ super.addFirst(o);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public void addLast(E o)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ super.addLast(o);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public void clear()
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ super.clear();
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public Object clone()
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.clone();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean contains(Object o)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.contains(o);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean containsAll(Collection<?> c)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.containsAll(c);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public E element()
+ {
+ try
+ {
+ lock.readLock().lock();
+ if (isEmpty())
+ {
+ return null;
+ }
+
+ if (it == null || !it.hasNext())
+ {
+ it = iterator();
+ }
+
+ return it.next();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public E get(int index)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.get(index);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public E getFirst()
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.getFirst();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public E getLast()
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.getLast();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public int indexOf(Object o)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.indexOf(o);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public int lastIndexOf(Object o)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.lastIndexOf(o);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean offer(E o)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.offer(o);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public E peek()
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.peek();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public E poll()
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.poll();
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public E remove()
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.remove();
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public E remove(int index)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.remove(index);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean remove(Object o)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.remove(o);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean removeAll(Collection<?> c)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.removeAll(c);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public E removeFirst()
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.removeFirst();
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public E removeLast()
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.removeLast();
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean retainAll(Collection<?> c)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.retainAll(c);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public E set(int index, E element)
+ {
+ try
+ {
+ lock.writeLock().lock();
+ it = null;
+ return super.set(index, element);
+ }
+ finally
+ {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public List<E> subList(int fromIndex, int toIndex)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.subList(fromIndex, toIndex);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public Object[] toArray()
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.toArray();
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public <T> T[] toArray(T[] a)
+ {
+ try
+ {
+ lock.readLock().lock();
+ return super.toArray(a);
+ }
+ finally
+ {
+ lock.readLock().unlock();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java index adcf7ef34d..339ef4053f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java @@ -1,63 +1,63 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -/** - * @author Eike Stepper - */ -public class Sleeper -{ - private static final int DEFAULT_INTERVAL = 10; - - private long start; - - private int interval; - - public Sleeper() - { - this(DEFAULT_INTERVAL); - } - - public Sleeper(int interval) - { - this.interval = interval; - restart(); - } - - public int getInterval() - { - return interval; - } - - public long getStart() - { - return start; - } - - public void restart() - { - start = System.currentTimeMillis(); - } - - public void sleep(long millis) - { - while (System.currentTimeMillis() < start + millis) - { - ConcurrencyUtil.sleep(interval); - } - } - - public void resleep(long millis) - { - restart(); - sleep(millis); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * @author Eike Stepper
+ */
+public class Sleeper
+{
+ private static final int DEFAULT_INTERVAL = 10;
+
+ private long start;
+
+ private int interval;
+
+ public Sleeper()
+ {
+ this(DEFAULT_INTERVAL);
+ }
+
+ public Sleeper(int interval)
+ {
+ this.interval = interval;
+ restart();
+ }
+
+ public int getInterval()
+ {
+ return interval;
+ }
+
+ public long getStart()
+ {
+ return start;
+ }
+
+ public void restart()
+ {
+ start = System.currentTimeMillis();
+ }
+
+ public void sleep(long millis)
+ {
+ while (System.currentTimeMillis() < start + millis)
+ {
+ ConcurrencyUtil.sleep(interval);
+ }
+ }
+
+ public void resleep(long millis)
+ {
+ restart();
+ sleep(millis);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java index 75dc60cfad..dcd2a5fb5e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java @@ -1,126 +1,126 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * @author Eike Stepper - */ -public class SynchronizingCorrelator<CORRELATION, RESULT> implements ICorrelator<CORRELATION, ISynchronizer<RESULT>> -{ - private ConcurrentMap<CORRELATION, ISynchronizer<RESULT>> map = new ConcurrentHashMap<CORRELATION, ISynchronizer<RESULT>>( - 0); - - /** - * @since 3.0 - */ - public ISynchronizer<RESULT> getSynchronizer(CORRELATION correlation) - { - return map.get(correlation); - } - - public boolean isCorrelated(CORRELATION correlation) - { - return map.containsKey(correlation); - } - - public ISynchronizer<RESULT> correlate(CORRELATION correlation) - { - ISynchronizer<RESULT> synchronizer = map.get(correlation); - if (synchronizer == null) - { - synchronizer = createSynchronizer(correlation); - map.put(correlation, synchronizer); - } - - return synchronizer; - } - - public ISynchronizer<RESULT> correlateUnique(CORRELATION correlation) - { - ISynchronizer<RESULT> synchronizer = createSynchronizer(correlation); - if (map.putIfAbsent(correlation, synchronizer) != null) - { - throw new IllegalStateException("Already correlated: " + correlation); //$NON-NLS-1$ - } - - return synchronizer; - } - - public ISynchronizer<RESULT> uncorrelate(CORRELATION correlation) - { - return map.remove(correlation); - } - - public RESULT get(CORRELATION correlation, long timeout) - { - return correlate(correlation).get(timeout); - } - - public void put(CORRELATION correlation, RESULT result) - { - correlate(correlation).put(result); - } - - /** - * @since 3.0 - */ - public boolean putIfCorrelated(CORRELATION correlation, RESULT result) - { - ISynchronizer<RESULT> synchronizer = getSynchronizer(correlation); - if (synchronizer != null) - { - synchronizer.put(result); - return true; - } - - return false; - } - - public boolean put(CORRELATION correlation, RESULT result, long timeout) - { - return correlate(correlation).put(result, timeout); - } - - protected ISynchronizer<RESULT> createSynchronizer(final CORRELATION correlation) - { - // TODO Make top level class - return new ISynchronizer<RESULT>() - { - private ISynchronizer<RESULT> delegate = new ResultSynchronizer<RESULT>(); - - public RESULT get(long timeout) - { - RESULT result = delegate.get(timeout); - uncorrelate(correlation); - return result; - } - - public void put(RESULT result) - { - delegate.put(result); - } - - public boolean put(RESULT result, long timeout) - { - return delegate.put(result, timeout); - } - }; - } - - @Override - public String toString() - { - return "SynchronizingCorrelator" + map; //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * @author Eike Stepper
+ */
+public class SynchronizingCorrelator<CORRELATION, RESULT> implements ICorrelator<CORRELATION, ISynchronizer<RESULT>>
+{
+ private ConcurrentMap<CORRELATION, ISynchronizer<RESULT>> map = new ConcurrentHashMap<CORRELATION, ISynchronizer<RESULT>>(
+ 0);
+
+ /**
+ * @since 3.0
+ */
+ public ISynchronizer<RESULT> getSynchronizer(CORRELATION correlation)
+ {
+ return map.get(correlation);
+ }
+
+ public boolean isCorrelated(CORRELATION correlation)
+ {
+ return map.containsKey(correlation);
+ }
+
+ public ISynchronizer<RESULT> correlate(CORRELATION correlation)
+ {
+ ISynchronizer<RESULT> synchronizer = map.get(correlation);
+ if (synchronizer == null)
+ {
+ synchronizer = createSynchronizer(correlation);
+ map.put(correlation, synchronizer);
+ }
+
+ return synchronizer;
+ }
+
+ public ISynchronizer<RESULT> correlateUnique(CORRELATION correlation)
+ {
+ ISynchronizer<RESULT> synchronizer = createSynchronizer(correlation);
+ if (map.putIfAbsent(correlation, synchronizer) != null)
+ {
+ throw new IllegalStateException("Already correlated: " + correlation); //$NON-NLS-1$
+ }
+
+ return synchronizer;
+ }
+
+ public ISynchronizer<RESULT> uncorrelate(CORRELATION correlation)
+ {
+ return map.remove(correlation);
+ }
+
+ public RESULT get(CORRELATION correlation, long timeout)
+ {
+ return correlate(correlation).get(timeout);
+ }
+
+ public void put(CORRELATION correlation, RESULT result)
+ {
+ correlate(correlation).put(result);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public boolean putIfCorrelated(CORRELATION correlation, RESULT result)
+ {
+ ISynchronizer<RESULT> synchronizer = getSynchronizer(correlation);
+ if (synchronizer != null)
+ {
+ synchronizer.put(result);
+ return true;
+ }
+
+ return false;
+ }
+
+ public boolean put(CORRELATION correlation, RESULT result, long timeout)
+ {
+ return correlate(correlation).put(result, timeout);
+ }
+
+ protected ISynchronizer<RESULT> createSynchronizer(final CORRELATION correlation)
+ {
+ // TODO Make top level class
+ return new ISynchronizer<RESULT>()
+ {
+ private ISynchronizer<RESULT> delegate = new ResultSynchronizer<RESULT>();
+
+ public RESULT get(long timeout)
+ {
+ RESULT result = delegate.get(timeout);
+ uncorrelate(correlation);
+ return result;
+ }
+
+ public void put(RESULT result)
+ {
+ delegate.put(result);
+ }
+
+ public boolean put(RESULT result, long timeout)
+ {
+ return delegate.put(result, timeout);
+ }
+ };
+ }
+
+ @Override
+ public String toString()
+ {
+ return "SynchronizingCorrelator" + map; //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java index 3ada0d1a0e..2427a92378 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java @@ -1,37 +1,37 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -/** - * @author Eike Stepper - */ -public class SynchronousWorkSerializer implements IWorkSerializer -{ - public SynchronousWorkSerializer() - { - } - - public boolean addWork(Runnable work) - { - work.run(); - return true; - } - - public void dispose() - { - } - - @Override - public String toString() - { - return SynchronousWorkSerializer.class.getSimpleName(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+/**
+ * @author Eike Stepper
+ */
+public class SynchronousWorkSerializer implements IWorkSerializer
+{
+ public SynchronousWorkSerializer()
+ {
+ }
+
+ public boolean addWork(Runnable work)
+ {
+ work.run();
+ return true;
+ }
+
+ public void dispose()
+ {
+ }
+
+ @Override
+ public String toString()
+ {
+ return SynchronousWorkSerializer.class.getSimpleName();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java index 53899af28d..5be51f9c17 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java @@ -1,50 +1,50 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import java.util.concurrent.TimeoutException; - -/** - * @author Eike Stepper - */ -public class TimeoutRuntimeException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public TimeoutRuntimeException() - { - } - - public TimeoutRuntimeException(String message) - { - super(message); - } - - public TimeoutRuntimeException(Throwable cause) - { - super(cause); - } - - public TimeoutRuntimeException(String message, Throwable cause) - { - super(message, cause); - } - - /** - * @since 3.0 - */ - public TimeoutException createTimeoutException() - { - TimeoutException timeoutException = new TimeoutException(getMessage()); - timeoutException.initCause(this); - return timeoutException; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import java.util.concurrent.TimeoutException;
+
+/**
+ * @author Eike Stepper
+ */
+public class TimeoutRuntimeException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public TimeoutRuntimeException()
+ {
+ }
+
+ public TimeoutRuntimeException(String message)
+ {
+ super(message);
+ }
+
+ public TimeoutRuntimeException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public TimeoutRuntimeException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public TimeoutException createTimeoutException()
+ {
+ TimeoutException timeoutException = new TimeoutException(getMessage());
+ timeoutException.initCause(this);
+ return timeoutException;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java index e9997c8680..2787ac8158 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java @@ -1,113 +1,113 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.internal.util.bundle.OM; - -import java.util.Timer; -import java.util.TimerTask; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class Timeouter -{ - private Timer timer; - - private long timeout; - - private TimerTask timeoutTask; - - private volatile long touched; - - public Timeouter(Timer timer, long timeout) - { - this.timer = timer; - this.timeout = timeout; - - touch(); - scheduleTimeout(); - } - - public long getTimeout() - { - return timeout; - } - - public void setTimeout(long timeout) - { - this.timeout = timeout; - } - - public void touch() - { - touched = System.currentTimeMillis(); - } - - public void dispose() - { - if (timeoutTask != null) - { - TimerTask task = timeoutTask; - timeoutTask = null; - task.cancel(); - } - } - - protected boolean isDisposed() - { - return timeoutTask == null; - } - - protected abstract void handleTimeout(long untouched); - - private void scheduleTimeout() - { - timeoutTask = new TimerTask() - { - @Override - public void run() - { - try - { - if (!isDisposed()) - { - long untouched = System.currentTimeMillis() - touched; - if (untouched > timeout) - { - timeoutTask = null; - handleTimeout(untouched); - } - else - { - scheduleTimeout(); - } - } - } - catch (Exception ex) - { - OM.LOG.error("TimeouterTask failed", ex); - } - } - }; - - try - { - long delay = Math.max(timeout - (System.currentTimeMillis() - touched), 0L); - timer.schedule(timeoutTask, delay); - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class Timeouter
+{
+ private Timer timer;
+
+ private long timeout;
+
+ private TimerTask timeoutTask;
+
+ private volatile long touched;
+
+ public Timeouter(Timer timer, long timeout)
+ {
+ this.timer = timer;
+ this.timeout = timeout;
+
+ touch();
+ scheduleTimeout();
+ }
+
+ public long getTimeout()
+ {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout)
+ {
+ this.timeout = timeout;
+ }
+
+ public void touch()
+ {
+ touched = System.currentTimeMillis();
+ }
+
+ public void dispose()
+ {
+ if (timeoutTask != null)
+ {
+ TimerTask task = timeoutTask;
+ timeoutTask = null;
+ task.cancel();
+ }
+ }
+
+ protected boolean isDisposed()
+ {
+ return timeoutTask == null;
+ }
+
+ protected abstract void handleTimeout(long untouched);
+
+ private void scheduleTimeout()
+ {
+ timeoutTask = new TimerTask()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ if (!isDisposed())
+ {
+ long untouched = System.currentTimeMillis() - touched;
+ if (untouched > timeout)
+ {
+ timeoutTask = null;
+ handleTimeout(untouched);
+ }
+ else
+ {
+ scheduleTimeout();
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error("TimeouterTask failed", ex);
+ }
+ }
+ };
+
+ try
+ {
+ long delay = Math.max(timeout - (System.currentTimeMillis() - touched), 0L);
+ timer.schedule(timeoutTask, delay);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java index 3415f2efd5..04c09fb86f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java @@ -1,134 +1,134 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.util.container.IManagedContainer; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.factory.Factory; -import org.eclipse.net4j.util.factory.ProductCreationException; -import org.eclipse.net4j.util.lifecycle.ILifecycle; -import org.eclipse.net4j.util.lifecycle.Lifecycle; -import org.eclipse.net4j.util.lifecycle.LifecycleException; -import org.eclipse.net4j.util.lifecycle.LifecycleState; - -import java.util.Timer; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class TimerLifecycle extends Timer implements ILifecycle -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.timers"; - - private Lifecycle delegate = new Lifecycle() - { - @Override - protected void doDeactivate() throws Exception - { - cancel(); - } - }; - - public TimerLifecycle() - { - activate(); - } - - public TimerLifecycle(boolean isDaemon) - { - super(isDaemon); - activate(); - } - - public TimerLifecycle(String name) - { - super(name); - activate(); - } - - public TimerLifecycle(String name, boolean isDaemon) - { - super(name, isDaemon); - activate(); - } - - /** - * @since 3.0 - */ - public final LifecycleState getLifecycleState() - { - return delegate.getLifecycleState(); - } - - public final boolean isActive() - { - return delegate.isActive(); - } - - public void addListener(IListener listener) - { - delegate.addListener(listener); - } - - public void removeListener(IListener listener) - { - delegate.removeListener(listener); - } - - public IListener[] getListeners() - { - return delegate.getListeners(); - } - - public boolean hasListeners() - { - return delegate.hasListeners(); - } - - public final void activate() throws LifecycleException - { - delegate.activate(); - } - - public final Exception deactivate() - { - return delegate.deactivate(); - } - - /** - * @author Eike Stepper - */ - public static class DaemonFactory extends Factory - { - public static final String TYPE = "daemon"; - - public DaemonFactory() - { - super(PRODUCT_GROUP, TYPE); - } - - public Object create(String name) throws ProductCreationException - { - if (name == null) - { - return new TimerLifecycle(true); - } - - return new TimerLifecycle(name, true); - } - - public static TimerLifecycle getTimer(IManagedContainer container, String name) - { - return (TimerLifecycle)container.getElement(PRODUCT_GROUP, TYPE, name); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.util.container.IManagedContainer;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.factory.Factory;
+import org.eclipse.net4j.util.factory.ProductCreationException;
+import org.eclipse.net4j.util.lifecycle.ILifecycle;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+import org.eclipse.net4j.util.lifecycle.LifecycleException;
+import org.eclipse.net4j.util.lifecycle.LifecycleState;
+
+import java.util.Timer;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class TimerLifecycle extends Timer implements ILifecycle
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.timers";
+
+ private Lifecycle delegate = new Lifecycle()
+ {
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ cancel();
+ }
+ };
+
+ public TimerLifecycle()
+ {
+ activate();
+ }
+
+ public TimerLifecycle(boolean isDaemon)
+ {
+ super(isDaemon);
+ activate();
+ }
+
+ public TimerLifecycle(String name)
+ {
+ super(name);
+ activate();
+ }
+
+ public TimerLifecycle(String name, boolean isDaemon)
+ {
+ super(name, isDaemon);
+ activate();
+ }
+
+ /**
+ * @since 3.0
+ */
+ public final LifecycleState getLifecycleState()
+ {
+ return delegate.getLifecycleState();
+ }
+
+ public final boolean isActive()
+ {
+ return delegate.isActive();
+ }
+
+ public void addListener(IListener listener)
+ {
+ delegate.addListener(listener);
+ }
+
+ public void removeListener(IListener listener)
+ {
+ delegate.removeListener(listener);
+ }
+
+ public IListener[] getListeners()
+ {
+ return delegate.getListeners();
+ }
+
+ public boolean hasListeners()
+ {
+ return delegate.hasListeners();
+ }
+
+ public final void activate() throws LifecycleException
+ {
+ delegate.activate();
+ }
+
+ public final Exception deactivate()
+ {
+ return delegate.deactivate();
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class DaemonFactory extends Factory
+ {
+ public static final String TYPE = "daemon";
+
+ public DaemonFactory()
+ {
+ super(PRODUCT_GROUP, TYPE);
+ }
+
+ public Object create(String name) throws ProductCreationException
+ {
+ if (name == null)
+ {
+ return new TimerLifecycle(true);
+ }
+
+ return new TimerLifecycle(name, true);
+ }
+
+ public static TimerLifecycle getTimer(IManagedContainer container, String name)
+ {
+ return (TimerLifecycle)container.getElement(PRODUCT_GROUP, TYPE, name);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java index 90f4415aa2..a0bfe7322b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java @@ -1,312 +1,312 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.concurrent; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.IErrorHandler; -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class Worker extends Lifecycle -{ - public static final int DEFAULT_TIMEOUT = 10000; - - /** - * @since 3.0 - */ - public static final IErrorHandler DEFAULT_ERROR_HANDLER = new IErrorHandler() - { - public void handleError(Throwable t) - { - OM.LOG.error(t); - } - }; - - private static IErrorHandler globalErrorHandler = DEFAULT_ERROR_HANDLER; - - private boolean daemon; - - private long activationTimeout = DEFAULT_TIMEOUT; - - private long deactivationTimeout = DEFAULT_TIMEOUT; - - @ExcludeFromDump - private transient CountDownLatch activationLatch; - - @ExcludeFromDump - private transient WorkerThread workerThread; - - public Worker() - { - } - - public boolean isDaemon() - { - return daemon; - } - - public void setDaemon(boolean daemon) - { - this.daemon = daemon; - } - - public long getActivationTimeout() - { - return activationTimeout; - } - - public void setActivationTimeout(long activationTimeout) - { - this.activationTimeout = activationTimeout; - } - - public long getDeactivationTimeout() - { - return deactivationTimeout; - } - - public void setDeactivationTimeout(long deactivationTimeout) - { - this.deactivationTimeout = deactivationTimeout; - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - activationLatch = new CountDownLatch(1); - String threadName = getThreadName(); - workerThread = threadName == null ? new WorkerThread() : new WorkerThread(threadName); - workerThread.start(); - if (!activationLatch.await(activationTimeout, TimeUnit.MILLISECONDS)) - { - try - { - workerThread.stopRunning(); - workerThread.interrupt(); - } - catch (RuntimeException ex) - { - OM.LOG.warn(ex); - } - - throw new TimeoutException("Worker thread activation timed out after " + activationTimeout + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - @Override - protected void doDeactivate() throws Exception - { - try - { - workerThread.stopRunning(); - workerThread.interrupt(); - workerThread.join(deactivationTimeout); - } - catch (RuntimeException ex) - { - OM.LOG.warn(ex); - } - - super.doDeactivate(); - } - - protected String getThreadName() - { - return null; - } - - /** - * @since 3.1 - */ - protected void handleError(Exception ex) - { - try - { - if (globalErrorHandler != null) - { - globalErrorHandler.handleError(ex); - } - } - catch (Exception ex1) - { - OM.LOG.error(ex1); - } - } - - protected abstract void work(WorkContext context) throws Exception; - - /** - * @since 3.0 - */ - public static IErrorHandler getGlobalErrorHandler() - { - return globalErrorHandler; - } - - /** - * @since 3.0 - */ - public static IErrorHandler setGlobalErrorHandler(IErrorHandler globalErrorHandler) - { - IErrorHandler oldHandler = Worker.globalErrorHandler; - Worker.globalErrorHandler = globalErrorHandler; - return oldHandler; - } - - /** - * @author Eike Stepper - */ - private final class WorkerThread extends Thread - { - private boolean running = true; - - public WorkerThread() - { - setDaemon(daemon); - } - - public WorkerThread(String threadName) - { - super(threadName); - setDaemon(daemon); - } - - public void stopRunning() - { - running = false; - } - - @Override - public void run() - { - WorkContext context = new WorkContext(); - activationLatch.countDown(); - while (running && !isInterrupted()) - { - try - { - context.increaseCount(); - work(context); - } - catch (NextWork nextWork) - { - try - { - nextWork.pause(); - } - catch (InterruptedException ex) - { - break; - } - } - catch (Terminate terminate) - { - break; - } - catch (InterruptedException ex) - { - break; - } - catch (Exception ex) - { - handleError(ex); - } - } - - deactivate(); - } - } - - /** - * @author Eike Stepper - */ - public class WorkContext - { - private long count; - - public WorkContext() - { - } - - public long getCount() - { - return count; - } - - public void nextWork() - { - throw new NextWork(); - } - - public void nextWork(long pauseMillis) - { - throw new NextWork(pauseMillis); - } - - public void terminate() - { - throw new Terminate(); - } - - private void increaseCount() - { - ++count; - } - } - - /** - * @author Eike Stepper - */ - private static final class NextWork extends RuntimeException - { - private static final long serialVersionUID = 1L; - - private long pauseMillis; - - public NextWork() - { - } - - public NextWork(long pauseMillis) - { - this.pauseMillis = pauseMillis; - } - - public void pause() throws InterruptedException - { - if (pauseMillis > 0) - { - Thread.sleep(pauseMillis); - } - } - } - - /** - * @author Eike Stepper - */ - private static final class Terminate extends RuntimeException - { - private static final long serialVersionUID = 1L; - - public Terminate() - { - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.concurrent;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.IErrorHandler;
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class Worker extends Lifecycle
+{
+ public static final int DEFAULT_TIMEOUT = 10000;
+
+ /**
+ * @since 3.0
+ */
+ public static final IErrorHandler DEFAULT_ERROR_HANDLER = new IErrorHandler()
+ {
+ public void handleError(Throwable t)
+ {
+ OM.LOG.error(t);
+ }
+ };
+
+ private static IErrorHandler globalErrorHandler = DEFAULT_ERROR_HANDLER;
+
+ private boolean daemon;
+
+ private long activationTimeout = DEFAULT_TIMEOUT;
+
+ private long deactivationTimeout = DEFAULT_TIMEOUT;
+
+ @ExcludeFromDump
+ private transient CountDownLatch activationLatch;
+
+ @ExcludeFromDump
+ private transient WorkerThread workerThread;
+
+ public Worker()
+ {
+ }
+
+ public boolean isDaemon()
+ {
+ return daemon;
+ }
+
+ public void setDaemon(boolean daemon)
+ {
+ this.daemon = daemon;
+ }
+
+ public long getActivationTimeout()
+ {
+ return activationTimeout;
+ }
+
+ public void setActivationTimeout(long activationTimeout)
+ {
+ this.activationTimeout = activationTimeout;
+ }
+
+ public long getDeactivationTimeout()
+ {
+ return deactivationTimeout;
+ }
+
+ public void setDeactivationTimeout(long deactivationTimeout)
+ {
+ this.deactivationTimeout = deactivationTimeout;
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ activationLatch = new CountDownLatch(1);
+ String threadName = getThreadName();
+ workerThread = threadName == null ? new WorkerThread() : new WorkerThread(threadName);
+ workerThread.start();
+ if (!activationLatch.await(activationTimeout, TimeUnit.MILLISECONDS))
+ {
+ try
+ {
+ workerThread.stopRunning();
+ workerThread.interrupt();
+ }
+ catch (RuntimeException ex)
+ {
+ OM.LOG.warn(ex);
+ }
+
+ throw new TimeoutException("Worker thread activation timed out after " + activationTimeout + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ try
+ {
+ workerThread.stopRunning();
+ workerThread.interrupt();
+ workerThread.join(deactivationTimeout);
+ }
+ catch (RuntimeException ex)
+ {
+ OM.LOG.warn(ex);
+ }
+
+ super.doDeactivate();
+ }
+
+ protected String getThreadName()
+ {
+ return null;
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected void handleError(Exception ex)
+ {
+ try
+ {
+ if (globalErrorHandler != null)
+ {
+ globalErrorHandler.handleError(ex);
+ }
+ }
+ catch (Exception ex1)
+ {
+ OM.LOG.error(ex1);
+ }
+ }
+
+ protected abstract void work(WorkContext context) throws Exception;
+
+ /**
+ * @since 3.0
+ */
+ public static IErrorHandler getGlobalErrorHandler()
+ {
+ return globalErrorHandler;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static IErrorHandler setGlobalErrorHandler(IErrorHandler globalErrorHandler)
+ {
+ IErrorHandler oldHandler = Worker.globalErrorHandler;
+ Worker.globalErrorHandler = globalErrorHandler;
+ return oldHandler;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class WorkerThread extends Thread
+ {
+ private boolean running = true;
+
+ public WorkerThread()
+ {
+ setDaemon(daemon);
+ }
+
+ public WorkerThread(String threadName)
+ {
+ super(threadName);
+ setDaemon(daemon);
+ }
+
+ public void stopRunning()
+ {
+ running = false;
+ }
+
+ @Override
+ public void run()
+ {
+ WorkContext context = new WorkContext();
+ activationLatch.countDown();
+ while (running && !isInterrupted())
+ {
+ try
+ {
+ context.increaseCount();
+ work(context);
+ }
+ catch (NextWork nextWork)
+ {
+ try
+ {
+ nextWork.pause();
+ }
+ catch (InterruptedException ex)
+ {
+ break;
+ }
+ }
+ catch (Terminate terminate)
+ {
+ break;
+ }
+ catch (InterruptedException ex)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ handleError(ex);
+ }
+ }
+
+ deactivate();
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public class WorkContext
+ {
+ private long count;
+
+ public WorkContext()
+ {
+ }
+
+ public long getCount()
+ {
+ return count;
+ }
+
+ public void nextWork()
+ {
+ throw new NextWork();
+ }
+
+ public void nextWork(long pauseMillis)
+ {
+ throw new NextWork(pauseMillis);
+ }
+
+ public void terminate()
+ {
+ throw new Terminate();
+ }
+
+ private void increaseCount()
+ {
+ ++count;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class NextWork extends RuntimeException
+ {
+ private static final long serialVersionUID = 1L;
+
+ private long pauseMillis;
+
+ public NextWork()
+ {
+ }
+
+ public NextWork(long pauseMillis)
+ {
+ this.pauseMillis = pauseMillis;
+ }
+
+ public void pause() throws InterruptedException
+ {
+ if (pauseMillis > 0)
+ {
+ Thread.sleep(pauseMillis);
+ }
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class Terminate extends RuntimeException
+ {
+ private static final long serialVersionUID = 1L;
+
+ public Terminate()
+ {
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java index 9aa535b8e1..9392ff754f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/Container.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/Container.java index 64f55c03da..6aae78cea8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/Container.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/Container.java @@ -1,115 +1,115 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.container.IContainerDelta.Kind; -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.lifecycle.ILifecycle; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.util.List; - -/** - * A default {@link IContainer container} implementation with a {@link ILifecycle lifecycle}. - * - * @author Eike Stepper - */ -public abstract class Container<E> extends Lifecycle implements IContainer<E> -{ - public Container() - { - } - - public boolean isEmpty() - { - if (!isActive()) - { - return true; - } - - E[] elements = getElements(); - return elements == null || elements.length == 0; - } - - @Override - public void fireEvent(IEvent event) - { - if (event instanceof IContainerEvent<?>) - { - if (((IContainerEvent<?>)event).isEmpty()) - { - return; - } - } - - super.fireEvent(event); - } - - public void fireContainerEvent(E element, Kind kind) - { - fireEvent(newContainerEvent(element, kind)); - } - - public void fireElementAddedEvent(E element) - { - fireContainerEvent(element, IContainerDelta.Kind.ADDED); - } - - public void fireElementRemovedEvent(E element) - { - fireContainerEvent(element, IContainerDelta.Kind.REMOVED); - } - - /** - * @since 2.0 - */ - public void fireContainerEvent(E[] elements, Kind kind) - { - ContainerEvent<E> event = new ContainerEvent<E>(this); - for (E element : elements) - { - event.addDelta(element, kind); - } - - fireEvent(event); - } - - /** - * @since 2.0 - */ - public void fireElementsAddedEvent(E[] elements) - { - fireContainerEvent(elements, IContainerDelta.Kind.ADDED); - } - - /** - * @since 2.0 - */ - public void fireElementsRemovedEvent(E[] elements) - { - fireContainerEvent(elements, IContainerDelta.Kind.REMOVED); - } - - public void fireContainerEvent(List<IContainerDelta<E>> deltas) - { - fireEvent(new ContainerEvent<E>(this, deltas)); - } - - protected SingleDeltaContainerEvent<E> newContainerEvent(E element, IContainerDelta.Kind kind) - { - return new SingleDeltaContainerEvent<E>(this, element, kind); - } - - protected ContainerEvent<E> newContainerEvent() - { - return new ContainerEvent<E>(this); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.container.IContainerDelta.Kind;
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.lifecycle.ILifecycle;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.util.List;
+
+/**
+ * A default {@link IContainer container} implementation with a {@link ILifecycle lifecycle}.
+ *
+ * @author Eike Stepper
+ */
+public abstract class Container<E> extends Lifecycle implements IContainer<E>
+{
+ public Container()
+ {
+ }
+
+ public boolean isEmpty()
+ {
+ if (!isActive())
+ {
+ return true;
+ }
+
+ E[] elements = getElements();
+ return elements == null || elements.length == 0;
+ }
+
+ @Override
+ public void fireEvent(IEvent event)
+ {
+ if (event instanceof IContainerEvent<?>)
+ {
+ if (((IContainerEvent<?>)event).isEmpty())
+ {
+ return;
+ }
+ }
+
+ super.fireEvent(event);
+ }
+
+ public void fireContainerEvent(E element, Kind kind)
+ {
+ fireEvent(newContainerEvent(element, kind));
+ }
+
+ public void fireElementAddedEvent(E element)
+ {
+ fireContainerEvent(element, IContainerDelta.Kind.ADDED);
+ }
+
+ public void fireElementRemovedEvent(E element)
+ {
+ fireContainerEvent(element, IContainerDelta.Kind.REMOVED);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void fireContainerEvent(E[] elements, Kind kind)
+ {
+ ContainerEvent<E> event = new ContainerEvent<E>(this);
+ for (E element : elements)
+ {
+ event.addDelta(element, kind);
+ }
+
+ fireEvent(event);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void fireElementsAddedEvent(E[] elements)
+ {
+ fireContainerEvent(elements, IContainerDelta.Kind.ADDED);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void fireElementsRemovedEvent(E[] elements)
+ {
+ fireContainerEvent(elements, IContainerDelta.Kind.REMOVED);
+ }
+
+ public void fireContainerEvent(List<IContainerDelta<E>> deltas)
+ {
+ fireEvent(new ContainerEvent<E>(this, deltas));
+ }
+
+ protected SingleDeltaContainerEvent<E> newContainerEvent(E element, IContainerDelta.Kind kind)
+ {
+ return new SingleDeltaContainerEvent<E>(this, element, kind);
+ }
+
+ protected ContainerEvent<E> newContainerEvent()
+ {
+ return new ContainerEvent<E>(this);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java index 8522519362..f2c0dea2f3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java @@ -1,45 +1,45 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -/** - * A default {@link IContainerDelta container delta} implementation. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerDelta<E> implements IContainerDelta<E> -{ - private E element; - - private Kind kind; - - public ContainerDelta(E element, Kind kind) - { - this.element = element; - this.kind = kind; - } - - public E getElement() - { - return element; - } - - public E setValue(E value) - { - throw new UnsupportedOperationException(); - } - - public Kind getKind() - { - return kind; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+/**
+ * A default {@link IContainerDelta container delta} implementation.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerDelta<E> implements IContainerDelta<E>
+{
+ private E element;
+
+ private Kind kind;
+
+ public ContainerDelta(E element, Kind kind)
+ {
+ this.element = element;
+ this.kind = kind;
+ }
+
+ public E getElement()
+ {
+ return element;
+ }
+
+ public E setValue(E value)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Kind getKind()
+ {
+ return kind;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java index 3ebc9aaa5b..b61d3912a5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java @@ -1,137 +1,137 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered; -import org.eclipse.net4j.util.event.Event; - -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; - -/** - * A default {@link IContainerEvent container event} implementation. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class ContainerEvent<E> extends Event implements IContainerEvent<E> -{ - private static final long serialVersionUID = 1L; - - private List<IContainerDelta<E>> deltas; - - public ContainerEvent(IContainer<E> container) - { - super(container); - deltas = new ArrayList<IContainerDelta<E>>(); - } - - public ContainerEvent(IContainer<E> container, List<IContainerDelta<E>> deltas) - { - super(container); - this.deltas = deltas; - } - - /** - * @since 3.0 - */ - @Override - @SuppressWarnings("unchecked") - public IContainer<E> getSource() - { - return (IContainer<E>)super.getSource(); - } - - public boolean isEmpty() - { - return deltas.isEmpty(); - } - - @SuppressWarnings("unchecked") - public IContainerDelta<E>[] getDeltas() - { - return deltas.toArray(new IContainerDelta[deltas.size()]); - } - - public IContainerDelta<E> getDelta() throws IllegalStateException - { - if (deltas.size() != 1) - { - throw new IllegalStateException("deltas.size() != 1"); //$NON-NLS-1$ - } - - return deltas.get(0); - } - - public E getDeltaElement() throws IllegalStateException - { - return getDelta().getElement(); - } - - public IContainerDelta.Kind getDeltaKind() throws IllegalStateException - { - return getDelta().getKind(); - } - - public void addDelta(E element, IContainerDelta.Kind kind) - { - addDelta(new ContainerDelta<E>(element, kind)); - } - - public void addDelta(IContainerDelta<E> delta) - { - deltas.add(delta); - } - - public void accept(IContainerEventVisitor<E> visitor) - { - for (IContainerDelta<E> delta : deltas) - { - E element = delta.getElement(); - - boolean filtered = true; - if (visitor instanceof Filtered<?>) - { - filtered = ((Filtered<E>)visitor).filter(element); - } - - if (filtered) - { - switch (delta.getKind()) - { - case ADDED: - visitor.added(element); - break; - case REMOVED: - visitor.removed(element); - break; - } - } - } - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - for (IContainerDelta<E> delta : getDeltas()) - { - builder.append(", "); //$NON-NLS-1$ - builder.append(delta.getKind()); - builder.append("="); //$NON-NLS-1$ - builder.append(delta.getElement()); - } - - return MessageFormat.format("ContainerEvent[source={0}{1}]", getSource(), builder.toString()); //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered;
+import org.eclipse.net4j.util.event.Event;
+
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A default {@link IContainerEvent container event} implementation.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class ContainerEvent<E> extends Event implements IContainerEvent<E>
+{
+ private static final long serialVersionUID = 1L;
+
+ private List<IContainerDelta<E>> deltas;
+
+ public ContainerEvent(IContainer<E> container)
+ {
+ super(container);
+ deltas = new ArrayList<IContainerDelta<E>>();
+ }
+
+ public ContainerEvent(IContainer<E> container, List<IContainerDelta<E>> deltas)
+ {
+ super(container);
+ this.deltas = deltas;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ public IContainer<E> getSource()
+ {
+ return (IContainer<E>)super.getSource();
+ }
+
+ public boolean isEmpty()
+ {
+ return deltas.isEmpty();
+ }
+
+ @SuppressWarnings("unchecked")
+ public IContainerDelta<E>[] getDeltas()
+ {
+ return deltas.toArray(new IContainerDelta[deltas.size()]);
+ }
+
+ public IContainerDelta<E> getDelta() throws IllegalStateException
+ {
+ if (deltas.size() != 1)
+ {
+ throw new IllegalStateException("deltas.size() != 1"); //$NON-NLS-1$
+ }
+
+ return deltas.get(0);
+ }
+
+ public E getDeltaElement() throws IllegalStateException
+ {
+ return getDelta().getElement();
+ }
+
+ public IContainerDelta.Kind getDeltaKind() throws IllegalStateException
+ {
+ return getDelta().getKind();
+ }
+
+ public void addDelta(E element, IContainerDelta.Kind kind)
+ {
+ addDelta(new ContainerDelta<E>(element, kind));
+ }
+
+ public void addDelta(IContainerDelta<E> delta)
+ {
+ deltas.add(delta);
+ }
+
+ public void accept(IContainerEventVisitor<E> visitor)
+ {
+ for (IContainerDelta<E> delta : deltas)
+ {
+ E element = delta.getElement();
+
+ boolean filtered = true;
+ if (visitor instanceof Filtered<?>)
+ {
+ filtered = ((Filtered<E>)visitor).filter(element);
+ }
+
+ if (filtered)
+ {
+ switch (delta.getKind())
+ {
+ case ADDED:
+ visitor.added(element);
+ break;
+ case REMOVED:
+ visitor.removed(element);
+ break;
+ }
+ }
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ StringBuilder builder = new StringBuilder();
+ for (IContainerDelta<E> delta : getDeltas())
+ {
+ builder.append(", "); //$NON-NLS-1$
+ builder.append(delta.getKind());
+ builder.append("="); //$NON-NLS-1$
+ builder.append(delta.getElement());
+ }
+
+ return MessageFormat.format("ContainerEvent[source={0}{1}]", getSource(), builder.toString()); //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java index 8df8d57ccc..5745dbb809 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java @@ -1,71 +1,71 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.event.IListener; - -/** - * A {@link IListener listener} that dispatches container {@link IContainerEvent events} to methods that can be - * overridden by extenders. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerEventAdapter<E> implements IListener -{ - public ContainerEventAdapter() - { - } - - public final void notifyEvent(IEvent event) - { - if (event instanceof IContainerEvent<?>) - { - @SuppressWarnings("unchecked") - IContainerEvent<E> e = (IContainerEvent<E>)event; - notifyContainerEvent(e); - } - else - { - notifyOtherEvent(event); - } - } - - protected void notifyContainerEvent(IContainerEvent<E> event) - { - final IContainer<E> container = event.getSource(); - event.accept(new IContainerEventVisitor<E>() - { - public void added(E element) - { - onAdded(container, element); - } - - public void removed(E element) - { - onRemoved(container, element); - } - }); - } - - protected void notifyOtherEvent(IEvent event) - { - } - - protected void onAdded(IContainer<E> container, E element) - { - } - - protected void onRemoved(IContainer<E> container, E element) - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.event.IListener;
+
+/**
+ * A {@link IListener listener} that dispatches container {@link IContainerEvent events} to methods that can be
+ * overridden by extenders.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerEventAdapter<E> implements IListener
+{
+ public ContainerEventAdapter()
+ {
+ }
+
+ public final void notifyEvent(IEvent event)
+ {
+ if (event instanceof IContainerEvent<?>)
+ {
+ @SuppressWarnings("unchecked")
+ IContainerEvent<E> e = (IContainerEvent<E>)event;
+ notifyContainerEvent(e);
+ }
+ else
+ {
+ notifyOtherEvent(event);
+ }
+ }
+
+ protected void notifyContainerEvent(IContainerEvent<E> event)
+ {
+ final IContainer<E> container = event.getSource();
+ event.accept(new IContainerEventVisitor<E>()
+ {
+ public void added(E element)
+ {
+ onAdded(container, element);
+ }
+
+ public void removed(E element)
+ {
+ onRemoved(container, element);
+ }
+ });
+ }
+
+ protected void notifyOtherEvent(IEvent event)
+ {
+ }
+
+ protected void onAdded(IContainer<E> container, E element)
+ {
+ }
+
+ protected void onRemoved(IContainer<E> container, E element)
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java index b6581cc295..c6032c87b0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java @@ -1,110 +1,110 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.concurrent.ExecutorServiceFactory; -import org.eclipse.net4j.util.concurrent.TimerLifecycle; -import org.eclipse.net4j.util.event.EventUtil; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.security.FileUserManagerFactory; -import org.eclipse.net4j.util.security.RandomizerFactory; - -/** - * Various static helper methods for dealing with {@link IContainer containers}. - * - * @author Eike Stepper - */ -public final class ContainerUtil -{ - private static final Object[] NO_ELEMENTS = {}; - - private static final IContainer<Object> EMPTY = new IContainer<Object>() - { - public Object[] getElements() - { - return NO_ELEMENTS; - } - - public boolean isEmpty() - { - return true; - } - - public void addListener(IListener listener) - { - } - - public void removeListener(IListener listener) - { - } - - public IListener[] getListeners() - { - return EventUtil.NO_LISTENERS; - } - - public boolean hasListeners() - { - return false; - } - - @Override - public String toString() - { - return "EMPTY_CONTAINER"; //$NON-NLS-1$ - } - }; - - private ContainerUtil() - { - } - - /** - * @since 2.0 - */ - public static void prepareContainer(IManagedContainer container) - { - container.registerFactory(new TimerLifecycle.DaemonFactory()); - container.registerFactory(new ExecutorServiceFactory()); - container.registerFactory(new RandomizerFactory()); - container.registerFactory(new FileUserManagerFactory()); - } - - public static IContainer<Object> emptyContainer() - { - return EMPTY; - } - - public static IManagedContainer createContainer() - { - return new ManagedContainer(); - } - - public static boolean isEmpty(Object container) - { - if (container instanceof IContainer<?>) - { - return ((IContainer<?>)container).isEmpty(); - } - - return true; - } - - public static Object[] getElements(Object container) - { - if (container instanceof IContainer<?>) - { - return ((IContainer<?>)container).getElements(); - } - - return NO_ELEMENTS; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.concurrent.ExecutorServiceFactory;
+import org.eclipse.net4j.util.concurrent.TimerLifecycle;
+import org.eclipse.net4j.util.event.EventUtil;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.security.FileUserManagerFactory;
+import org.eclipse.net4j.util.security.RandomizerFactory;
+
+/**
+ * Various static helper methods for dealing with {@link IContainer containers}.
+ *
+ * @author Eike Stepper
+ */
+public final class ContainerUtil
+{
+ private static final Object[] NO_ELEMENTS = {};
+
+ private static final IContainer<Object> EMPTY = new IContainer<Object>()
+ {
+ public Object[] getElements()
+ {
+ return NO_ELEMENTS;
+ }
+
+ public boolean isEmpty()
+ {
+ return true;
+ }
+
+ public void addListener(IListener listener)
+ {
+ }
+
+ public void removeListener(IListener listener)
+ {
+ }
+
+ public IListener[] getListeners()
+ {
+ return EventUtil.NO_LISTENERS;
+ }
+
+ public boolean hasListeners()
+ {
+ return false;
+ }
+
+ @Override
+ public String toString()
+ {
+ return "EMPTY_CONTAINER"; //$NON-NLS-1$
+ }
+ };
+
+ private ContainerUtil()
+ {
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static void prepareContainer(IManagedContainer container)
+ {
+ container.registerFactory(new TimerLifecycle.DaemonFactory());
+ container.registerFactory(new ExecutorServiceFactory());
+ container.registerFactory(new RandomizerFactory());
+ container.registerFactory(new FileUserManagerFactory());
+ }
+
+ public static IContainer<Object> emptyContainer()
+ {
+ return EMPTY;
+ }
+
+ public static IManagedContainer createContainer()
+ {
+ return new ManagedContainer();
+ }
+
+ public static boolean isEmpty(Object container)
+ {
+ if (container instanceof IContainer<?>)
+ {
+ return ((IContainer<?>)container).isEmpty();
+ }
+
+ return true;
+ }
+
+ public static Object[] getElements(Object container)
+ {
+ if (container instanceof IContainer<?>)
+ {
+ return ((IContainer<?>)container).getElements();
+ }
+
+ return NO_ELEMENTS;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java index 368c90a84a..91c25abcae 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java @@ -1,46 +1,46 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.factory.IFactory; -import org.eclipse.net4j.util.factory.IFactoryKey; - -/** - * An unchecked exception that indicates the absence of a {@link IFactory factory} identified by - * {@link IFactoryKey#getProductGroup() product group} and {@link IFactoryKey#getType() type}. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class FactoryNotFoundException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public FactoryNotFoundException() - { - } - - public FactoryNotFoundException(String message) - { - super(message); - } - - public FactoryNotFoundException(Throwable cause) - { - super(cause); - } - - public FactoryNotFoundException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.factory.IFactory;
+import org.eclipse.net4j.util.factory.IFactoryKey;
+
+/**
+ * An unchecked exception that indicates the absence of a {@link IFactory factory} identified by
+ * {@link IFactoryKey#getProductGroup() product group} and {@link IFactoryKey#getType() type}.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class FactoryNotFoundException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public FactoryNotFoundException()
+ {
+ }
+
+ public FactoryNotFoundException(String message)
+ {
+ super(message);
+ }
+
+ public FactoryNotFoundException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public FactoryNotFoundException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainer.java index 197134fb9b..97eae94642 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainer.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - * Victor Roldan Betancort - maintenance - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.event.INotifier; - -import java.util.Collection; - -/** - * Contains a number of elements and notifies about element addition and removal. - * <p> - * A container can fire the following events: - * <ul> - * <li> {@link IContainerEvent} after the addition and/or removal of elements. - * </ul> - * - * @author Eike Stepper - * @apiviz.landmark - * @apiviz.composedOf {@link java.lang.Object} - - elements - * @apiviz.uses {@link IContainerEvent} - - fires - */ -public interface IContainer<E> extends INotifier -{ - public boolean isEmpty(); - - public E[] getElements(); - - /** - * @author Eike Stepper - * @since 2.0 - */ - public interface Modifiable<E> extends IContainer<E> - { - public boolean addElement(E element); - - public boolean addAllElements(Collection<E> elements); - - public boolean removeElement(E element); - - public boolean removeAllElements(Collection<E> elements); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ * Victor Roldan Betancort - maintenance
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.event.INotifier;
+
+import java.util.Collection;
+
+/**
+ * Contains a number of elements and notifies about element addition and removal.
+ * <p>
+ * A container can fire the following events:
+ * <ul>
+ * <li> {@link IContainerEvent} after the addition and/or removal of elements.
+ * </ul>
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ * @apiviz.composedOf {@link java.lang.Object} - - elements
+ * @apiviz.uses {@link IContainerEvent} - - fires
+ */
+public interface IContainer<E> extends INotifier
+{
+ public boolean isEmpty();
+
+ public E[] getElements();
+
+ /**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+ public interface Modifiable<E> extends IContainer<E>
+ {
+ public boolean addElement(E element);
+
+ public boolean addAllElements(Collection<E> elements);
+
+ public boolean removeElement(E element);
+
+ public boolean removeAllElements(Collection<E> elements);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java index fdcc699c21..7120e43325 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -/** - * Describes the addition or removal of a single element from a {@link IContainer container}. - * - * @author Eike Stepper - */ -public interface IContainerDelta<E> -{ - public E getElement(); - - public Kind getKind(); - - /** - * Enumerates the possible {@link IContainerDelta container delta} kinds {@link #ADDED} or {@link #REMOVED}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - public enum Kind - { - ADDED, REMOVED - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+/**
+ * Describes the addition or removal of a single element from a {@link IContainer container}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerDelta<E>
+{
+ public E getElement();
+
+ public Kind getKind();
+
+ /**
+ * Enumerates the possible {@link IContainerDelta container delta} kinds {@link #ADDED} or {@link #REMOVED}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ public enum Kind
+ {
+ ADDED, REMOVED
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java index d462ae74fe..c0dec36d55 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java @@ -1,42 +1,42 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.container.IContainerDelta.Kind; -import org.eclipse.net4j.util.event.IEvent; - -/** - * An {@link IEvent event} fired from a {@link IContainer container} when its elements have changed. - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - * @apiviz.composedOf {@link IContainerDelta} - - deltas - */ -public interface IContainerEvent<E> extends IEvent -{ - /** - * @since 3.0 - */ - public IContainer<E> getSource(); - - public boolean isEmpty(); - - public IContainerDelta<E>[] getDeltas(); - - public IContainerDelta<E> getDelta() throws IllegalStateException; - - public E getDeltaElement() throws IllegalStateException; - - public Kind getDeltaKind() throws IllegalStateException; - - public void accept(IContainerEventVisitor<E> visitor); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.container.IContainerDelta.Kind;
+import org.eclipse.net4j.util.event.IEvent;
+
+/**
+ * An {@link IEvent event} fired from a {@link IContainer container} when its elements have changed.
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @apiviz.composedOf {@link IContainerDelta} - - deltas
+ */
+public interface IContainerEvent<E> extends IEvent
+{
+ /**
+ * @since 3.0
+ */
+ public IContainer<E> getSource();
+
+ public boolean isEmpty();
+
+ public IContainerDelta<E>[] getDeltas();
+
+ public IContainerDelta<E> getDelta() throws IllegalStateException;
+
+ public E getDeltaElement() throws IllegalStateException;
+
+ public Kind getDeltaKind() throws IllegalStateException;
+
+ public void accept(IContainerEventVisitor<E> visitor);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java index cbe17ffb4b..26f86cf06b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java @@ -1,38 +1,38 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -/** - * A callback interface for visiting {@link IContainerDelta container deltas}. - * - * @see IContainerEvent#accept(IContainerEventVisitor) - * @author Eike Stepper - * @apiviz.exclude - */ -public interface IContainerEventVisitor<E> -{ - public void added(E element); - - public void removed(E element); - - /** - * An extension interface for {@link IContainerEventVisitor container event visitors} that can {@link #filter(Object) - * filter} deltas from being visited. - * - * @see IContainerEvent#accept(IContainerEventVisitor) - * @author Eike Stepper - * @apiviz.exclude - */ - public interface Filtered<E> extends IContainerEventVisitor<E> - { - public boolean filter(E element); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+/**
+ * A callback interface for visiting {@link IContainerDelta container deltas}.
+ *
+ * @see IContainerEvent#accept(IContainerEventVisitor)
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public interface IContainerEventVisitor<E>
+{
+ public void added(E element);
+
+ public void removed(E element);
+
+ /**
+ * An extension interface for {@link IContainerEventVisitor container event visitors} that can {@link #filter(Object)
+ * filter} deltas from being visited.
+ *
+ * @see IContainerEvent#accept(IContainerEventVisitor)
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ public interface Filtered<E> extends IContainerEventVisitor<E>
+ {
+ public boolean filter(E element);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java index 8455475308..4976b989f7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -/** - * Processes elements of a {@link IManagedContainer managed container} when they're added to the container. - * - * @author Eike Stepper - */ -public interface IElementProcessor -{ - public Object process(IManagedContainer container, String productGroup, String factoryType, String description, - Object element); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+/**
+ * Processes elements of a {@link IManagedContainer managed container} when they're added to the container.
+ *
+ * @author Eike Stepper
+ */
+public interface IElementProcessor
+{
+ public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
+ Object element);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java index 3af1b571f1..73df8ecaf9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.factory.IFactory; -import org.eclipse.net4j.util.factory.IFactoryKey; -import org.eclipse.net4j.util.lifecycle.ILifecycle; -import org.eclipse.net4j.util.registry.IRegistry; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Set; - -/** - * A {@link IContainer container} that populates itself by means of element {@link #getFactoryRegistry() factories} and - * {@link #getPostProcessors() post processors} . - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - * @apiviz.landmark - * @apiviz.composedOf {@link org.eclipse.net4j.util.factory.IFactory} - - factoryRegistry - * @apiviz.composedOf {@link org.eclipse.net4j.util.container.IElementProcessor} - - postProcessors - */ -public interface IManagedContainer extends IContainer<Object>, ILifecycle -{ - public IRegistry<IFactoryKey, IFactory> getFactoryRegistry(); - - public IManagedContainer registerFactory(IFactory factory); - - public List<IElementProcessor> getPostProcessors(); - - public void addPostProcessor(IElementProcessor postProcessor, boolean processExistingElements); - - public void addPostProcessor(IElementProcessor postProcessor); - - public void removePostProcessor(IElementProcessor postProcessor); - - public Set<String> getProductGroups(); - - public Set<String> getFactoryTypes(String productGroup); - - public IFactory getFactory(String productGroup, String factoryType); - - public Object putElement(String productGroup, String factoryType, String description, Object element); - - public String[] getElementKey(Object element); - - public Object[] getElements(String productGroup); - - public Object[] getElements(String productGroup, String factoryType); - - public Object getElement(String productGroup, String factoryType, String description); - - /** - * @since 2.0 - */ - public Object getElement(String productGroup, String factoryType, String description, boolean activate); - - public Object removeElement(String productGroup, String factoryType, String description); - - public void clearElements(); - - public void loadElements(InputStream stream) throws IOException; - - public void saveElements(OutputStream stream) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.factory.IFactory;
+import org.eclipse.net4j.util.factory.IFactoryKey;
+import org.eclipse.net4j.util.lifecycle.ILifecycle;
+import org.eclipse.net4j.util.registry.IRegistry;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A {@link IContainer container} that populates itself by means of element {@link #getFactoryRegistry() factories} and
+ * {@link #getPostProcessors() post processors} .
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @apiviz.landmark
+ * @apiviz.composedOf {@link org.eclipse.net4j.util.factory.IFactory} - - factoryRegistry
+ * @apiviz.composedOf {@link org.eclipse.net4j.util.container.IElementProcessor} - - postProcessors
+ */
+public interface IManagedContainer extends IContainer<Object>, ILifecycle
+{
+ public IRegistry<IFactoryKey, IFactory> getFactoryRegistry();
+
+ public IManagedContainer registerFactory(IFactory factory);
+
+ public List<IElementProcessor> getPostProcessors();
+
+ public void addPostProcessor(IElementProcessor postProcessor, boolean processExistingElements);
+
+ public void addPostProcessor(IElementProcessor postProcessor);
+
+ public void removePostProcessor(IElementProcessor postProcessor);
+
+ public Set<String> getProductGroups();
+
+ public Set<String> getFactoryTypes(String productGroup);
+
+ public IFactory getFactory(String productGroup, String factoryType);
+
+ public Object putElement(String productGroup, String factoryType, String description, Object element);
+
+ public String[] getElementKey(Object element);
+
+ public Object[] getElements(String productGroup);
+
+ public Object[] getElements(String productGroup, String factoryType);
+
+ public Object getElement(String productGroup, String factoryType, String description);
+
+ /**
+ * @since 2.0
+ */
+ public Object getElement(String productGroup, String factoryType, String description, boolean activate);
+
+ public Object removeElement(String productGroup, String factoryType, String description);
+
+ public void clearElements();
+
+ public void loadElements(InputStream stream) throws IOException;
+
+ public void saveElements(OutputStream stream) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java index 54288de62e..f62b62b39c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java @@ -1,28 +1,28 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.internal.util.container.PluginContainer; - -import org.eclipse.core.runtime.IExtensionRegistry; - -/** - * A {@link IManagedContainer managed container} that is configured by the {@link IExtensionRegistry extension registry} - * . - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface IPluginContainer extends IManagedContainer -{ - public static final IPluginContainer INSTANCE = PluginContainer.getInstance(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.internal.util.container.PluginContainer;
+
+import org.eclipse.core.runtime.IExtensionRegistry;
+
+/**
+ * A {@link IManagedContainer managed container} that is configured by the {@link IExtensionRegistry extension registry}
+ * .
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface IPluginContainer extends IManagedContainer
+{
+ public static final IPluginContainer INSTANCE = PluginContainer.getInstance();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java index d1e398dd01..e71b7712e5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -/** - * A marker interface to indicate that some method calls may be slow. - * - * @author Eike Stepper - * @since 3.1 - * @apiviz.exclude - */ -public interface ISlow -{ -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+/**
+ * A marker interface to indicate that some method calls may be slow.
+ *
+ * @author Eike Stepper
+ * @since 3.1
+ * @apiviz.exclude
+ */
+public interface ISlow
+{
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java index e66d12d17d..f0ad96466d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java @@ -1,88 +1,88 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.INotifier; -import org.eclipse.net4j.util.event.Notifier; -import org.eclipse.net4j.util.lifecycle.ILifecycleEvent; - -/** - * A delegating {@link IListener listener} that converts {@link ILifecycleEvent lifecycle events} into - * {@link IContainerEvent container events}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class LifecycleEventConverter<E> implements IListener -{ - private Notifier owner; - - public LifecycleEventConverter(Notifier owner) - { - this.owner = owner; - } - - public INotifier getOwner() - { - return owner; - } - - public void notifyEvent(IEvent event) - { - if (event instanceof ILifecycleEvent) - { - ILifecycleEvent e = (ILifecycleEvent)event; - switch (e.getKind()) - { - case ACTIVATED: - added(e); - break; - - case DEACTIVATED: - removed(e); - break; - } - } - } - - protected void added(ILifecycleEvent e) - { - fireContainerEvent(e, IContainerDelta.Kind.ADDED); - } - - protected void removed(ILifecycleEvent e) - { - fireContainerEvent(e, IContainerDelta.Kind.REMOVED); - } - - @SuppressWarnings("unchecked") - protected void fireContainerEvent(ILifecycleEvent e, IContainerDelta.Kind kind) - { - E element = (E)e.getSource(); - if (element != null) - { - IListener[] listeners = owner.getListeners(); - if (listeners != null) - { - owner.fireEvent(createContainerEvent((IContainer<E>)owner, element, kind), listeners); - } - } - } - - protected IContainerEvent<E> createContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind) - { - ContainerEvent<E> event = new ContainerEvent<E>(container); - event.addDelta(new ContainerDelta<E>(element, kind)); - return event; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.INotifier;
+import org.eclipse.net4j.util.event.Notifier;
+import org.eclipse.net4j.util.lifecycle.ILifecycleEvent;
+
+/**
+ * A delegating {@link IListener listener} that converts {@link ILifecycleEvent lifecycle events} into
+ * {@link IContainerEvent container events}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class LifecycleEventConverter<E> implements IListener
+{
+ private Notifier owner;
+
+ public LifecycleEventConverter(Notifier owner)
+ {
+ this.owner = owner;
+ }
+
+ public INotifier getOwner()
+ {
+ return owner;
+ }
+
+ public void notifyEvent(IEvent event)
+ {
+ if (event instanceof ILifecycleEvent)
+ {
+ ILifecycleEvent e = (ILifecycleEvent)event;
+ switch (e.getKind())
+ {
+ case ACTIVATED:
+ added(e);
+ break;
+
+ case DEACTIVATED:
+ removed(e);
+ break;
+ }
+ }
+ }
+
+ protected void added(ILifecycleEvent e)
+ {
+ fireContainerEvent(e, IContainerDelta.Kind.ADDED);
+ }
+
+ protected void removed(ILifecycleEvent e)
+ {
+ fireContainerEvent(e, IContainerDelta.Kind.REMOVED);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void fireContainerEvent(ILifecycleEvent e, IContainerDelta.Kind kind)
+ {
+ E element = (E)e.getSource();
+ if (element != null)
+ {
+ IListener[] listeners = owner.getListeners();
+ if (listeners != null)
+ {
+ owner.fireEvent(createContainerEvent((IContainer<E>)owner, element, kind), listeners);
+ }
+ }
+ }
+
+ protected IContainerEvent<E> createContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind)
+ {
+ ContainerEvent<E> event = new ContainerEvent<E>(container);
+ event.addDelta(new ContainerDelta<E>(element, kind));
+ return event;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ManagedContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ManagedContainer.java index d3e5029565..f975016c97 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ManagedContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ManagedContainer.java @@ -1,662 +1,662 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.ObjectUtil; -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.event.EventUtil; -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.factory.FactoryKey; -import org.eclipse.net4j.util.factory.IFactory; -import org.eclipse.net4j.util.factory.IFactoryKey; -import org.eclipse.net4j.util.lifecycle.ILifecycle; -import org.eclipse.net4j.util.lifecycle.Lifecycle; -import org.eclipse.net4j.util.lifecycle.LifecycleEventAdapter; -import org.eclipse.net4j.util.lifecycle.LifecycleUtil; -import org.eclipse.net4j.util.registry.HashMapRegistry; -import org.eclipse.net4j.util.registry.IRegistry; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -/** - * A default implementation of a {@link IManagedContainer managed container}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ManagedContainer extends Lifecycle implements IManagedContainer -{ - private IRegistry<IFactoryKey, IFactory> factoryRegistry; - - private List<IElementProcessor> postProcessors; - - private IRegistry<ElementKey, Object> elementRegistry = new HashMapRegistry<ElementKey, Object>(); - - @ExcludeFromDump - private transient long maxElementID; - - @ExcludeFromDump - private transient IListener elementListener = new LifecycleEventAdapter() - { - @Override - protected void onDeactivated(ILifecycle lifecycle) - { - for (Entry<ElementKey, Object> entry : getElementRegistryEntries()) - { - if (lifecycle == entry.getValue()) - { - removeElement(entry.getKey()); - return; - } - } - } - }; - - public ManagedContainer() - { - } - - public synchronized IRegistry<IFactoryKey, IFactory> getFactoryRegistry() - { - if (factoryRegistry == null) - { - factoryRegistry = createFactoryRegistry(); - } - - return factoryRegistry; - } - - public ManagedContainer registerFactory(IFactory factory) - { - getFactoryRegistry().put(factory.getKey(), factory); - return this; - } - - public synchronized List<IElementProcessor> getPostProcessors() - { - if (postProcessors == null) - { - postProcessors = createPostProcessors(); - } - - return postProcessors; - } - - public synchronized void addPostProcessor(IElementProcessor postProcessor, boolean processExistingElements) - { - if (processExistingElements) - { - ContainerEvent<Object> event = new ContainerEvent<Object>(this); - for (Entry<ElementKey, Object> entry : getElementRegistryEntries()) - { - ElementKey key = entry.getKey(); - Object element = entry.getValue(); - - String productGroup = key.getProductGroup(); - String factoryType = key.getFactoryType(); - String description = key.getDescription(); - Object newElement = postProcessor.process(this, productGroup, factoryType, description, element); - if (newElement != element) - { - synchronized (elementRegistry) - { - elementRegistry.put(key, newElement); - } - - event.addDelta(element, IContainerDelta.Kind.REMOVED); - event.addDelta(newElement, IContainerDelta.Kind.ADDED); - } - } - - fireEvent(event); - } - - getPostProcessors().add(postProcessor); - } - - public void addPostProcessor(IElementProcessor postProcessor) - { - addPostProcessor(postProcessor, false); - } - - public void removePostProcessor(IElementProcessor postProcessor) - { - getPostProcessors().remove(postProcessor); - } - - public Set<String> getProductGroups() - { - checkActive(); - Set<String> result = new HashSet<String>(); - for (IFactoryKey key : factoryRegistry.keySet()) - { - result.add(key.getProductGroup()); - } - - for (ElementKey key : getElementRegistryKeys()) - { - result.add(key.getProductGroup()); - } - - return result; - } - - public Set<String> getFactoryTypes(String productGroup) - { - checkActive(); - Set<String> result = new HashSet<String>(); - for (IFactoryKey key : factoryRegistry.keySet()) - { - if (ObjectUtil.equals(key.getProductGroup(), productGroup)) - { - result.add(key.getType()); - } - } - - for (ElementKey key : getElementRegistryKeys()) - { - if (ObjectUtil.equals(key.getProductGroup(), productGroup)) - { - result.add(key.getFactoryType()); - } - } - - return result; - } - - public IFactory getFactory(String productGroup, String factoryType) - { - FactoryKey key = new FactoryKey(productGroup, factoryType); - IFactory factory = getFactoryRegistry().get(key); - if (factory == null) - { - throw new FactoryNotFoundException("Factory not found: " + key); //$NON-NLS-1$ - } - - return factory; - } - - public boolean isEmpty() - { - checkActive(); - synchronized (elementRegistry) - { - return elementRegistry.isEmpty(); - } - } - - public String[] getElementKey(Object element) - { - checkActive(); - for (Entry<ElementKey, Object> entry : getElementRegistryEntries()) - { - if (entry.getValue() == element) - { - ElementKey key = entry.getKey(); - String[] result = { key.getProductGroup(), key.getFactoryType(), key.getDescription() }; - return result; - } - } - - return null; - } - - public Object[] getElements() - { - checkActive(); - return getElementRegistryValues(); - } - - public Object[] getElements(String productGroup) - { - checkActive(); - List<Object> result = new ArrayList<Object>(); - for (Entry<ElementKey, Object> entry : getElementRegistryEntries()) - { - ElementKey key = entry.getKey(); - if (ObjectUtil.equals(key.getProductGroup(), productGroup)) - { - result.add(entry.getValue()); - } - } - - return result.toArray(); - } - - public Object[] getElements(String productGroup, String factoryType) - { - checkActive(); - List<Object> result = new ArrayList<Object>(); - for (Entry<ElementKey, Object> entry : getElementRegistryEntries()) - { - ElementKey key = entry.getKey(); - if (ObjectUtil.equals(key.getProductGroup(), productGroup) - && ObjectUtil.equals(key.getFactoryType(), factoryType)) - { - result.add(entry.getValue()); - } - } - - return result.toArray(); - } - - public Object getElement(String productGroup, String factoryType, String description) - { - return getElement(productGroup, factoryType, description, true); - } - - /** - * @since 2.0 - */ - public Object getElement(String productGroup, String factoryType, String description, boolean activate) - { - checkActive(); - ElementKey key = new ElementKey(productGroup, factoryType, description); - Object element; - synchronized (elementRegistry) - { - element = elementRegistry.get(key); - } - - if (element == null) - { - element = createElement(productGroup, factoryType, description); - element = postProcessElement(productGroup, factoryType, description, element); - - if (activate) - { - LifecycleUtil.activate(element); - } - - putElement(key, element); - } - - return element; - } - - public Object putElement(String productGroup, String factoryType, String description, Object element) - { - checkActive(); - element = postProcessElement(productGroup, factoryType, description, element); - - ElementKey key = new ElementKey(productGroup, factoryType, description); - return putElement(key, element); - } - - protected Object putElement(ElementKey key, Object element) - { - ContainerEvent<Object> event = new ContainerEvent<Object>(this); - Object oldElement; - synchronized (elementRegistry) - { - key.setID(++maxElementID); - oldElement = elementRegistry.put(key, element); - } - - if (oldElement != null) - { - EventUtil.removeListener(oldElement, elementListener); - event.addDelta(oldElement, IContainerDelta.Kind.REMOVED); - } - - event.addDelta(element, IContainerDelta.Kind.ADDED); - fireEvent(event); - EventUtil.addListener(element, elementListener); - return oldElement; - } - - public Object removeElement(String productGroup, String factoryType, String description) - { - checkActive(); - ElementKey key = new ElementKey(productGroup, factoryType, description); - return removeElement(key); - } - - protected Object removeElement(ElementKey key) - { - Object element; - synchronized (elementRegistry) - { - element = elementRegistry.remove(key); - } - - if (element != null) - { - EventUtil.removeListener(element, elementListener); - fireEvent(new SingleDeltaContainerEvent<Object>(this, element, IContainerDelta.Kind.REMOVED)); - } - - return element; - } - - public void clearElements() - { - checkActive(); - ContainerEvent<Object> event = null; - synchronized (elementRegistry) - { - if (!elementRegistry.isEmpty()) - { - event = new ContainerEvent<Object>(this); - for (Object element : elementRegistry.values()) - { - EventUtil.removeListener(element, elementListener); - event.addDelta(element, IContainerDelta.Kind.REMOVED); - } - - elementRegistry.clear(); - } - } - - if (event != null) - { - fireEvent(event); - } - } - - public void loadElements(InputStream stream) throws IOException - { - checkActive(); - synchronized (elementRegistry) - { - clearElements(); - ObjectInputStream ois = new ObjectInputStream(stream); - int size = ois.readInt(); - for (int i = 0; i < size; i++) - { - try - { - ElementKey key = (ElementKey)ois.readObject(); - Object element = getElement(key.getProductGroup(), key.getFactoryType(), key.getDescription()); - - boolean active = ois.readBoolean(); - if (active) - { - // TODO Reconsider activation - LifecycleUtil.activate(element); - } - } - catch (ClassNotFoundException cannotHappen) - { - } - } - - initMaxElementID(); - } - } - - public void saveElements(OutputStream stream) throws IOException - { - checkActive(); - synchronized (elementRegistry) - { - ObjectOutputStream oos = new ObjectOutputStream(stream); - List<Entry<ElementKey, Object>> entries = new ArrayList<Entry<ElementKey, Object>>(elementRegistry.entrySet()); - Collections.sort(entries, new EntryComparator()); - - oos.writeInt(entries.size()); - for (Entry<ElementKey, Object> entry : entries) - { - oos.writeObject(entry.getKey()); - oos.writeBoolean(LifecycleUtil.isActive(entry.getValue())); - } - } - } - - @Override - public void fireEvent(IEvent event) - { - if (event instanceof IContainerEvent<?>) - { - @SuppressWarnings("unchecked") - IContainerEvent<Object> e = (IContainerEvent<Object>)event; - if (e.isEmpty()) - { - return; - } - } - - super.fireEvent(event); - } - - @Override - public String toString() - { - return "ManagedContainer"; //$NON-NLS-1$ - } - - protected IRegistry<IFactoryKey, IFactory> createFactoryRegistry() - { - return new HashMapRegistry<IFactoryKey, IFactory>(); - } - - protected List<IElementProcessor> createPostProcessors() - { - return new ArrayList<IElementProcessor>(); - } - - /** - * @since 2.0 - */ - protected ElementKey[] getElementRegistryKeys() - { - synchronized (elementRegistry) - { - return elementRegistry.keySet().toArray(new ElementKey[elementRegistry.size()]); - } - } - - /** - * @since 2.0 - */ - protected Object[] getElementRegistryValues() - { - synchronized (elementRegistry) - { - return elementRegistry.values().toArray(new Object[elementRegistry.size()]); - } - } - - /** - * @since 2.0 - */ - @SuppressWarnings("unchecked") - protected Entry<ElementKey, Object>[] getElementRegistryEntries() - { - synchronized (elementRegistry) - { - return elementRegistry.entrySet().toArray(new Entry[elementRegistry.size()]); - } - } - - protected Object createElement(String productGroup, String factoryType, String description) - { - IFactory factory = getFactory(productGroup, factoryType); - return factory.create(description); - } - - protected Object postProcessElement(String productGroup, String factoryType, String description, Object element) - { - for (IElementProcessor processor : getPostProcessors()) - { - element = processor.process(this, productGroup, factoryType, description, element); - } - - return element; - } - - private void initMaxElementID() - { - maxElementID = 0L; - for (ElementKey key : elementRegistry.keySet()) - { - long id = key.getID(); - if (maxElementID < id) - { - maxElementID = id; - } - } - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - LifecycleUtil.activate(getFactoryRegistry()); - LifecycleUtil.activate(getPostProcessors()); - } - - @Override - protected void doDeactivate() throws Exception - { - for (Object element : getElementRegistryValues()) - { - try - { - LifecycleUtil.deactivateNoisy(element); - EventUtil.removeListener(element, elementListener); - } - catch (RuntimeException ex) - { - OM.LOG.warn(ex); - } - } - - LifecycleUtil.deactivate(factoryRegistry); - factoryRegistry = null; - - LifecycleUtil.deactivate(postProcessors); - postProcessors = null; - - elementRegistry.clear(); - elementRegistry = null; - super.doDeactivate(); - } - - /** - * @author Eike Stepper - */ - private static final class ElementKey implements Serializable, Comparable<ElementKey> - { - private static final long serialVersionUID = 1L; - - private long id; - - private String productGroup; - - private String factoryType; - - private String description; - - public ElementKey(String productGroup, String factoryType, String description) - { - this.productGroup = productGroup; - this.factoryType = factoryType; - this.description = description; - } - - public long getID() - { - return id; - } - - public void setID(long id) - { - this.id = id; - } - - public String getProductGroup() - { - return productGroup; - } - - public String getFactoryType() - { - return factoryType; - } - - public String getDescription() - { - return description; - } - - @Override - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (obj instanceof ElementKey) - { - ElementKey key = (ElementKey)obj; - return ObjectUtil.equals(productGroup, key.productGroup) && ObjectUtil.equals(factoryType, key.factoryType) - && ObjectUtil.equals(description, key.description); - } - - return false; - } - - @Override - public int hashCode() - { - return ObjectUtil.hashCode(productGroup) ^ ObjectUtil.hashCode(factoryType) ^ ObjectUtil.hashCode(description); - } - - @Override - public String toString() - { - return MessageFormat.format("{0}[{1}, {2}]", productGroup, factoryType, description); //$NON-NLS-1$ - } - - public int compareTo(ElementKey key) - { - if (id < key.id) - { - return -1; - } - - if (id > key.id) - { - return 1; - } - - return 0; - } - } - - /** - * @author Eike Stepper - */ - private static final class EntryComparator implements Comparator<Entry<ElementKey, Object>> - { - public int compare(Entry<ElementKey, Object> entry1, Entry<ElementKey, Object> entry2) - { - return entry1.getKey().compareTo(entry2.getKey()); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.ObjectUtil;
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.event.EventUtil;
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.factory.FactoryKey;
+import org.eclipse.net4j.util.factory.IFactory;
+import org.eclipse.net4j.util.factory.IFactoryKey;
+import org.eclipse.net4j.util.lifecycle.ILifecycle;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+import org.eclipse.net4j.util.lifecycle.LifecycleEventAdapter;
+import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
+import org.eclipse.net4j.util.registry.HashMapRegistry;
+import org.eclipse.net4j.util.registry.IRegistry;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+
+/**
+ * A default implementation of a {@link IManagedContainer managed container}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ManagedContainer extends Lifecycle implements IManagedContainer
+{
+ private IRegistry<IFactoryKey, IFactory> factoryRegistry;
+
+ private List<IElementProcessor> postProcessors;
+
+ private IRegistry<ElementKey, Object> elementRegistry = new HashMapRegistry<ElementKey, Object>();
+
+ @ExcludeFromDump
+ private transient long maxElementID;
+
+ @ExcludeFromDump
+ private transient IListener elementListener = new LifecycleEventAdapter()
+ {
+ @Override
+ protected void onDeactivated(ILifecycle lifecycle)
+ {
+ for (Entry<ElementKey, Object> entry : getElementRegistryEntries())
+ {
+ if (lifecycle == entry.getValue())
+ {
+ removeElement(entry.getKey());
+ return;
+ }
+ }
+ }
+ };
+
+ public ManagedContainer()
+ {
+ }
+
+ public synchronized IRegistry<IFactoryKey, IFactory> getFactoryRegistry()
+ {
+ if (factoryRegistry == null)
+ {
+ factoryRegistry = createFactoryRegistry();
+ }
+
+ return factoryRegistry;
+ }
+
+ public ManagedContainer registerFactory(IFactory factory)
+ {
+ getFactoryRegistry().put(factory.getKey(), factory);
+ return this;
+ }
+
+ public synchronized List<IElementProcessor> getPostProcessors()
+ {
+ if (postProcessors == null)
+ {
+ postProcessors = createPostProcessors();
+ }
+
+ return postProcessors;
+ }
+
+ public synchronized void addPostProcessor(IElementProcessor postProcessor, boolean processExistingElements)
+ {
+ if (processExistingElements)
+ {
+ ContainerEvent<Object> event = new ContainerEvent<Object>(this);
+ for (Entry<ElementKey, Object> entry : getElementRegistryEntries())
+ {
+ ElementKey key = entry.getKey();
+ Object element = entry.getValue();
+
+ String productGroup = key.getProductGroup();
+ String factoryType = key.getFactoryType();
+ String description = key.getDescription();
+ Object newElement = postProcessor.process(this, productGroup, factoryType, description, element);
+ if (newElement != element)
+ {
+ synchronized (elementRegistry)
+ {
+ elementRegistry.put(key, newElement);
+ }
+
+ event.addDelta(element, IContainerDelta.Kind.REMOVED);
+ event.addDelta(newElement, IContainerDelta.Kind.ADDED);
+ }
+ }
+
+ fireEvent(event);
+ }
+
+ getPostProcessors().add(postProcessor);
+ }
+
+ public void addPostProcessor(IElementProcessor postProcessor)
+ {
+ addPostProcessor(postProcessor, false);
+ }
+
+ public void removePostProcessor(IElementProcessor postProcessor)
+ {
+ getPostProcessors().remove(postProcessor);
+ }
+
+ public Set<String> getProductGroups()
+ {
+ checkActive();
+ Set<String> result = new HashSet<String>();
+ for (IFactoryKey key : factoryRegistry.keySet())
+ {
+ result.add(key.getProductGroup());
+ }
+
+ for (ElementKey key : getElementRegistryKeys())
+ {
+ result.add(key.getProductGroup());
+ }
+
+ return result;
+ }
+
+ public Set<String> getFactoryTypes(String productGroup)
+ {
+ checkActive();
+ Set<String> result = new HashSet<String>();
+ for (IFactoryKey key : factoryRegistry.keySet())
+ {
+ if (ObjectUtil.equals(key.getProductGroup(), productGroup))
+ {
+ result.add(key.getType());
+ }
+ }
+
+ for (ElementKey key : getElementRegistryKeys())
+ {
+ if (ObjectUtil.equals(key.getProductGroup(), productGroup))
+ {
+ result.add(key.getFactoryType());
+ }
+ }
+
+ return result;
+ }
+
+ public IFactory getFactory(String productGroup, String factoryType)
+ {
+ FactoryKey key = new FactoryKey(productGroup, factoryType);
+ IFactory factory = getFactoryRegistry().get(key);
+ if (factory == null)
+ {
+ throw new FactoryNotFoundException("Factory not found: " + key); //$NON-NLS-1$
+ }
+
+ return factory;
+ }
+
+ public boolean isEmpty()
+ {
+ checkActive();
+ synchronized (elementRegistry)
+ {
+ return elementRegistry.isEmpty();
+ }
+ }
+
+ public String[] getElementKey(Object element)
+ {
+ checkActive();
+ for (Entry<ElementKey, Object> entry : getElementRegistryEntries())
+ {
+ if (entry.getValue() == element)
+ {
+ ElementKey key = entry.getKey();
+ String[] result = { key.getProductGroup(), key.getFactoryType(), key.getDescription() };
+ return result;
+ }
+ }
+
+ return null;
+ }
+
+ public Object[] getElements()
+ {
+ checkActive();
+ return getElementRegistryValues();
+ }
+
+ public Object[] getElements(String productGroup)
+ {
+ checkActive();
+ List<Object> result = new ArrayList<Object>();
+ for (Entry<ElementKey, Object> entry : getElementRegistryEntries())
+ {
+ ElementKey key = entry.getKey();
+ if (ObjectUtil.equals(key.getProductGroup(), productGroup))
+ {
+ result.add(entry.getValue());
+ }
+ }
+
+ return result.toArray();
+ }
+
+ public Object[] getElements(String productGroup, String factoryType)
+ {
+ checkActive();
+ List<Object> result = new ArrayList<Object>();
+ for (Entry<ElementKey, Object> entry : getElementRegistryEntries())
+ {
+ ElementKey key = entry.getKey();
+ if (ObjectUtil.equals(key.getProductGroup(), productGroup)
+ && ObjectUtil.equals(key.getFactoryType(), factoryType))
+ {
+ result.add(entry.getValue());
+ }
+ }
+
+ return result.toArray();
+ }
+
+ public Object getElement(String productGroup, String factoryType, String description)
+ {
+ return getElement(productGroup, factoryType, description, true);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public Object getElement(String productGroup, String factoryType, String description, boolean activate)
+ {
+ checkActive();
+ ElementKey key = new ElementKey(productGroup, factoryType, description);
+ Object element;
+ synchronized (elementRegistry)
+ {
+ element = elementRegistry.get(key);
+ }
+
+ if (element == null)
+ {
+ element = createElement(productGroup, factoryType, description);
+ element = postProcessElement(productGroup, factoryType, description, element);
+
+ if (activate)
+ {
+ LifecycleUtil.activate(element);
+ }
+
+ putElement(key, element);
+ }
+
+ return element;
+ }
+
+ public Object putElement(String productGroup, String factoryType, String description, Object element)
+ {
+ checkActive();
+ element = postProcessElement(productGroup, factoryType, description, element);
+
+ ElementKey key = new ElementKey(productGroup, factoryType, description);
+ return putElement(key, element);
+ }
+
+ protected Object putElement(ElementKey key, Object element)
+ {
+ ContainerEvent<Object> event = new ContainerEvent<Object>(this);
+ Object oldElement;
+ synchronized (elementRegistry)
+ {
+ key.setID(++maxElementID);
+ oldElement = elementRegistry.put(key, element);
+ }
+
+ if (oldElement != null)
+ {
+ EventUtil.removeListener(oldElement, elementListener);
+ event.addDelta(oldElement, IContainerDelta.Kind.REMOVED);
+ }
+
+ event.addDelta(element, IContainerDelta.Kind.ADDED);
+ fireEvent(event);
+ EventUtil.addListener(element, elementListener);
+ return oldElement;
+ }
+
+ public Object removeElement(String productGroup, String factoryType, String description)
+ {
+ checkActive();
+ ElementKey key = new ElementKey(productGroup, factoryType, description);
+ return removeElement(key);
+ }
+
+ protected Object removeElement(ElementKey key)
+ {
+ Object element;
+ synchronized (elementRegistry)
+ {
+ element = elementRegistry.remove(key);
+ }
+
+ if (element != null)
+ {
+ EventUtil.removeListener(element, elementListener);
+ fireEvent(new SingleDeltaContainerEvent<Object>(this, element, IContainerDelta.Kind.REMOVED));
+ }
+
+ return element;
+ }
+
+ public void clearElements()
+ {
+ checkActive();
+ ContainerEvent<Object> event = null;
+ synchronized (elementRegistry)
+ {
+ if (!elementRegistry.isEmpty())
+ {
+ event = new ContainerEvent<Object>(this);
+ for (Object element : elementRegistry.values())
+ {
+ EventUtil.removeListener(element, elementListener);
+ event.addDelta(element, IContainerDelta.Kind.REMOVED);
+ }
+
+ elementRegistry.clear();
+ }
+ }
+
+ if (event != null)
+ {
+ fireEvent(event);
+ }
+ }
+
+ public void loadElements(InputStream stream) throws IOException
+ {
+ checkActive();
+ synchronized (elementRegistry)
+ {
+ clearElements();
+ ObjectInputStream ois = new ObjectInputStream(stream);
+ int size = ois.readInt();
+ for (int i = 0; i < size; i++)
+ {
+ try
+ {
+ ElementKey key = (ElementKey)ois.readObject();
+ Object element = getElement(key.getProductGroup(), key.getFactoryType(), key.getDescription());
+
+ boolean active = ois.readBoolean();
+ if (active)
+ {
+ // TODO Reconsider activation
+ LifecycleUtil.activate(element);
+ }
+ }
+ catch (ClassNotFoundException cannotHappen)
+ {
+ }
+ }
+
+ initMaxElementID();
+ }
+ }
+
+ public void saveElements(OutputStream stream) throws IOException
+ {
+ checkActive();
+ synchronized (elementRegistry)
+ {
+ ObjectOutputStream oos = new ObjectOutputStream(stream);
+ List<Entry<ElementKey, Object>> entries = new ArrayList<Entry<ElementKey, Object>>(elementRegistry.entrySet());
+ Collections.sort(entries, new EntryComparator());
+
+ oos.writeInt(entries.size());
+ for (Entry<ElementKey, Object> entry : entries)
+ {
+ oos.writeObject(entry.getKey());
+ oos.writeBoolean(LifecycleUtil.isActive(entry.getValue()));
+ }
+ }
+ }
+
+ @Override
+ public void fireEvent(IEvent event)
+ {
+ if (event instanceof IContainerEvent<?>)
+ {
+ @SuppressWarnings("unchecked")
+ IContainerEvent<Object> e = (IContainerEvent<Object>)event;
+ if (e.isEmpty())
+ {
+ return;
+ }
+ }
+
+ super.fireEvent(event);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "ManagedContainer"; //$NON-NLS-1$
+ }
+
+ protected IRegistry<IFactoryKey, IFactory> createFactoryRegistry()
+ {
+ return new HashMapRegistry<IFactoryKey, IFactory>();
+ }
+
+ protected List<IElementProcessor> createPostProcessors()
+ {
+ return new ArrayList<IElementProcessor>();
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected ElementKey[] getElementRegistryKeys()
+ {
+ synchronized (elementRegistry)
+ {
+ return elementRegistry.keySet().toArray(new ElementKey[elementRegistry.size()]);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected Object[] getElementRegistryValues()
+ {
+ synchronized (elementRegistry)
+ {
+ return elementRegistry.values().toArray(new Object[elementRegistry.size()]);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ @SuppressWarnings("unchecked")
+ protected Entry<ElementKey, Object>[] getElementRegistryEntries()
+ {
+ synchronized (elementRegistry)
+ {
+ return elementRegistry.entrySet().toArray(new Entry[elementRegistry.size()]);
+ }
+ }
+
+ protected Object createElement(String productGroup, String factoryType, String description)
+ {
+ IFactory factory = getFactory(productGroup, factoryType);
+ return factory.create(description);
+ }
+
+ protected Object postProcessElement(String productGroup, String factoryType, String description, Object element)
+ {
+ for (IElementProcessor processor : getPostProcessors())
+ {
+ element = processor.process(this, productGroup, factoryType, description, element);
+ }
+
+ return element;
+ }
+
+ private void initMaxElementID()
+ {
+ maxElementID = 0L;
+ for (ElementKey key : elementRegistry.keySet())
+ {
+ long id = key.getID();
+ if (maxElementID < id)
+ {
+ maxElementID = id;
+ }
+ }
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ LifecycleUtil.activate(getFactoryRegistry());
+ LifecycleUtil.activate(getPostProcessors());
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ for (Object element : getElementRegistryValues())
+ {
+ try
+ {
+ LifecycleUtil.deactivateNoisy(element);
+ EventUtil.removeListener(element, elementListener);
+ }
+ catch (RuntimeException ex)
+ {
+ OM.LOG.warn(ex);
+ }
+ }
+
+ LifecycleUtil.deactivate(factoryRegistry);
+ factoryRegistry = null;
+
+ LifecycleUtil.deactivate(postProcessors);
+ postProcessors = null;
+
+ elementRegistry.clear();
+ elementRegistry = null;
+ super.doDeactivate();
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class ElementKey implements Serializable, Comparable<ElementKey>
+ {
+ private static final long serialVersionUID = 1L;
+
+ private long id;
+
+ private String productGroup;
+
+ private String factoryType;
+
+ private String description;
+
+ public ElementKey(String productGroup, String factoryType, String description)
+ {
+ this.productGroup = productGroup;
+ this.factoryType = factoryType;
+ this.description = description;
+ }
+
+ public long getID()
+ {
+ return id;
+ }
+
+ public void setID(long id)
+ {
+ this.id = id;
+ }
+
+ public String getProductGroup()
+ {
+ return productGroup;
+ }
+
+ public String getFactoryType()
+ {
+ return factoryType;
+ }
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ if (obj instanceof ElementKey)
+ {
+ ElementKey key = (ElementKey)obj;
+ return ObjectUtil.equals(productGroup, key.productGroup) && ObjectUtil.equals(factoryType, key.factoryType)
+ && ObjectUtil.equals(description, key.description);
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return ObjectUtil.hashCode(productGroup) ^ ObjectUtil.hashCode(factoryType) ^ ObjectUtil.hashCode(description);
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("{0}[{1}, {2}]", productGroup, factoryType, description); //$NON-NLS-1$
+ }
+
+ public int compareTo(ElementKey key)
+ {
+ if (id < key.id)
+ {
+ return -1;
+ }
+
+ if (id > key.id)
+ {
+ return 1;
+ }
+
+ return 0;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class EntryComparator implements Comparator<Entry<ElementKey, Object>>
+ {
+ public int compare(Entry<ElementKey, Object> entry1, Entry<ElementKey, Object> entry2)
+ {
+ return entry1.getKey().compareTo(entry2.getKey());
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java index 2b229fccba..527795b63c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container; - -import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered; -import org.eclipse.net4j.util.event.Event; - -import java.text.MessageFormat; - -/** - * A {@link IContainerEvent container event} with a single element {@link IContainerDelta delta}. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class SingleDeltaContainerEvent<E> extends Event implements IContainerEvent<E> -{ - private static final long serialVersionUID = 1L; - - private IContainerDelta<E>[] deltas; - - @SuppressWarnings("unchecked") - public SingleDeltaContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind) - { - super(container); - deltas = new IContainerDelta[] { new ContainerDelta<E>(element, kind) }; - } - - /** - * @since 3.0 - */ - @Override - @SuppressWarnings("unchecked") - public IContainer<E> getSource() - { - return (IContainer<E>)super.getSource(); - } - - public boolean isEmpty() - { - return false; - } - - public IContainerDelta<E>[] getDeltas() - { - return deltas; - } - - public IContainerDelta<E> getDelta() throws IllegalStateException - { - return deltas[0]; - } - - public E getDeltaElement() throws IllegalStateException - { - return deltas[0].getElement(); - } - - public IContainerDelta.Kind getDeltaKind() throws IllegalStateException - { - return deltas[0].getKind(); - } - - public void accept(IContainerEventVisitor<E> visitor) - { - E element = deltas[0].getElement(); - - boolean filtered = true; - if (visitor instanceof Filtered<?>) - { - filtered = ((Filtered<E>)visitor).filter(element); - } - - if (filtered) - { - switch (deltas[0].getKind()) - { - case ADDED: - visitor.added(element); - break; - case REMOVED: - visitor.removed(element); - break; - } - } - } - - @Override - public String toString() - { - return MessageFormat.format("ContainerEvent[source={0}, {1}={2}]", getSource(), getDeltaElement(), getDeltaKind()); //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container;
+
+import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered;
+import org.eclipse.net4j.util.event.Event;
+
+import java.text.MessageFormat;
+
+/**
+ * A {@link IContainerEvent container event} with a single element {@link IContainerDelta delta}.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class SingleDeltaContainerEvent<E> extends Event implements IContainerEvent<E>
+{
+ private static final long serialVersionUID = 1L;
+
+ private IContainerDelta<E>[] deltas;
+
+ @SuppressWarnings("unchecked")
+ public SingleDeltaContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind)
+ {
+ super(container);
+ deltas = new IContainerDelta[] { new ContainerDelta<E>(element, kind) };
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ @SuppressWarnings("unchecked")
+ public IContainer<E> getSource()
+ {
+ return (IContainer<E>)super.getSource();
+ }
+
+ public boolean isEmpty()
+ {
+ return false;
+ }
+
+ public IContainerDelta<E>[] getDeltas()
+ {
+ return deltas;
+ }
+
+ public IContainerDelta<E> getDelta() throws IllegalStateException
+ {
+ return deltas[0];
+ }
+
+ public E getDeltaElement() throws IllegalStateException
+ {
+ return deltas[0].getElement();
+ }
+
+ public IContainerDelta.Kind getDeltaKind() throws IllegalStateException
+ {
+ return deltas[0].getKind();
+ }
+
+ public void accept(IContainerEventVisitor<E> visitor)
+ {
+ E element = deltas[0].getElement();
+
+ boolean filtered = true;
+ if (visitor instanceof Filtered<?>)
+ {
+ filtered = ((Filtered<E>)visitor).filter(element);
+ }
+
+ if (filtered)
+ {
+ switch (deltas[0].getKind())
+ {
+ case ADDED:
+ visitor.added(element);
+ break;
+ case REMOVED:
+ visitor.removed(element);
+ break;
+ }
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("ContainerEvent[source={0}, {1}={2}]", getSource(), getDeltaElement(), getDeltaKind()); //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java index bb54aba178..957c7f62a5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java @@ -1,131 +1,131 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.ContainerEvent; -import org.eclipse.net4j.util.container.IContainer; -import org.eclipse.net4j.util.container.IContainerDelta; -import org.eclipse.net4j.util.container.IContainerDelta.Kind; -import org.eclipse.net4j.util.container.SingleDeltaContainerEvent; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.Notifier; - -import java.util.Collection; -import java.util.Iterator; - -/** - * A delegating base class for {@link IContainer containers}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public abstract class AbstractDelegator<E> extends Notifier implements IContainer<E> -{ - public AbstractDelegator() - { - } - - protected void fireAddedEvent(E o) - { - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new SingleDeltaContainerEvent<E>(this, o, IContainerDelta.Kind.ADDED), listeners); - } - } - - @SuppressWarnings("unchecked") - protected void fireRemovedEvent(Object o) - { - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new SingleDeltaContainerEvent<E>(this, (E)o, IContainerDelta.Kind.REMOVED), listeners); - } - } - - @SuppressWarnings("unchecked") - protected ContainerEvent<E> createEvent(Collection<? super E> c, Kind kind) - { - ContainerEvent<E> event = new ContainerEvent<E>(this); - for (Object o : c) - { - event.addDelta((E)o, kind); - } - - return event; - } - - protected boolean dispatchEvent(ContainerEvent<E> event) - { - if (event.isEmpty()) - { - return false; - } - - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - - return true; - } - - /** - * A delegating {@link Iterator iterator}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - public class DelegatingIterator implements Iterator<E> - { - private Iterator<E> delegate; - - protected E last; - - public DelegatingIterator(Iterator<E> delegate) - { - this.delegate = delegate; - } - - public Iterator<E> getDelegate() - { - return delegate; - } - - /** - * @category READ - */ - public boolean hasNext() - { - return getDelegate().hasNext(); - } - - /** - * @category READ - */ - public E next() - { - return last = getDelegate().next(); - } - - /** - * @category WRITE - */ - public void remove() - { - getDelegate().remove(); - fireRemovedEvent(last); - last = null; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.ContainerEvent;
+import org.eclipse.net4j.util.container.IContainer;
+import org.eclipse.net4j.util.container.IContainerDelta;
+import org.eclipse.net4j.util.container.IContainerDelta.Kind;
+import org.eclipse.net4j.util.container.SingleDeltaContainerEvent;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.Notifier;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * A delegating base class for {@link IContainer containers}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public abstract class AbstractDelegator<E> extends Notifier implements IContainer<E>
+{
+ public AbstractDelegator()
+ {
+ }
+
+ protected void fireAddedEvent(E o)
+ {
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new SingleDeltaContainerEvent<E>(this, o, IContainerDelta.Kind.ADDED), listeners);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void fireRemovedEvent(Object o)
+ {
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new SingleDeltaContainerEvent<E>(this, (E)o, IContainerDelta.Kind.REMOVED), listeners);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected ContainerEvent<E> createEvent(Collection<? super E> c, Kind kind)
+ {
+ ContainerEvent<E> event = new ContainerEvent<E>(this);
+ for (Object o : c)
+ {
+ event.addDelta((E)o, kind);
+ }
+
+ return event;
+ }
+
+ protected boolean dispatchEvent(ContainerEvent<E> event)
+ {
+ if (event.isEmpty())
+ {
+ return false;
+ }
+
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+
+ return true;
+ }
+
+ /**
+ * A delegating {@link Iterator iterator}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ public class DelegatingIterator implements Iterator<E>
+ {
+ private Iterator<E> delegate;
+
+ protected E last;
+
+ public DelegatingIterator(Iterator<E> delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public Iterator<E> getDelegate()
+ {
+ return delegate;
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean hasNext()
+ {
+ return getDelegate().hasNext();
+ }
+
+ /**
+ * @category READ
+ */
+ public E next()
+ {
+ return last = getDelegate().next();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void remove()
+ {
+ getDelegate().remove();
+ fireRemovedEvent(last);
+ last = null;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java index 458658e243..dc97e2795c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java @@ -1,125 +1,125 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.ContainerEvent; -import org.eclipse.net4j.util.container.IContainerDelta; -import org.eclipse.net4j.util.event.IListener; - -import java.util.Collection; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; - -/** - * A default implementation of a {@link IContainerBlockingQueue container blocking queue}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerBlockingQueue<E> extends ContainerQueue<E> implements IContainerBlockingQueue<E> -{ - public ContainerBlockingQueue(BlockingQueue<E> delegate) - { - super(delegate); - } - - @Override - public BlockingQueue<E> getDelegate() - { - return (BlockingQueue<E>)super.getDelegate(); - } - - /** - * @category WRITE - */ - public int drainTo(Collection<? super E> c) - { - int drainTo = getDelegate().drainTo(c); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(createEvent(c, IContainerDelta.Kind.REMOVED), listeners); - } - - return drainTo; - } - - /** - * @category WRITE - */ - public int drainTo(Collection<? super E> c, int maxElements) - { - int drainTo = getDelegate().drainTo(c, maxElements); - ContainerEvent<E> event = createEvent(c, IContainerDelta.Kind.REMOVED); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - - return drainTo; - } - - /** - * @category WRITE - */ - public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException - { - boolean modified = getDelegate().offer(o, timeout, unit); - if (modified) - { - fireAddedEvent(o); - } - - return modified; - } - - /** - * @category WRITE - */ - public E poll(long timeout, TimeUnit unit) throws InterruptedException - { - E removed = getDelegate().poll(timeout, unit); - if (removed != null) - { - fireRemovedEvent(removed); - } - - return removed; - } - - /** - * @category WRITE - */ - public void put(E o) throws InterruptedException - { - getDelegate().put(o); - fireAddedEvent(o); - } - - /** - * @category READ - */ - public int remainingCapacity() - { - return getDelegate().remainingCapacity(); - } - - /** - * @category WRITE - */ - public E take() throws InterruptedException - { - E element = getDelegate().take(); - fireRemovedEvent(element); - return element; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.ContainerEvent;
+import org.eclipse.net4j.util.container.IContainerDelta;
+import org.eclipse.net4j.util.event.IListener;
+
+import java.util.Collection;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A default implementation of a {@link IContainerBlockingQueue container blocking queue}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerBlockingQueue<E> extends ContainerQueue<E> implements IContainerBlockingQueue<E>
+{
+ public ContainerBlockingQueue(BlockingQueue<E> delegate)
+ {
+ super(delegate);
+ }
+
+ @Override
+ public BlockingQueue<E> getDelegate()
+ {
+ return (BlockingQueue<E>)super.getDelegate();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public int drainTo(Collection<? super E> c)
+ {
+ int drainTo = getDelegate().drainTo(c);
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(createEvent(c, IContainerDelta.Kind.REMOVED), listeners);
+ }
+
+ return drainTo;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public int drainTo(Collection<? super E> c, int maxElements)
+ {
+ int drainTo = getDelegate().drainTo(c, maxElements);
+ ContainerEvent<E> event = createEvent(c, IContainerDelta.Kind.REMOVED);
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+
+ return drainTo;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException
+ {
+ boolean modified = getDelegate().offer(o, timeout, unit);
+ if (modified)
+ {
+ fireAddedEvent(o);
+ }
+
+ return modified;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public E poll(long timeout, TimeUnit unit) throws InterruptedException
+ {
+ E removed = getDelegate().poll(timeout, unit);
+ if (removed != null)
+ {
+ fireRemovedEvent(removed);
+ }
+
+ return removed;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void put(E o) throws InterruptedException
+ {
+ getDelegate().put(o);
+ fireAddedEvent(o);
+ }
+
+ /**
+ * @category READ
+ */
+ public int remainingCapacity()
+ {
+ return getDelegate().remainingCapacity();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public E take() throws InterruptedException
+ {
+ E element = getDelegate().take();
+ fireRemovedEvent(element);
+ return element;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java index fab939bd9e..4bc68a58ba 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java @@ -1,220 +1,220 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.ContainerEvent; -import org.eclipse.net4j.util.container.IContainerDelta; -import org.eclipse.net4j.util.event.IListener; - -import java.util.Collection; -import java.util.Iterator; - -/** - * A default implementation of a {@link IContainerCollection container collection}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerCollection<E> extends AbstractDelegator<E> implements IContainerCollection<E> -{ - private Collection<E> delegate; - - public ContainerCollection(Collection<E> delegate) - { - this.delegate = delegate; - } - - public Collection<E> getDelegate() - { - return delegate; - } - - @SuppressWarnings("unchecked") - public E[] getElements() - { - return (E[])toArray(); - } - - /** - * @category WRITE - */ - public boolean add(E o) - { - boolean modified = getDelegate().add(o); - if (modified) - { - fireAddedEvent(o); - } - - return modified; - } - - /** - * @category WRITE - */ - public boolean addAll(Collection<? extends E> c) - { - ContainerEvent<E> event = new ContainerEvent<E>(this); - for (E e : c) - { - boolean modified = getDelegate().add(e); - if (modified) - { - event.addDelta(e, IContainerDelta.Kind.ADDED); - } - } - - return dispatchEvent(event); - } - - /** - * @category WRITE - */ - public void clear() - { - if (!isEmpty()) - { - ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.REMOVED); - getDelegate().clear(); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - } - } - - /** - * @category WRITE - */ - public boolean remove(Object o) - { - boolean modified = getDelegate().remove(o); - if (modified) - { - fireRemovedEvent(o); - } - - return modified; - } - - /** - * @category WRITE - */ - @SuppressWarnings("unchecked") - public boolean removeAll(Collection<?> c) - { - ContainerEvent<E> event = new ContainerEvent<E>(this); - for (Object o : c) - { - boolean modified = getDelegate().remove(o); - if (modified) - { - event.addDelta((E)o, IContainerDelta.Kind.REMOVED); - } - } - - return dispatchEvent(event); - } - - /** - * @category WRITE - */ - @SuppressWarnings("unchecked") - public boolean retainAll(Collection<?> c) - { - ContainerEvent<E> event = new ContainerEvent<E>(this); - for (Object o : getDelegate()) - { - if (!c.contains(o)) - { - getDelegate().remove(o); - event.addDelta((E)o, IContainerDelta.Kind.REMOVED); - } - } - - return dispatchEvent(event); - } - - /** - * @category READ - */ - public boolean contains(Object o) - { - return getDelegate().contains(o); - } - - /** - * @category READ - */ - public boolean containsAll(Collection<?> c) - { - return getDelegate().containsAll(c); - } - - /** - * @category READ - */ - @Override - public boolean equals(Object o) - { - return getDelegate().equals(o); - } - - /** - * @category READ - */ - @Override - public int hashCode() - { - return getDelegate().hashCode(); - } - - /** - * @category READ - */ - public boolean isEmpty() - { - return getDelegate().isEmpty(); - } - - /** - * @category READ - */ - public Iterator<E> iterator() - { - return new DelegatingIterator(getDelegate().iterator()); - } - - /** - * @category READ - */ - public int size() - { - return getDelegate().size(); - } - - /** - * @category READ - */ - public Object[] toArray() - { - return getDelegate().toArray(); - } - - /** - * @category READ - */ - public <T> T[] toArray(T[] a) - { - return getDelegate().toArray(a); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.ContainerEvent;
+import org.eclipse.net4j.util.container.IContainerDelta;
+import org.eclipse.net4j.util.event.IListener;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+/**
+ * A default implementation of a {@link IContainerCollection container collection}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerCollection<E> extends AbstractDelegator<E> implements IContainerCollection<E>
+{
+ private Collection<E> delegate;
+
+ public ContainerCollection(Collection<E> delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public Collection<E> getDelegate()
+ {
+ return delegate;
+ }
+
+ @SuppressWarnings("unchecked")
+ public E[] getElements()
+ {
+ return (E[])toArray();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public boolean add(E o)
+ {
+ boolean modified = getDelegate().add(o);
+ if (modified)
+ {
+ fireAddedEvent(o);
+ }
+
+ return modified;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public boolean addAll(Collection<? extends E> c)
+ {
+ ContainerEvent<E> event = new ContainerEvent<E>(this);
+ for (E e : c)
+ {
+ boolean modified = getDelegate().add(e);
+ if (modified)
+ {
+ event.addDelta(e, IContainerDelta.Kind.ADDED);
+ }
+ }
+
+ return dispatchEvent(event);
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void clear()
+ {
+ if (!isEmpty())
+ {
+ ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.REMOVED);
+ getDelegate().clear();
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+ }
+ }
+
+ /**
+ * @category WRITE
+ */
+ public boolean remove(Object o)
+ {
+ boolean modified = getDelegate().remove(o);
+ if (modified)
+ {
+ fireRemovedEvent(o);
+ }
+
+ return modified;
+ }
+
+ /**
+ * @category WRITE
+ */
+ @SuppressWarnings("unchecked")
+ public boolean removeAll(Collection<?> c)
+ {
+ ContainerEvent<E> event = new ContainerEvent<E>(this);
+ for (Object o : c)
+ {
+ boolean modified = getDelegate().remove(o);
+ if (modified)
+ {
+ event.addDelta((E)o, IContainerDelta.Kind.REMOVED);
+ }
+ }
+
+ return dispatchEvent(event);
+ }
+
+ /**
+ * @category WRITE
+ */
+ @SuppressWarnings("unchecked")
+ public boolean retainAll(Collection<?> c)
+ {
+ ContainerEvent<E> event = new ContainerEvent<E>(this);
+ for (Object o : getDelegate())
+ {
+ if (!c.contains(o))
+ {
+ getDelegate().remove(o);
+ event.addDelta((E)o, IContainerDelta.Kind.REMOVED);
+ }
+ }
+
+ return dispatchEvent(event);
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean contains(Object o)
+ {
+ return getDelegate().contains(o);
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean containsAll(Collection<?> c)
+ {
+ return getDelegate().containsAll(c);
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public boolean equals(Object o)
+ {
+ return getDelegate().equals(o);
+ }
+
+ /**
+ * @category READ
+ */
+ @Override
+ public int hashCode()
+ {
+ return getDelegate().hashCode();
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean isEmpty()
+ {
+ return getDelegate().isEmpty();
+ }
+
+ /**
+ * @category READ
+ */
+ public Iterator<E> iterator()
+ {
+ return new DelegatingIterator(getDelegate().iterator());
+ }
+
+ /**
+ * @category READ
+ */
+ public int size()
+ {
+ return getDelegate().size();
+ }
+
+ /**
+ * @category READ
+ */
+ public Object[] toArray()
+ {
+ return getDelegate().toArray();
+ }
+
+ /**
+ * @category READ
+ */
+ public <T> T[] toArray(T[] a)
+ {
+ return getDelegate().toArray(a);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java index fb295347ad..5d22ec04c3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java @@ -1,218 +1,218 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.ContainerEvent; -import org.eclipse.net4j.util.container.IContainerDelta; -import org.eclipse.net4j.util.event.IListener; - -import java.util.Collection; -import java.util.List; -import java.util.ListIterator; - -/** - * A default implementation of a {@link IContainerList container list}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerList<E> extends ContainerCollection<E> implements IContainerList<E> -{ - public ContainerList(List<E> delegate) - { - super(delegate); - } - - @Override - public List<E> getDelegate() - { - return (List<E>)super.getDelegate(); - } - - /** - * @category WRITE - */ - public void add(int index, E element) - { - getDelegate().add(index, element); - fireAddedEvent(element); - } - - /** - * @category WRITE - */ - public boolean addAll(int index, Collection<? extends E> c) - { - ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.ADDED); - getDelegate().addAll(index, c); - return dispatchEvent(event); - } - - /** - * @category READ - */ - public E get(int index) - { - return getDelegate().get(index); - } - - /** - * @category READ - */ - public int indexOf(Object o) - { - return getDelegate().indexOf(o); - } - - /** - * @category READ - */ - public int lastIndexOf(Object o) - { - return getDelegate().lastIndexOf(o); - } - - /** - * @category READ - */ - public ListIterator<E> listIterator() - { - return new DelegatingListIterator(getDelegate().listIterator()); - } - - /** - * @category READ - */ - public ListIterator<E> listIterator(int index) - { - return new DelegatingListIterator(getDelegate().listIterator(index)); - } - - /** - * @category WRITE - */ - public E remove(int index) - { - E removed = getDelegate().remove(index); - if (removed != null) - { - fireRemovedEvent(removed); - } - - return removed; - } - - /** - * @category WRITE - */ - public E set(int index, E element) - { - E removed = getDelegate().set(index, element); - ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this); - event.addDelta(removed, IContainerDelta.Kind.REMOVED); - event.addDelta(element, IContainerDelta.Kind.ADDED); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - - return removed; - } - - /** - * @category READ - */ - public List<E> subList(int fromIndex, int toIndex) - { - return getDelegate().subList(fromIndex, toIndex); - } - - /** - * A delegating {@link ListIterator list iterator}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - public class DelegatingListIterator extends DelegatingIterator implements ListIterator<E> - { - public DelegatingListIterator(ListIterator<E> delegate) - { - super(delegate); - } - - @Override - public ListIterator<E> getDelegate() - { - return (ListIterator<E>)super.getDelegate(); - } - - /** - * @category WRITE - */ - public void add(E o) - { - getDelegate().add(o); - fireAddedEvent(o); - last = o; - } - - /** - * @category WRITE - */ - public void set(E o) - { - getDelegate().set(o); - ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this); - event.addDelta(last, IContainerDelta.Kind.REMOVED); - event.addDelta(o, IContainerDelta.Kind.ADDED); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - - last = o; - } - - /** - * @category READ - */ - public boolean hasPrevious() - { - return getDelegate().hasPrevious(); - } - - /** - * @category READ - */ - public int nextIndex() - { - return getDelegate().nextIndex(); - } - - /** - * @category READ - */ - public E previous() - { - return getDelegate().previous(); - } - - /** - * @category READ - */ - public int previousIndex() - { - return getDelegate().previousIndex(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.ContainerEvent;
+import org.eclipse.net4j.util.container.IContainerDelta;
+import org.eclipse.net4j.util.event.IListener;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * A default implementation of a {@link IContainerList container list}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerList<E> extends ContainerCollection<E> implements IContainerList<E>
+{
+ public ContainerList(List<E> delegate)
+ {
+ super(delegate);
+ }
+
+ @Override
+ public List<E> getDelegate()
+ {
+ return (List<E>)super.getDelegate();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void add(int index, E element)
+ {
+ getDelegate().add(index, element);
+ fireAddedEvent(element);
+ }
+
+ /**
+ * @category WRITE
+ */
+ public boolean addAll(int index, Collection<? extends E> c)
+ {
+ ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.ADDED);
+ getDelegate().addAll(index, c);
+ return dispatchEvent(event);
+ }
+
+ /**
+ * @category READ
+ */
+ public E get(int index)
+ {
+ return getDelegate().get(index);
+ }
+
+ /**
+ * @category READ
+ */
+ public int indexOf(Object o)
+ {
+ return getDelegate().indexOf(o);
+ }
+
+ /**
+ * @category READ
+ */
+ public int lastIndexOf(Object o)
+ {
+ return getDelegate().lastIndexOf(o);
+ }
+
+ /**
+ * @category READ
+ */
+ public ListIterator<E> listIterator()
+ {
+ return new DelegatingListIterator(getDelegate().listIterator());
+ }
+
+ /**
+ * @category READ
+ */
+ public ListIterator<E> listIterator(int index)
+ {
+ return new DelegatingListIterator(getDelegate().listIterator(index));
+ }
+
+ /**
+ * @category WRITE
+ */
+ public E remove(int index)
+ {
+ E removed = getDelegate().remove(index);
+ if (removed != null)
+ {
+ fireRemovedEvent(removed);
+ }
+
+ return removed;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public E set(int index, E element)
+ {
+ E removed = getDelegate().set(index, element);
+ ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this);
+ event.addDelta(removed, IContainerDelta.Kind.REMOVED);
+ event.addDelta(element, IContainerDelta.Kind.ADDED);
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+
+ return removed;
+ }
+
+ /**
+ * @category READ
+ */
+ public List<E> subList(int fromIndex, int toIndex)
+ {
+ return getDelegate().subList(fromIndex, toIndex);
+ }
+
+ /**
+ * A delegating {@link ListIterator list iterator}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ public class DelegatingListIterator extends DelegatingIterator implements ListIterator<E>
+ {
+ public DelegatingListIterator(ListIterator<E> delegate)
+ {
+ super(delegate);
+ }
+
+ @Override
+ public ListIterator<E> getDelegate()
+ {
+ return (ListIterator<E>)super.getDelegate();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void add(E o)
+ {
+ getDelegate().add(o);
+ fireAddedEvent(o);
+ last = o;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void set(E o)
+ {
+ getDelegate().set(o);
+ ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this);
+ event.addDelta(last, IContainerDelta.Kind.REMOVED);
+ event.addDelta(o, IContainerDelta.Kind.ADDED);
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+
+ last = o;
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean hasPrevious()
+ {
+ return getDelegate().hasPrevious();
+ }
+
+ /**
+ * @category READ
+ */
+ public int nextIndex()
+ {
+ return getDelegate().nextIndex();
+ }
+
+ /**
+ * @category READ
+ */
+ public E previous()
+ {
+ return getDelegate().previous();
+ }
+
+ /**
+ * @category READ
+ */
+ public int previousIndex()
+ {
+ return getDelegate().previousIndex();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java index 4e134d4706..be111fc73f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java @@ -1,209 +1,209 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.collection.MapEntry; -import org.eclipse.net4j.util.container.ContainerEvent; -import org.eclipse.net4j.util.container.IContainerDelta; -import org.eclipse.net4j.util.event.IListener; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * A default implementation of a {@link IContainerMap container map}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerMap<K, V> extends AbstractDelegator<Map.Entry<K, V>> implements IContainerMap<K, V> -{ - private Map<K, V> delegate; - - public ContainerMap(Map<K, V> delegate) - { - this.delegate = delegate; - } - - public Map<K, V> getDelegate() - { - return delegate; - } - - /** - * @category WRITE - */ - public void clear() - { - if (!isEmpty()) - { - ContainerEvent<Map.Entry<K, V>> event = createEvent(getDelegate().entrySet(), IContainerDelta.Kind.REMOVED); - getDelegate().clear(); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - } - } - - /** - * @category WRITE - */ - public V put(K key, V value) - { - ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this); - V removed = getDelegate().put(key, value); - if (removed != null) - { - event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED); - } - - event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(event, listeners); - } - - return removed; - } - - /** - * @category WRITE - */ - public void putAll(Map<? extends K, ? extends V> t) - { - ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this); - Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator(); - while (i.hasNext()) - { - Entry<? extends K, ? extends V> entry = i.next(); - K key = entry.getKey(); - V value = entry.getValue(); - V removed = getDelegate().put(key, value); - if (removed != null) - { - event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED); - } - - event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED); - } - - dispatchEvent(event); - } - - /** - * @category WRITE - */ - public V remove(Object key) - { - V removed = getDelegate().remove(key); - if (removed != null) - { - fireRemovedEvent(new ContainerMapEntry<Object, V>(key, removed)); - } - - return removed; - } - - /** - * @category READ - */ - public boolean containsKey(Object key) - { - return getDelegate().containsKey(key); - } - - /** - * @category READ - */ - public boolean containsValue(Object value) - { - return getDelegate().containsValue(value); - } - - /** - * @category READ - */ - public V get(Object key) - { - return getDelegate().get(key); - } - - /** - * @category READ - */ - public int size() - { - return getDelegate().size(); - } - - /** - * @category READ - */ - @SuppressWarnings("unchecked") - public Map.Entry<K, V>[] getElements() - { - return (Entry<K, V>[])getDelegate().entrySet().toArray(); - } - - /** - * @category READ - */ - public boolean isEmpty() - { - return getDelegate().isEmpty(); - } - - /** - * @category READ - */ - public Set<Map.Entry<K, V>> entrySet() - { - return new ContainerSet<Map.Entry<K, V>>(getDelegate().entrySet()); - } - - /** - * @category READ - */ - public Set<K> keySet() - { - return new ContainerSet<K>(getDelegate().keySet()); - } - - /** - * @category READ - */ - public Collection<V> values() - { - return new ContainerCollection<V>(getDelegate().values()); - } - - /** - * @author Eike Stepper - */ - private static final class ContainerMapEntry<K, V> extends MapEntry<K, V> - { - public ContainerMapEntry(K key, V value) - { - super(key, value); - } - - @Override - public V setValue(V value) - { - throw new UnsupportedOperationException(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.collection.MapEntry;
+import org.eclipse.net4j.util.container.ContainerEvent;
+import org.eclipse.net4j.util.container.IContainerDelta;
+import org.eclipse.net4j.util.event.IListener;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A default implementation of a {@link IContainerMap container map}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerMap<K, V> extends AbstractDelegator<Map.Entry<K, V>> implements IContainerMap<K, V>
+{
+ private Map<K, V> delegate;
+
+ public ContainerMap(Map<K, V> delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public Map<K, V> getDelegate()
+ {
+ return delegate;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void clear()
+ {
+ if (!isEmpty())
+ {
+ ContainerEvent<Map.Entry<K, V>> event = createEvent(getDelegate().entrySet(), IContainerDelta.Kind.REMOVED);
+ getDelegate().clear();
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+ }
+ }
+
+ /**
+ * @category WRITE
+ */
+ public V put(K key, V value)
+ {
+ ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this);
+ V removed = getDelegate().put(key, value);
+ if (removed != null)
+ {
+ event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED);
+ }
+
+ event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED);
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(event, listeners);
+ }
+
+ return removed;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public void putAll(Map<? extends K, ? extends V> t)
+ {
+ ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this);
+ Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator();
+ while (i.hasNext())
+ {
+ Entry<? extends K, ? extends V> entry = i.next();
+ K key = entry.getKey();
+ V value = entry.getValue();
+ V removed = getDelegate().put(key, value);
+ if (removed != null)
+ {
+ event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED);
+ }
+
+ event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED);
+ }
+
+ dispatchEvent(event);
+ }
+
+ /**
+ * @category WRITE
+ */
+ public V remove(Object key)
+ {
+ V removed = getDelegate().remove(key);
+ if (removed != null)
+ {
+ fireRemovedEvent(new ContainerMapEntry<Object, V>(key, removed));
+ }
+
+ return removed;
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean containsKey(Object key)
+ {
+ return getDelegate().containsKey(key);
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean containsValue(Object value)
+ {
+ return getDelegate().containsValue(value);
+ }
+
+ /**
+ * @category READ
+ */
+ public V get(Object key)
+ {
+ return getDelegate().get(key);
+ }
+
+ /**
+ * @category READ
+ */
+ public int size()
+ {
+ return getDelegate().size();
+ }
+
+ /**
+ * @category READ
+ */
+ @SuppressWarnings("unchecked")
+ public Map.Entry<K, V>[] getElements()
+ {
+ return (Entry<K, V>[])getDelegate().entrySet().toArray();
+ }
+
+ /**
+ * @category READ
+ */
+ public boolean isEmpty()
+ {
+ return getDelegate().isEmpty();
+ }
+
+ /**
+ * @category READ
+ */
+ public Set<Map.Entry<K, V>> entrySet()
+ {
+ return new ContainerSet<Map.Entry<K, V>>(getDelegate().entrySet());
+ }
+
+ /**
+ * @category READ
+ */
+ public Set<K> keySet()
+ {
+ return new ContainerSet<K>(getDelegate().keySet());
+ }
+
+ /**
+ * @category READ
+ */
+ public Collection<V> values()
+ {
+ return new ContainerCollection<V>(getDelegate().values());
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class ContainerMapEntry<K, V> extends MapEntry<K, V>
+ {
+ public ContainerMapEntry(K key, V value)
+ {
+ super(key, value);
+ }
+
+ @Override
+ public V setValue(V value)
+ {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java index a422080d03..2a6a746730 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java @@ -1,91 +1,91 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import java.util.Queue; - -/** - * A default implementation of a {@link IContainerQueue container queue}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerQueue<E> extends ContainerCollection<E> implements IContainerQueue<E> -{ - public ContainerQueue(Queue<E> delegate) - { - super(delegate); - } - - @Override - public Queue<E> getDelegate() - { - return (Queue<E>)super.getDelegate(); - } - - /** - * @category READ - */ - public E element() - { - return getDelegate().element(); - } - - /** - * @category WRITE - */ - public boolean offer(E o) - { - boolean modified = getDelegate().offer(o); - if (modified) - { - fireAddedEvent(o); - } - - return modified; - } - - /** - * @category READ - */ - public E peek() - { - return getDelegate().element(); - } - - /** - * @category WRITE - */ - public E poll() - { - E removed = getDelegate().poll(); - if (removed != null) - { - fireRemovedEvent(removed); - } - - return removed; - } - - /** - * @category WRITE - */ - public E remove() - { - E removed = getDelegate().remove(); - if (removed != null) - { - fireRemovedEvent(removed); - } - - return removed; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import java.util.Queue;
+
+/**
+ * A default implementation of a {@link IContainerQueue container queue}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerQueue<E> extends ContainerCollection<E> implements IContainerQueue<E>
+{
+ public ContainerQueue(Queue<E> delegate)
+ {
+ super(delegate);
+ }
+
+ @Override
+ public Queue<E> getDelegate()
+ {
+ return (Queue<E>)super.getDelegate();
+ }
+
+ /**
+ * @category READ
+ */
+ public E element()
+ {
+ return getDelegate().element();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public boolean offer(E o)
+ {
+ boolean modified = getDelegate().offer(o);
+ if (modified)
+ {
+ fireAddedEvent(o);
+ }
+
+ return modified;
+ }
+
+ /**
+ * @category READ
+ */
+ public E peek()
+ {
+ return getDelegate().element();
+ }
+
+ /**
+ * @category WRITE
+ */
+ public E poll()
+ {
+ E removed = getDelegate().poll();
+ if (removed != null)
+ {
+ fireRemovedEvent(removed);
+ }
+
+ return removed;
+ }
+
+ /**
+ * @category WRITE
+ */
+ public E remove()
+ {
+ E removed = getDelegate().remove();
+ if (removed != null)
+ {
+ fireRemovedEvent(removed);
+ }
+
+ return removed;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java index baec772f25..5b3bf8e7cb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java @@ -1,33 +1,33 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import java.util.Set; - -/** - * A default implementation of a {@link IContainerSet container set}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerSet<E> extends ContainerCollection<E> implements IContainerSet<E> -{ - public ContainerSet(Set<E> delegate) - { - super(delegate); - } - - @Override - public Set<E> getDelegate() - { - return (Set<E>)super.getDelegate(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import java.util.Set;
+
+/**
+ * A default implementation of a {@link IContainerSet container set}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerSet<E> extends ContainerCollection<E> implements IContainerSet<E>
+{
+ public ContainerSet(Set<E> delegate)
+ {
+ super(delegate);
+ }
+
+ @Override
+ public Set<E> getDelegate()
+ {
+ return (Set<E>)super.getDelegate();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java index d1211849a7..4ffb4b891d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java @@ -1,82 +1,82 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import java.util.Comparator; -import java.util.SortedSet; - -/** - * A default implementation of a {@link IContainerSortedSet container sorted set}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class ContainerSortedSet<E> extends ContainerSet<E> implements IContainerSortedSet<E> -{ - public ContainerSortedSet(SortedSet<E> delegate) - { - super(delegate); - } - - @Override - public SortedSet<E> getDelegate() - { - return (SortedSet<E>)super.getDelegate(); - } - - /** - * @category READ - */ - public Comparator<? super E> comparator() - { - return getDelegate().comparator(); - } - - /** - * @category READ - */ - public E first() - { - return getDelegate().first(); - } - - /** - * @category READ - */ - public E last() - { - return getDelegate().last(); - } - - /** - * @category READ - */ - public SortedSet<E> headSet(E toElement) - { - return getDelegate().headSet(toElement); - } - - /** - * @category READ - */ - public SortedSet<E> subSet(E fromElement, E toElement) - { - return getDelegate().subSet(fromElement, toElement); - } - - /** - * @category READ - */ - public SortedSet<E> tailSet(E fromElement) - { - return getDelegate().tailSet(fromElement); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import java.util.Comparator;
+import java.util.SortedSet;
+
+/**
+ * A default implementation of a {@link IContainerSortedSet container sorted set}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class ContainerSortedSet<E> extends ContainerSet<E> implements IContainerSortedSet<E>
+{
+ public ContainerSortedSet(SortedSet<E> delegate)
+ {
+ super(delegate);
+ }
+
+ @Override
+ public SortedSet<E> getDelegate()
+ {
+ return (SortedSet<E>)super.getDelegate();
+ }
+
+ /**
+ * @category READ
+ */
+ public Comparator<? super E> comparator()
+ {
+ return getDelegate().comparator();
+ }
+
+ /**
+ * @category READ
+ */
+ public E first()
+ {
+ return getDelegate().first();
+ }
+
+ /**
+ * @category READ
+ */
+ public E last()
+ {
+ return getDelegate().last();
+ }
+
+ /**
+ * @category READ
+ */
+ public SortedSet<E> headSet(E toElement)
+ {
+ return getDelegate().headSet(toElement);
+ }
+
+ /**
+ * @category READ
+ */
+ public SortedSet<E> subSet(E fromElement, E toElement)
+ {
+ return getDelegate().subSet(fromElement, toElement);
+ }
+
+ /**
+ * @category READ
+ */
+ public SortedSet<E> tailSet(E fromElement)
+ {
+ return getDelegate().tailSet(fromElement);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerBlockingQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerBlockingQueue.java index af304bcf28..b9171525a3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerBlockingQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerBlockingQueue.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import java.util.concurrent.BlockingQueue; - -/** - * @author Eike Stepper - */ -public interface IContainerBlockingQueue<E> extends IContainerQueue<E>, BlockingQueue<E> -{ - public BlockingQueue<E> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import java.util.concurrent.BlockingQueue;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IContainerBlockingQueue<E> extends IContainerQueue<E>, BlockingQueue<E>
+{
+ public BlockingQueue<E> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java index a2e5521371..100d57b670 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.Collection; - -/** - * A {@link IContainer container} that is a {@link Collection}. - * - * @author Eike Stepper - */ -public interface IContainerCollection<E> extends IContainer<E>, Collection<E> -{ - public Collection<E> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.Collection;
+
+/**
+ * A {@link IContainer container} that is a {@link Collection}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerCollection<E> extends IContainer<E>, Collection<E>
+{
+ public Collection<E> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java index c8fa2167d4..2bc34b3401 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.List; - -/** - * A {@link IContainer container} that is a {@link List}. - * - * @author Eike Stepper - */ -public interface IContainerList<E> extends IContainerCollection<E>, List<E> -{ - public List<E> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.List;
+
+/**
+ * A {@link IContainer container} that is a {@link List}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerList<E> extends IContainerCollection<E>, List<E>
+{
+ public List<E> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java index 708dc31b89..7a69f5248f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.Map; - -/** - * A {@link IContainer container} (of {@link java.util.Map.Entry map entries}) that is a {@link Map}. - * - * @author Eike Stepper - */ -public interface IContainerMap<K, V> extends IContainer<Map.Entry<K, V>>, Map<K, V> -{ - public Map<K, V> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.Map;
+
+/**
+ * A {@link IContainer container} (of {@link java.util.Map.Entry map entries}) that is a {@link Map}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerMap<K, V> extends IContainer<Map.Entry<K, V>>, Map<K, V>
+{
+ public Map<K, V> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java index ea6b48bd67..e552d2ee16 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.Queue; - -/** - * A {@link IContainer container} that is a {@link Queue}. - * - * @author Eike Stepper - */ -public interface IContainerQueue<E> extends IContainerCollection<E>, Queue<E> -{ - public Queue<E> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.Queue;
+
+/**
+ * A {@link IContainer container} that is a {@link Queue}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerQueue<E> extends IContainerCollection<E>, Queue<E>
+{
+ public Queue<E> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSet.java index 57aa76abc3..8950981e9e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSet.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.Set; - -/** - * A {@link IContainer container} that is a {@link Set}. - * - * @author Eike Stepper - */ -public interface IContainerSet<E> extends IContainerCollection<E>, Set<E> -{ - public Set<E> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.Set;
+
+/**
+ * A {@link IContainer container} that is a {@link Set}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerSet<E> extends IContainerCollection<E>, Set<E>
+{
+ public Set<E> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java index cb8cd2d21b..402b5b3a9a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.container.delegate; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.SortedSet; - -/** - * A {@link IContainer container} that is a {@link SortedSet}. - * - * @author Eike Stepper - */ -public interface IContainerSortedSet<E> extends IContainerSet<E>, SortedSet<E> -{ - public SortedSet<E> getDelegate(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.container.delegate;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.SortedSet;
+
+/**
+ * A {@link IContainer container} that is a {@link SortedSet}.
+ *
+ * @author Eike Stepper
+ */
+public interface IContainerSortedSet<E> extends IContainerSet<E>, SortedSet<E>
+{
+ public SortedSet<E> getDelegate();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java index 93f2bd5ec6..52c772fe30 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java index fa7741d80f..9e67eadd66 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java index c630da28d8..e5539396fd 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -import java.text.MessageFormat; -import java.util.EventObject; - -/** - * A default implementation of an {@link IEvent event}. - * - * @author Eike Stepper - */ -public class Event extends EventObject implements IEvent -{ - private static final long serialVersionUID = 1L; - - public Event(INotifier notifier) - { - super(notifier); - } - - @Override - public INotifier getSource() - { - return (INotifier)source; - } - - @Override - public String toString() - { - String params = formatAdditionalParameters(); - params = params == null ? "" : ", " + params; - return MessageFormat.format("{0}[source={1}{2}]", getClass().getSimpleName(), getSource(), params); - } - - /** - * @since 3.0 - */ - protected String formatAdditionalParameters() - { - return null; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+import java.text.MessageFormat;
+import java.util.EventObject;
+
+/**
+ * A default implementation of an {@link IEvent event}.
+ *
+ * @author Eike Stepper
+ */
+public class Event extends EventObject implements IEvent
+{
+ private static final long serialVersionUID = 1L;
+
+ public Event(INotifier notifier)
+ {
+ super(notifier);
+ }
+
+ @Override
+ public INotifier getSource()
+ {
+ return (INotifier)source;
+ }
+
+ @Override
+ public String toString()
+ {
+ String params = formatAdditionalParameters();
+ params = params == null ? "" : ", " + params;
+ return MessageFormat.format("{0}[source={1}{2}]", getClass().getSimpleName(), getSource(), params);
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected String formatAdditionalParameters()
+ {
+ return null;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/EventUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/EventUtil.java index 461b09ce31..9d0d8076ea 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/EventUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/EventUtil.java @@ -1,61 +1,61 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -/** - * Various static helper methods for dealing with {@link IEvent events}, {@link INotifier notifiers} and - * {@link IListener listeners}. - * - * @author Eike Stepper - */ -public final class EventUtil -{ - /** - * @since 3.0 - */ - public static final IListener[] NO_LISTENERS = {}; - - private EventUtil() - { - } - - public static boolean addListener(Object notifier, IListener listener) - { - if (notifier instanceof INotifier) - { - ((INotifier)notifier).addListener(listener); - return true; - } - - return false; - } - - public static boolean removeListener(Object notifier, IListener listener) - { - if (notifier instanceof INotifier) - { - ((INotifier)notifier).removeListener(listener); - return true; - } - - return false; - } - - public static IListener[] getListeners(Object notifier) - { - if (notifier instanceof INotifier) - { - return ((INotifier)notifier).getListeners(); - } - - return NO_LISTENERS; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+/**
+ * Various static helper methods for dealing with {@link IEvent events}, {@link INotifier notifiers} and
+ * {@link IListener listeners}.
+ *
+ * @author Eike Stepper
+ */
+public final class EventUtil
+{
+ /**
+ * @since 3.0
+ */
+ public static final IListener[] NO_LISTENERS = {};
+
+ private EventUtil()
+ {
+ }
+
+ public static boolean addListener(Object notifier, IListener listener)
+ {
+ if (notifier instanceof INotifier)
+ {
+ ((INotifier)notifier).addListener(listener);
+ return true;
+ }
+
+ return false;
+ }
+
+ public static boolean removeListener(Object notifier, IListener listener)
+ {
+ if (notifier instanceof INotifier)
+ {
+ ((INotifier)notifier).removeListener(listener);
+ return true;
+ }
+
+ return false;
+ }
+
+ public static IListener[] getListeners(Object notifier)
+ {
+ if (notifier instanceof INotifier)
+ {
+ return ((INotifier)notifier).getListeners();
+ }
+
+ return NO_LISTENERS;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java index 2483016c43..b5803f6332 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java @@ -1,52 +1,52 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -import java.util.concurrent.ExecutorService; - -/** - * Deprecated. - * - * @author Eike Stepper - * @since 2.0 - * @apiviz.exclude - */ -@Deprecated -public class ExecutorServiceNotifier extends Notifier -{ - private ExecutorService notificationExecutorService; - - public ExecutorServiceNotifier() - { - } - - @Override - public ExecutorService getNotificationService() - { - return notificationExecutorService; - } - - public void setNotificationExecutorService(ExecutorService notificationExecutorService) - { - this.notificationExecutorService = notificationExecutorService; - } - - /** - * Deprecated. - * - * @author Eike Stepper - * @apiviz.exclude - */ - @Deprecated - public static class ThreadPool extends ExecutorServiceNotifier - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+import java.util.concurrent.ExecutorService;
+
+/**
+ * Deprecated.
+ *
+ * @author Eike Stepper
+ * @since 2.0
+ * @apiviz.exclude
+ */
+@Deprecated
+public class ExecutorServiceNotifier extends Notifier
+{
+ private ExecutorService notificationExecutorService;
+
+ public ExecutorServiceNotifier()
+ {
+ }
+
+ @Override
+ public ExecutorService getNotificationService()
+ {
+ return notificationExecutorService;
+ }
+
+ public void setNotificationExecutorService(ExecutorService notificationExecutorService)
+ {
+ this.notificationExecutorService = notificationExecutorService;
+ }
+
+ /**
+ * Deprecated.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ @Deprecated
+ public static class ThreadPool extends ExecutorServiceNotifier
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java index a63018fada..e189d866c2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -/** - * An event that is fired from a {@link INotifier notifier} and can be handled by {@link IListener listeners}. - * - * @author Eike Stepper - * @apiviz.landmark - */ -public interface IEvent -{ - public INotifier getSource(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+/**
+ * An event that is fired from a {@link INotifier notifier} and can be handled by {@link IListener listeners}.
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ */
+public interface IEvent
+{
+ public INotifier getSource();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java index 0fd814b6ee..c3dd0e557a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -import java.util.EventListener; - -/** - * A callback interface that {@link INotifier notifiers} use to pass {@link IEvent events} to. - * - * @author Eike Stepper - * @apiviz.landmark - */ -public interface IListener extends EventListener -{ - public void notifyEvent(IEvent event); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+import java.util.EventListener;
+
+/**
+ * A callback interface that {@link INotifier notifiers} use to pass {@link IEvent events} to.
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ */
+public interface IListener extends EventListener
+{
+ public void notifyEvent(IEvent event);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java index c742355fd1..c7c4c09d19 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -/** - * An entity that a number of {@link IListener listeners} can be registered with and that can fire {@link IEvent events} - * to these registered listeners. - * <p> - * Implementors are encouraged to document the event types that they are able to fire and that their listeners may want - * to receive and handle. - * <p> - * Implementors may want to extend {@link Notifier} instead of implementing this interface directly. - * - * @author Eike Stepper - * @apiviz.landmark - * @apiviz.owns {@link IListener} - - listeners - * @apiviz.uses {@link IEvent} - - fires - */ -public interface INotifier -{ - /** - * Adds a listener to this notifier. - * <p> - * Depending on the implementation duplicate listeners may lead to duplicate event delivery or not. Implementors are - * encouraged to prevent events from being delivered more than once to the same listener, - */ - public void addListener(IListener listener); - - /** - * Removes a listener from this notifier. - */ - public void removeListener(IListener listener); - - /** - * Returns <code>true</code> if one or more listeners are registered with this notifier, <code>false</code> otherwise. - * - * @since 3.0 - */ - public boolean hasListeners(); - - /** - * Returns the listeners that are registered with this notifier. - * <p> - * Depending on the implementation duplicate listeners may be contained in the returned array. - * - * @since 3.0 - */ - public IListener[] getListeners(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+/**
+ * An entity that a number of {@link IListener listeners} can be registered with and that can fire {@link IEvent events}
+ * to these registered listeners.
+ * <p>
+ * Implementors are encouraged to document the event types that they are able to fire and that their listeners may want
+ * to receive and handle.
+ * <p>
+ * Implementors may want to extend {@link Notifier} instead of implementing this interface directly.
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ * @apiviz.owns {@link IListener} - - listeners
+ * @apiviz.uses {@link IEvent} - - fires
+ */
+public interface INotifier
+{
+ /**
+ * Adds a listener to this notifier.
+ * <p>
+ * Depending on the implementation duplicate listeners may lead to duplicate event delivery or not. Implementors are
+ * encouraged to prevent events from being delivered more than once to the same listener,
+ */
+ public void addListener(IListener listener);
+
+ /**
+ * Removes a listener from this notifier.
+ */
+ public void removeListener(IListener listener);
+
+ /**
+ * Returns <code>true</code> if one or more listeners are registered with this notifier, <code>false</code> otherwise.
+ *
+ * @since 3.0
+ */
+ public boolean hasListeners();
+
+ /**
+ * Returns the listeners that are registered with this notifier.
+ * <p>
+ * Depending on the implementation duplicate listeners may be contained in the returned array.
+ *
+ * @since 3.0
+ */
+ public IListener[] getListeners();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java index ea7bedfb4f..3e6bd7335d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java @@ -1,155 +1,155 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.event; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.CheckUtil; -import org.eclipse.net4j.util.collection.ConcurrentArray; - -import java.util.concurrent.ExecutorService; - -/** - * A default implementation of a {@link INotifier notifier}. - * - * @author Eike Stepper - * @since 3.0 - */ -public class Notifier implements INotifier -{ - private ConcurrentArray<IListener> listeners = new ConcurrentArray<IListener>() - { - @Override - protected IListener[] newArray(int length) - { - return new IListener[length]; - } - - @Override - protected void firstElementAdded() - { - firstListenerAdded(); - } - - @Override - protected void lastElementRemoved() - { - lastListenerRemoved(); - } - }; - - public Notifier() - { - } - - public void addListener(IListener listener) - { - CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$ - listeners.add(listener); - } - - public void removeListener(IListener listener) - { - CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$ - listeners.remove(listener); - } - - public boolean hasListeners() - { - return listeners.get() != null; - } - - public IListener[] getListeners() - { - return listeners.get(); - } - - /** - * @since 3.2 - */ - public void fireEvent() - { - fireEvent(new Event(this)); - } - - public void fireEvent(IEvent event) - { - if (event != null) - { - fireEvent(event, getListeners()); - } - } - - /** - * @since 3.0 - */ - public void fireEvent(final IEvent event, final IListener[] listeners) - { - if (event != null && listeners != null) - { - ExecutorService notificationService = getNotificationService(); - if (notificationService != null) - { - notificationService.execute(new Runnable() - { - public void run() - { - fireEventSafe(event, listeners); - } - }); - } - else - { - fireEventSafe(event, listeners); - } - } - } - - /** - * @since 3.0 - */ - protected ExecutorService getNotificationService() - { - return null; - } - - /** - * @since 3.0 - */ - protected void firstListenerAdded() - { - } - - /** - * @since 3.0 - */ - protected void lastListenerRemoved() - { - } - - private static void fireEventSafe(IEvent event, IListener[] listeners) - { - for (int i = 0; i < listeners.length; i++) - { - try - { - IListener listener = listeners[i]; - if (listener != null) - { - listener.notifyEvent(event); - } - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.event;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.CheckUtil;
+import org.eclipse.net4j.util.collection.ConcurrentArray;
+
+import java.util.concurrent.ExecutorService;
+
+/**
+ * A default implementation of a {@link INotifier notifier}.
+ *
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public class Notifier implements INotifier
+{
+ private ConcurrentArray<IListener> listeners = new ConcurrentArray<IListener>()
+ {
+ @Override
+ protected IListener[] newArray(int length)
+ {
+ return new IListener[length];
+ }
+
+ @Override
+ protected void firstElementAdded()
+ {
+ firstListenerAdded();
+ }
+
+ @Override
+ protected void lastElementRemoved()
+ {
+ lastListenerRemoved();
+ }
+ };
+
+ public Notifier()
+ {
+ }
+
+ public void addListener(IListener listener)
+ {
+ CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$
+ listeners.add(listener);
+ }
+
+ public void removeListener(IListener listener)
+ {
+ CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$
+ listeners.remove(listener);
+ }
+
+ public boolean hasListeners()
+ {
+ return listeners.get() != null;
+ }
+
+ public IListener[] getListeners()
+ {
+ return listeners.get();
+ }
+
+ /**
+ * @since 3.2
+ */
+ public void fireEvent()
+ {
+ fireEvent(new Event(this));
+ }
+
+ public void fireEvent(IEvent event)
+ {
+ if (event != null)
+ {
+ fireEvent(event, getListeners());
+ }
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void fireEvent(final IEvent event, final IListener[] listeners)
+ {
+ if (event != null && listeners != null)
+ {
+ ExecutorService notificationService = getNotificationService();
+ if (notificationService != null)
+ {
+ notificationService.execute(new Runnable()
+ {
+ public void run()
+ {
+ fireEventSafe(event, listeners);
+ }
+ });
+ }
+ else
+ {
+ fireEventSafe(event, listeners);
+ }
+ }
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected ExecutorService getNotificationService()
+ {
+ return null;
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected void firstListenerAdded()
+ {
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected void lastListenerRemoved()
+ {
+ }
+
+ private static void fireEventSafe(IEvent event, IListener[] listeners)
+ {
+ for (int i = 0; i < listeners.length; i++)
+ {
+ try
+ {
+ IListener listener = listeners[i];
+ if (listener != null)
+ {
+ listener.notifyEvent(event);
+ }
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java index ae10a7a7c6..e235fcb2f7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java index b8acaaafce..d0c231b62f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java index b7a1087f04..96b63150ef 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java index bb9f5587b8..dd20a98445 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java @@ -1,59 +1,59 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -import java.text.MessageFormat; - -/** - * A default implementation of a {@link IFactory factory}. - * - * @author Eike Stepper - */ -public abstract class Factory implements IFactory -{ - private FactoryKey key; - - public Factory(FactoryKey key) - { - this.key = key; - } - - public Factory(String productGroup, String type) - { - this(new FactoryKey(productGroup, type)); - } - - public FactoryKey getKey() - { - return key; - } - - public String getProductGroup() - { - return key.getProductGroup(); - } - - public String getType() - { - return key.getType(); - } - - public String getDescriptionFor(Object product) - { - return null; - } - - @Override - public String toString() - { - return MessageFormat.format("Factory[{0}, {1}]", getProductGroup(), getType()); //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+import java.text.MessageFormat;
+
+/**
+ * A default implementation of a {@link IFactory factory}.
+ *
+ * @author Eike Stepper
+ */
+public abstract class Factory implements IFactory
+{
+ private FactoryKey key;
+
+ public Factory(FactoryKey key)
+ {
+ this.key = key;
+ }
+
+ public Factory(String productGroup, String type)
+ {
+ this(new FactoryKey(productGroup, type));
+ }
+
+ public FactoryKey getKey()
+ {
+ return key;
+ }
+
+ public String getProductGroup()
+ {
+ return key.getProductGroup();
+ }
+
+ public String getType()
+ {
+ return key.getType();
+ }
+
+ public String getDescriptionFor(Object product)
+ {
+ return null;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("Factory[{0}, {1}]", getProductGroup(), getType()); //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java index 60993b763e..06da57ccef 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java @@ -1,42 +1,42 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -/** - * Thrown from {@link FactoryDescriptor#createFactory()} if a {@link IFactory factory} could not be created. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class FactoryCreationException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public FactoryCreationException() - { - } - - public FactoryCreationException(String message) - { - super(message); - } - - public FactoryCreationException(Throwable cause) - { - super(cause); - } - - public FactoryCreationException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+/**
+ * Thrown from {@link FactoryDescriptor#createFactory()} if a {@link IFactory factory} could not be created.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class FactoryCreationException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public FactoryCreationException()
+ {
+ }
+
+ public FactoryCreationException(String message)
+ {
+ super(message);
+ }
+
+ public FactoryCreationException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public FactoryCreationException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java index ec278029eb..51e3030a46 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java @@ -1,86 +1,86 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IConfigurationElement; -import org.eclipse.core.runtime.IExtensionRegistry; - -/** - * A {@link IFactory factory} that delegates to an {@link IExtensionRegistry extension registry} contribution. - * <p> - * Example contribution: - * - * <pre> - * <extension - * point="org.eclipse.net4j.util.factories"> - * <factory - * class="org.eclipse.net4j.util.concurrent.TimerLifecycle$DaemonFactory" - * productGroup="org.eclipse.net4j.util.timers" - * type="daemon"/> - * </extension> - * </pre> - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class FactoryDescriptor extends Factory -{ - private static final String ATTR_PRODUCT_GROUP = "productGroup"; //$NON-NLS-1$ - - private static final String ATTR_TYPE = "type"; //$NON-NLS-1$ - - private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ - - private IConfigurationElement configurationElement; - - public FactoryDescriptor(IConfigurationElement configurationElement) - { - super(createFactoryKey(configurationElement)); - this.configurationElement = configurationElement; - } - - public IConfigurationElement getConfigurationElement() - { - return configurationElement; - } - - public IFactory createFactory() - { - try - { - return (IFactory)configurationElement.createExecutableExtension(ATTR_CLASS); - } - catch (CoreException ex) - { - throw new FactoryCreationException(ex); - } - } - - public Object create(String description) - { - throw new UnsupportedOperationException(); - } - - @Override - public String getDescriptionFor(Object product) - { - throw new UnsupportedOperationException(); - } - - private static FactoryKey createFactoryKey(IConfigurationElement element) - { - String productGroup = element.getAttribute(ATTR_PRODUCT_GROUP); - String type = element.getAttribute(ATTR_TYPE); - return new FactoryKey(productGroup, type); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+import org.eclipse.core.runtime.CoreException;
+import org.eclipse.core.runtime.IConfigurationElement;
+import org.eclipse.core.runtime.IExtensionRegistry;
+
+/**
+ * A {@link IFactory factory} that delegates to an {@link IExtensionRegistry extension registry} contribution.
+ * <p>
+ * Example contribution:
+ *
+ * <pre>
+ * <extension
+ * point="org.eclipse.net4j.util.factories">
+ * <factory
+ * class="org.eclipse.net4j.util.concurrent.TimerLifecycle$DaemonFactory"
+ * productGroup="org.eclipse.net4j.util.timers"
+ * type="daemon"/>
+ * </extension>
+ * </pre>
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class FactoryDescriptor extends Factory
+{
+ private static final String ATTR_PRODUCT_GROUP = "productGroup"; //$NON-NLS-1$
+
+ private static final String ATTR_TYPE = "type"; //$NON-NLS-1$
+
+ private static final String ATTR_CLASS = "class"; //$NON-NLS-1$
+
+ private IConfigurationElement configurationElement;
+
+ public FactoryDescriptor(IConfigurationElement configurationElement)
+ {
+ super(createFactoryKey(configurationElement));
+ this.configurationElement = configurationElement;
+ }
+
+ public IConfigurationElement getConfigurationElement()
+ {
+ return configurationElement;
+ }
+
+ public IFactory createFactory()
+ {
+ try
+ {
+ return (IFactory)configurationElement.createExecutableExtension(ATTR_CLASS);
+ }
+ catch (CoreException ex)
+ {
+ throw new FactoryCreationException(ex);
+ }
+ }
+
+ public Object create(String description)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String getDescriptionFor(Object product)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ private static FactoryKey createFactoryKey(IConfigurationElement element)
+ {
+ String productGroup = element.getAttribute(ATTR_PRODUCT_GROUP);
+ String type = element.getAttribute(ATTR_TYPE);
+ return new FactoryKey(productGroup, type);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java index 4604d52fd4..e61b81e7af 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java @@ -1,98 +1,98 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -import org.eclipse.net4j.util.ObjectUtil; -import org.eclipse.net4j.util.StringUtil; - -import java.io.Serializable; -import java.text.MessageFormat; - -/** - * A default implementation of a {@link IFactoryKey factory key}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public final class FactoryKey implements IFactoryKey, Serializable, Comparable<FactoryKey> -{ - private static final long serialVersionUID = 1L; - - private String productGroup; - - private String type; - - public FactoryKey(String productGroup, String type) - { - this.productGroup = productGroup; - this.type = type; - } - - public String getProductGroup() - { - return productGroup; - } - - public void setProductGroup(String productGroup) - { - this.productGroup = productGroup; - } - - public String getType() - { - return type; - } - - public void setType(String type) - { - this.type = type; - } - - @Override - public boolean equals(Object obj) - { - if (obj == this) - { - return true; - } - - if (obj instanceof FactoryKey) - { - FactoryKey key = (FactoryKey)obj; - return ObjectUtil.equals(productGroup, key.productGroup) && ObjectUtil.equals(type, key.type); - } - - return false; - } - - @Override - public int hashCode() - { - return ObjectUtil.hashCode(productGroup) ^ ObjectUtil.hashCode(type); - } - - @Override - public String toString() - { - return MessageFormat.format("{0}[{1}]", productGroup, type); //$NON-NLS-1$ - } - - public int compareTo(FactoryKey key) - { - int result = StringUtil.compare(productGroup, key.productGroup); - if (result == 0) - { - result = StringUtil.compare(type, key.type); - } - - return result; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+import org.eclipse.net4j.util.ObjectUtil;
+import org.eclipse.net4j.util.StringUtil;
+
+import java.io.Serializable;
+import java.text.MessageFormat;
+
+/**
+ * A default implementation of a {@link IFactoryKey factory key}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public final class FactoryKey implements IFactoryKey, Serializable, Comparable<FactoryKey>
+{
+ private static final long serialVersionUID = 1L;
+
+ private String productGroup;
+
+ private String type;
+
+ public FactoryKey(String productGroup, String type)
+ {
+ this.productGroup = productGroup;
+ this.type = type;
+ }
+
+ public String getProductGroup()
+ {
+ return productGroup;
+ }
+
+ public void setProductGroup(String productGroup)
+ {
+ this.productGroup = productGroup;
+ }
+
+ public String getType()
+ {
+ return type;
+ }
+
+ public void setType(String type)
+ {
+ this.type = type;
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ if (obj instanceof FactoryKey)
+ {
+ FactoryKey key = (FactoryKey)obj;
+ return ObjectUtil.equals(productGroup, key.productGroup) && ObjectUtil.equals(type, key.type);
+ }
+
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return ObjectUtil.hashCode(productGroup) ^ ObjectUtil.hashCode(type);
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("{0}[{1}]", productGroup, type); //$NON-NLS-1$
+ }
+
+ public int compareTo(FactoryKey key)
+ {
+ int result = StringUtil.compare(productGroup, key.productGroup);
+ if (result == 0)
+ {
+ result = StringUtil.compare(type, key.type);
+ }
+
+ return result;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java index 4b33e46854..d498911d52 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -/** - * {@link #create(String) Creates} objects from a string {@link #getDescriptionFor(Object) description}. - * - * @author Eike Stepper - * @apiviz.landmark - * @apiviz.has {@link IFactoryKey} - */ -public interface IFactory -{ - public IFactoryKey getKey(); - - public Object create(String description) throws ProductCreationException; - - public String getDescriptionFor(Object product); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+/**
+ * {@link #create(String) Creates} objects from a string {@link #getDescriptionFor(Object) description}.
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ * @apiviz.has {@link IFactoryKey}
+ */
+public interface IFactory
+{
+ public IFactoryKey getKey();
+
+ public Object create(String description) throws ProductCreationException;
+
+ public String getDescriptionFor(Object product);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java index e2afe35116..175e6396f6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -/** - * Identifies a {@link IFactory factory} by {@link #getProductGroup() product group} and {@link #getType() type}. - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - * @apiviz.landmark - */ -public interface IFactoryKey -{ - public String getProductGroup(); - - public String getType(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+/**
+ * Identifies a {@link IFactory factory} by {@link #getProductGroup() product group} and {@link #getType() type}.
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @apiviz.landmark
+ */
+public interface IFactoryKey
+{
+ public String getProductGroup();
+
+ public String getType();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java index 7565784f33..0304139339 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java @@ -1,43 +1,43 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.factory; - -/** - * An unchecked exception that may be thrown from {@link IFactory factories} to indicate the inability to create a - * product. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class ProductCreationException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public ProductCreationException() - { - } - - public ProductCreationException(String message) - { - super(message); - } - - public ProductCreationException(Throwable cause) - { - super(cause); - } - - public ProductCreationException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.factory;
+
+/**
+ * An unchecked exception that may be thrown from {@link IFactory factories} to indicate the inability to create a
+ * product.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class ProductCreationException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public ProductCreationException()
+ {
+ }
+
+ public ProductCreationException(String message)
+ {
+ super(message);
+ }
+
+ public ProductCreationException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public ProductCreationException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java index 6793032ee2..ed3c9cd220 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java index 998bc5bb02..fcd7f490ca 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java @@ -1,390 +1,390 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.fsm; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.INotifier; -import org.eclipse.net4j.util.lifecycle.Lifecycle; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.text.MessageFormat; - -/** - * A <a href="http://en.wikipedia.org/wiki/Finite-state_machine">finite state machine</a> that is based on a matrix of - * {@link ITransition transitions}. - * <p> - * A finite state machine can fire the following events: - * <ul> - * <li> {@link StateChangedEvent} after state changes of a <i>subject</i>. - * </ul> - * - * @author Eike Stepper - * @apiviz.landmark - * @apiviz.has {@link ITransition} oneway - - matrix - * @apiviz.uses {@link FiniteStateMachine.StateChangedEvent} - - fires - */ -public abstract class FiniteStateMachine<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT> extends Lifecycle -{ - @SuppressWarnings("rawtypes") - public static final ITransition IGNORE = new InternalIgnoreTransition(); - - @SuppressWarnings("rawtypes") - public static final ITransition FAIL = new InternalFailTransition(); - - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, FiniteStateMachine.class); - - private static final String MSG_PROCESS = "Processing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$ - - private static final String MSG_IGNORE = "Ignoring event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$ - - private static final String MSG_FAIL = "Failing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$ - - private STATE[] states; - - private EVENT[] events; - - private ITransition<STATE, EVENT, SUBJECT, ?>[][] transitions; - - @SuppressWarnings("unchecked") - public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum, - ITransition<STATE, EVENT, SUBJECT, ?> defaultTransition) - { - states = stateEnum.getEnumConstants(); - events = eventEnum.getEnumConstants(); - transitions = new ITransition[states.length][events.length]; - initAll(defaultTransition); - } - - @SuppressWarnings("unchecked") - public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum) - { - this(stateEnum, eventEnum, FAIL); - } - - public final STATE[] getStates() - { - return states; - } - - public final EVENT[] getEvents() - { - return events; - } - - public final ITransition<STATE, EVENT, SUBJECT, ?> getTransition(STATE state, EVENT event) - { - int s = state.ordinal(); - int e = event.ordinal(); - return transitions[s][e]; - } - - public final void init(STATE state, EVENT event, STATE targetState) - { - init(state, event, new ChangeStateTransition(targetState)); - } - - public final void init(STATE state, EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition) - { - checkTransition(transition); - int s = state.ordinal(); - int e = event.ordinal(); - transitions[s][e] = transition; - } - - public final void initEvents(STATE state, STATE targetState) - { - initEvents(state, new ChangeStateTransition(targetState)); - } - - public final void initEvents(STATE state, ITransition<STATE, EVENT, SUBJECT, ?> transition) - { - checkTransition(transition); - int s = state.ordinal(); - for (int e = 0; e < events.length; e++) - { - transitions[s][e] = transition; - } - } - - public final void initStates(EVENT event, STATE targetState) - { - initStates(event, new ChangeStateTransition(targetState)); - } - - public final void initStates(EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition) - { - checkTransition(transition); - int e = event.ordinal(); - for (int s = 0; s < states.length; s++) - { - transitions[s][e] = transition; - } - } - - public final void initAll(STATE targetState) - { - initAll(new ChangeStateTransition(targetState)); - } - - public final void initAll(ITransition<STATE, EVENT, SUBJECT, ?> transition) - { - checkTransition(transition); - for (int s = 0; s < states.length; s++) - { - for (int e = 0; e < events.length; e++) - { - transitions[s][e] = transition; - } - } - } - - @SuppressWarnings("unchecked") - public final <DATA> void process(SUBJECT subject, EVENT event, DATA data) - { - STATE state = getState(subject); - int s = state.ordinal(); - int e = event.ordinal(); - ITransition<STATE, EVENT, SUBJECT, DATA> transition = (ITransition<STATE, EVENT, SUBJECT, DATA>)transitions[s][e]; - if (transition == IGNORE) - { - // Do nothing - } - else if (transition == FAIL) - { - throw new IllegalStateException(formatFailMessage(subject, state, event, data)); - } - else - { - if (TRACER.isEnabled()) - { - TRACER.trace(formatProcessMessage(subject, state, event, data)); - } - - transition.execute(subject, state, event, data); - } - } - - @SuppressWarnings("unchecked") - protected ITransition<STATE, EVENT, SUBJECT, ?> createIgnoreTransition(STATE state, EVENT event) - { - return IGNORE; - } - - @SuppressWarnings("unchecked") - protected ITransition<STATE, EVENT, SUBJECT, ?> createFailTransition(STATE state, EVENT event) - { - return FAIL; - } - - protected String formatProcessMessage(SUBJECT subject, STATE state, EVENT event, Object data) - { - return MessageFormat.format(MSG_PROCESS, event, state, subject, data); - } - - protected String formatIgnoreMessage(SUBJECT subject, STATE state, EVENT event, Object data) - { - return MessageFormat.format(MSG_IGNORE, event, state, subject, data); - } - - protected String formatFailMessage(SUBJECT subject, STATE state, EVENT event, Object data) - { - return MessageFormat.format(MSG_FAIL, event, state, subject, data); - } - - protected abstract STATE getState(SUBJECT subject); - - protected abstract void setState(SUBJECT subject, STATE state); - - /** - * @since 3.0 - */ - protected STATE changeState(SUBJECT subject, STATE state) - { - STATE oldState = getState(subject); - if (oldState != state) - { - setState(subject, state); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new StateChangedEvent(subject, oldState, state), listeners); - } - - return oldState; - } - - return null; - } - - private void checkTransition(ITransition<STATE, EVENT, SUBJECT, ?> transition) - { - if (transition == null) - { - throw new IllegalArgumentException("transition == null"); //$NON-NLS-1$ - } - } - - /** - * A {@link ITransition transition} that does nothing. - * - * @author Eike Stepper - * @deprecated Use {@link FiniteStateMachine#IGNORE} - * @apiviz.exclude - */ - @Deprecated - public static class IgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> - { - public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) - { - // Do nothing - } - - @Override - public String toString() - { - return "IGNORE"; //$NON-NLS-1$ - } - } - - /** - * A {@link ITransition transition} that throws an {@link IllegalStateException}. - * - * @author Eike Stepper - * @deprecated Use {@link FiniteStateMachine#FAIL} - * @apiviz.exclude - */ - @Deprecated - public static class FailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> - { - public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) - { - // Do nothing - } - - @Override - public String toString() - { - return "FAIL"; //$NON-NLS-1$ - } - } - - /** - * A {@link ITransition transition} that does nothing. - * - * @author Eike Stepper - * @apiviz.exclude - */ - private static class InternalIgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> - { - public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) - { - // Do nothing - } - - @Override - public String toString() - { - return "IGNORE"; //$NON-NLS-1$ - } - } - - /** - * A {@link ITransition transition} that throws an {@link IllegalStateException}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - private static class InternalFailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> - { - public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) - { - // Do nothing - } - - @Override - public String toString() - { - return "FAIL"; //$NON-NLS-1$ - } - } - - /** - * A {@link ITransition transition} that changes the {@link #getTargetState() state} of a <i>subject</i>. - * - * @author Eike Stepper - */ - public class ChangeStateTransition implements ITransition<STATE, EVENT, SUBJECT, Object> - { - private STATE targetState; - - public ChangeStateTransition(STATE targetState) - { - this.targetState = targetState; - } - - public STATE getTargetState() - { - return targetState; - } - - public void execute(SUBJECT subject, STATE state, EVENT event, Object data) - { - changeState(subject, targetState); - } - - @Override - public String toString() - { - return MessageFormat.format("CHANGE_STATE[{0}]", targetState); //$NON-NLS-1$ - } - } - - /** - * @author Eike Stepper - */ - public class StateChangedEvent implements IEvent - { - private Object subject; - - private Enum<?> oldState; - - private Enum<?> newState; - - public StateChangedEvent(Object subject, Enum<?> oldState, Enum<?> newState) - { - this.subject = subject; - this.oldState = oldState; - this.newState = newState; - } - - public INotifier getSource() - { - return FiniteStateMachine.this; - } - - public Object getSubject() - { - return subject; - } - - public Enum<?> getOldState() - { - return oldState; - } - - public Enum<?> getNewState() - { - return newState; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.fsm;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.INotifier;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.text.MessageFormat;
+
+/**
+ * A <a href="http://en.wikipedia.org/wiki/Finite-state_machine">finite state machine</a> that is based on a matrix of
+ * {@link ITransition transitions}.
+ * <p>
+ * A finite state machine can fire the following events:
+ * <ul>
+ * <li> {@link StateChangedEvent} after state changes of a <i>subject</i>.
+ * </ul>
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ * @apiviz.has {@link ITransition} oneway - - matrix
+ * @apiviz.uses {@link FiniteStateMachine.StateChangedEvent} - - fires
+ */
+public abstract class FiniteStateMachine<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT> extends Lifecycle
+{
+ @SuppressWarnings("rawtypes")
+ public static final ITransition IGNORE = new InternalIgnoreTransition();
+
+ @SuppressWarnings("rawtypes")
+ public static final ITransition FAIL = new InternalFailTransition();
+
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, FiniteStateMachine.class);
+
+ private static final String MSG_PROCESS = "Processing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$
+
+ private static final String MSG_IGNORE = "Ignoring event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$
+
+ private static final String MSG_FAIL = "Failing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$
+
+ private STATE[] states;
+
+ private EVENT[] events;
+
+ private ITransition<STATE, EVENT, SUBJECT, ?>[][] transitions;
+
+ @SuppressWarnings("unchecked")
+ public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum,
+ ITransition<STATE, EVENT, SUBJECT, ?> defaultTransition)
+ {
+ states = stateEnum.getEnumConstants();
+ events = eventEnum.getEnumConstants();
+ transitions = new ITransition[states.length][events.length];
+ initAll(defaultTransition);
+ }
+
+ @SuppressWarnings("unchecked")
+ public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum)
+ {
+ this(stateEnum, eventEnum, FAIL);
+ }
+
+ public final STATE[] getStates()
+ {
+ return states;
+ }
+
+ public final EVENT[] getEvents()
+ {
+ return events;
+ }
+
+ public final ITransition<STATE, EVENT, SUBJECT, ?> getTransition(STATE state, EVENT event)
+ {
+ int s = state.ordinal();
+ int e = event.ordinal();
+ return transitions[s][e];
+ }
+
+ public final void init(STATE state, EVENT event, STATE targetState)
+ {
+ init(state, event, new ChangeStateTransition(targetState));
+ }
+
+ public final void init(STATE state, EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition)
+ {
+ checkTransition(transition);
+ int s = state.ordinal();
+ int e = event.ordinal();
+ transitions[s][e] = transition;
+ }
+
+ public final void initEvents(STATE state, STATE targetState)
+ {
+ initEvents(state, new ChangeStateTransition(targetState));
+ }
+
+ public final void initEvents(STATE state, ITransition<STATE, EVENT, SUBJECT, ?> transition)
+ {
+ checkTransition(transition);
+ int s = state.ordinal();
+ for (int e = 0; e < events.length; e++)
+ {
+ transitions[s][e] = transition;
+ }
+ }
+
+ public final void initStates(EVENT event, STATE targetState)
+ {
+ initStates(event, new ChangeStateTransition(targetState));
+ }
+
+ public final void initStates(EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition)
+ {
+ checkTransition(transition);
+ int e = event.ordinal();
+ for (int s = 0; s < states.length; s++)
+ {
+ transitions[s][e] = transition;
+ }
+ }
+
+ public final void initAll(STATE targetState)
+ {
+ initAll(new ChangeStateTransition(targetState));
+ }
+
+ public final void initAll(ITransition<STATE, EVENT, SUBJECT, ?> transition)
+ {
+ checkTransition(transition);
+ for (int s = 0; s < states.length; s++)
+ {
+ for (int e = 0; e < events.length; e++)
+ {
+ transitions[s][e] = transition;
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public final <DATA> void process(SUBJECT subject, EVENT event, DATA data)
+ {
+ STATE state = getState(subject);
+ int s = state.ordinal();
+ int e = event.ordinal();
+ ITransition<STATE, EVENT, SUBJECT, DATA> transition = (ITransition<STATE, EVENT, SUBJECT, DATA>)transitions[s][e];
+ if (transition == IGNORE)
+ {
+ // Do nothing
+ }
+ else if (transition == FAIL)
+ {
+ throw new IllegalStateException(formatFailMessage(subject, state, event, data));
+ }
+ else
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace(formatProcessMessage(subject, state, event, data));
+ }
+
+ transition.execute(subject, state, event, data);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected ITransition<STATE, EVENT, SUBJECT, ?> createIgnoreTransition(STATE state, EVENT event)
+ {
+ return IGNORE;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected ITransition<STATE, EVENT, SUBJECT, ?> createFailTransition(STATE state, EVENT event)
+ {
+ return FAIL;
+ }
+
+ protected String formatProcessMessage(SUBJECT subject, STATE state, EVENT event, Object data)
+ {
+ return MessageFormat.format(MSG_PROCESS, event, state, subject, data);
+ }
+
+ protected String formatIgnoreMessage(SUBJECT subject, STATE state, EVENT event, Object data)
+ {
+ return MessageFormat.format(MSG_IGNORE, event, state, subject, data);
+ }
+
+ protected String formatFailMessage(SUBJECT subject, STATE state, EVENT event, Object data)
+ {
+ return MessageFormat.format(MSG_FAIL, event, state, subject, data);
+ }
+
+ protected abstract STATE getState(SUBJECT subject);
+
+ protected abstract void setState(SUBJECT subject, STATE state);
+
+ /**
+ * @since 3.0
+ */
+ protected STATE changeState(SUBJECT subject, STATE state)
+ {
+ STATE oldState = getState(subject);
+ if (oldState != state)
+ {
+ setState(subject, state);
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new StateChangedEvent(subject, oldState, state), listeners);
+ }
+
+ return oldState;
+ }
+
+ return null;
+ }
+
+ private void checkTransition(ITransition<STATE, EVENT, SUBJECT, ?> transition)
+ {
+ if (transition == null)
+ {
+ throw new IllegalArgumentException("transition == null"); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * A {@link ITransition transition} that does nothing.
+ *
+ * @author Eike Stepper
+ * @deprecated Use {@link FiniteStateMachine#IGNORE}
+ * @apiviz.exclude
+ */
+ @Deprecated
+ public static class IgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
+ {
+ public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
+ {
+ // Do nothing
+ }
+
+ @Override
+ public String toString()
+ {
+ return "IGNORE"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * A {@link ITransition transition} that throws an {@link IllegalStateException}.
+ *
+ * @author Eike Stepper
+ * @deprecated Use {@link FiniteStateMachine#FAIL}
+ * @apiviz.exclude
+ */
+ @Deprecated
+ public static class FailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
+ {
+ public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
+ {
+ // Do nothing
+ }
+
+ @Override
+ public String toString()
+ {
+ return "FAIL"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * A {@link ITransition transition} that does nothing.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ private static class InternalIgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
+ {
+ public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
+ {
+ // Do nothing
+ }
+
+ @Override
+ public String toString()
+ {
+ return "IGNORE"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * A {@link ITransition transition} that throws an {@link IllegalStateException}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ private static class InternalFailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
+ {
+ public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
+ {
+ // Do nothing
+ }
+
+ @Override
+ public String toString()
+ {
+ return "FAIL"; //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * A {@link ITransition transition} that changes the {@link #getTargetState() state} of a <i>subject</i>.
+ *
+ * @author Eike Stepper
+ */
+ public class ChangeStateTransition implements ITransition<STATE, EVENT, SUBJECT, Object>
+ {
+ private STATE targetState;
+
+ public ChangeStateTransition(STATE targetState)
+ {
+ this.targetState = targetState;
+ }
+
+ public STATE getTargetState()
+ {
+ return targetState;
+ }
+
+ public void execute(SUBJECT subject, STATE state, EVENT event, Object data)
+ {
+ changeState(subject, targetState);
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("CHANGE_STATE[{0}]", targetState); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public class StateChangedEvent implements IEvent
+ {
+ private Object subject;
+
+ private Enum<?> oldState;
+
+ private Enum<?> newState;
+
+ public StateChangedEvent(Object subject, Enum<?> oldState, Enum<?> newState)
+ {
+ this.subject = subject;
+ this.oldState = oldState;
+ this.newState = newState;
+ }
+
+ public INotifier getSource()
+ {
+ return FiniteStateMachine.this;
+ }
+
+ public Object getSubject()
+ {
+ return subject;
+ }
+
+ public Enum<?> getOldState()
+ {
+ return oldState;
+ }
+
+ public Enum<?> getNewState()
+ {
+ return newState;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java index fd517b8790..3866cbfd49 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.fsm; - -/** - * Encpsulates the logic to be executed when an <i>event</i> arrives for a <i>subject</i> in a particular <i>state</i>. - * - * @author Eike Stepper - * @apiviz.landmark - */ -public interface ITransition<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT, DATA> -{ - public void execute(SUBJECT subject, STATE state, EVENT event, DATA data); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.fsm;
+
+/**
+ * Encpsulates the logic to be executed when an <i>event</i> arrives for a <i>subject</i> in a particular <i>state</i>.
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ */
+public interface ITransition<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT, DATA>
+{
+ public void execute(SUBJECT subject, STATE state, EVENT event, DATA data);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java index 3ca7a62c18..d42f1f6cb5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java index 52563ebda1..1b19f45256 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java @@ -1,74 +1,74 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.WrappedException; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.util.concurrent.CountDownLatch; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public abstract class AsyncOutputStream extends PipedOutputStream -{ - private CountDownLatch latch = new CountDownLatch(1); - - public AsyncOutputStream() throws IOException - { - final PipedInputStream in = new PipedInputStream(this); - Thread thread = new Thread("AsyncOutputStream") - { - @Override - public void run() - { - try - { - asyncWrite(in); - } - catch (IOException ex) - { - OM.LOG.error(ex); - throw WrappedException.wrap(ex); - } - finally - { - latch.countDown(); - } - } - }; - - thread.setDaemon(true); - thread.start(); - } - - @Override - public void close() throws IOException - { - super.close(); - - try - { - latch.await(); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } - - protected abstract void asyncWrite(InputStream in) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.WrappedException;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public abstract class AsyncOutputStream extends PipedOutputStream
+{
+ private CountDownLatch latch = new CountDownLatch(1);
+
+ public AsyncOutputStream() throws IOException
+ {
+ final PipedInputStream in = new PipedInputStream(this);
+ Thread thread = new Thread("AsyncOutputStream")
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ asyncWrite(in);
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error(ex);
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ latch.countDown();
+ }
+ }
+ };
+
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ super.close();
+
+ try
+ {
+ latch.await();
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ protected abstract void asyncWrite(InputStream in) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java index 3c7d9a6d34..79cf83bf5a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java @@ -1,74 +1,74 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.WrappedException; - -import java.io.IOException; -import java.io.PipedReader; -import java.io.PipedWriter; -import java.io.Reader; -import java.util.concurrent.CountDownLatch; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public abstract class AsyncWriter extends PipedWriter -{ - private CountDownLatch latch = new CountDownLatch(1); - - public AsyncWriter() throws IOException - { - final PipedReader in = new PipedReader(this); - Thread thread = new Thread("AsyncWriter") - { - @Override - public void run() - { - try - { - asyncWrite(in); - } - catch (IOException ex) - { - OM.LOG.error(ex); - throw WrappedException.wrap(ex); - } - finally - { - latch.countDown(); - } - } - }; - - thread.setDaemon(true); - thread.start(); - } - - @Override - public void close() throws IOException - { - super.close(); - - try - { - latch.await(); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } - - protected abstract void asyncWrite(Reader in) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.WrappedException;
+
+import java.io.IOException;
+import java.io.PipedReader;
+import java.io.PipedWriter;
+import java.io.Reader;
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public abstract class AsyncWriter extends PipedWriter
+{
+ private CountDownLatch latch = new CountDownLatch(1);
+
+ public AsyncWriter() throws IOException
+ {
+ final PipedReader in = new PipedReader(this);
+ Thread thread = new Thread("AsyncWriter")
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ asyncWrite(in);
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error(ex);
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ latch.countDown();
+ }
+ }
+ };
+
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ super.close();
+
+ try
+ {
+ latch.await();
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ protected abstract void asyncWrite(Reader in) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java index c20d9edba4..e212dde5cf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java @@ -1,48 +1,48 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public abstract class CachedFileMap<K extends Comparable<K>, V> extends SortedFileMap<K, V> -{ - private Map<K, V> cache = new HashMap<K, V>(); - - public CachedFileMap(File file, String mode) - { - super(file, mode); - } - - @Override - public V get(K key) - { - V value = cache.get(key); - if (value == null) - { - value = super.get(key); - cache.put(key, value); - } - - return value; - } - - @Override - public V put(K key, V value) - { - cache.put(key, value); - return super.put(key, value); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class CachedFileMap<K extends Comparable<K>, V> extends SortedFileMap<K, V>
+{
+ private Map<K, V> cache = new HashMap<K, V>();
+
+ public CachedFileMap(File file, String mode)
+ {
+ super(file, mode);
+ }
+
+ @Override
+ public V get(K key)
+ {
+ V value = cache.get(key);
+ if (value == null)
+ {
+ value = super.get(key);
+ cache.put(key, value);
+ }
+
+ return value;
+ }
+
+ @Override
+ public V put(K key, V value)
+ {
+ cache.put(key, value);
+ return super.put(key, value);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java index e240bf8303..49478c2409 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java @@ -1,137 +1,137 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver; - -import java.io.DataInput; -import java.io.IOException; - -/** - * @author Eike Stepper - */ -public class DataInputExtender implements ExtendedDataInput -{ - private DataInput input; - - public DataInputExtender(DataInput input) - { - this.input = input; - } - - public boolean readBoolean() throws IOException - { - return input.readBoolean(); - } - - public byte readByte() throws IOException - { - return input.readByte(); - } - - public char readChar() throws IOException - { - return input.readChar(); - } - - public double readDouble() throws IOException - { - return input.readDouble(); - } - - public float readFloat() throws IOException - { - return input.readFloat(); - } - - public void readFully(byte[] b, int off, int len) throws IOException - { - input.readFully(b, off, len); - } - - public void readFully(byte[] b) throws IOException - { - input.readFully(b); - } - - public int readInt() throws IOException - { - return input.readInt(); - } - - public String readLine() throws IOException - { - return input.readLine(); - } - - public long readLong() throws IOException - { - return input.readLong(); - } - - public short readShort() throws IOException - { - return input.readShort(); - } - - public int readUnsignedByte() throws IOException - { - return input.readUnsignedByte(); - } - - public int readUnsignedShort() throws IOException - { - return input.readUnsignedShort(); - } - - public String readUTF() throws IOException - { - return input.readUTF(); - } - - public byte[] readByteArray() throws IOException - { - return ExtendedIOUtil.readByteArray(input); - } - - public Object readObject() throws IOException - { - return ExtendedIOUtil.readObject(input); - } - - public Object readObject(ClassLoader classLoader) throws IOException - { - return ExtendedIOUtil.readObject(input, classLoader); - } - - public Object readObject(ClassResolver classResolver) throws IOException - { - return ExtendedIOUtil.readObject(input, classResolver); - } - - public String readString() throws IOException - { - return ExtendedIOUtil.readString(input); - } - - /** - * @since 3.0 - */ - public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException - { - return ExtendedIOUtil.readEnum(input, type); - } - - public int skipBytes(int n) throws IOException - { - return input.skipBytes(n); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver;
+
+import java.io.DataInput;
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ */
+public class DataInputExtender implements ExtendedDataInput
+{
+ private DataInput input;
+
+ public DataInputExtender(DataInput input)
+ {
+ this.input = input;
+ }
+
+ public boolean readBoolean() throws IOException
+ {
+ return input.readBoolean();
+ }
+
+ public byte readByte() throws IOException
+ {
+ return input.readByte();
+ }
+
+ public char readChar() throws IOException
+ {
+ return input.readChar();
+ }
+
+ public double readDouble() throws IOException
+ {
+ return input.readDouble();
+ }
+
+ public float readFloat() throws IOException
+ {
+ return input.readFloat();
+ }
+
+ public void readFully(byte[] b, int off, int len) throws IOException
+ {
+ input.readFully(b, off, len);
+ }
+
+ public void readFully(byte[] b) throws IOException
+ {
+ input.readFully(b);
+ }
+
+ public int readInt() throws IOException
+ {
+ return input.readInt();
+ }
+
+ public String readLine() throws IOException
+ {
+ return input.readLine();
+ }
+
+ public long readLong() throws IOException
+ {
+ return input.readLong();
+ }
+
+ public short readShort() throws IOException
+ {
+ return input.readShort();
+ }
+
+ public int readUnsignedByte() throws IOException
+ {
+ return input.readUnsignedByte();
+ }
+
+ public int readUnsignedShort() throws IOException
+ {
+ return input.readUnsignedShort();
+ }
+
+ public String readUTF() throws IOException
+ {
+ return input.readUTF();
+ }
+
+ public byte[] readByteArray() throws IOException
+ {
+ return ExtendedIOUtil.readByteArray(input);
+ }
+
+ public Object readObject() throws IOException
+ {
+ return ExtendedIOUtil.readObject(input);
+ }
+
+ public Object readObject(ClassLoader classLoader) throws IOException
+ {
+ return ExtendedIOUtil.readObject(input, classLoader);
+ }
+
+ public Object readObject(ClassResolver classResolver) throws IOException
+ {
+ return ExtendedIOUtil.readObject(input, classResolver);
+ }
+
+ public String readString() throws IOException
+ {
+ return ExtendedIOUtil.readString(input);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException
+ {
+ return ExtendedIOUtil.readEnum(input, type);
+ }
+
+ public int skipBytes(int n) throws IOException
+ {
+ return input.skipBytes(n);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java index 7b55f98b3c..f3b9e11b74 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java @@ -1,120 +1,120 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.DataOutput; -import java.io.IOException; - -/** - * @author Eike Stepper - */ -public class DataOutputExtender implements ExtendedDataOutput -{ - private DataOutput output; - - public DataOutputExtender(DataOutput output) - { - this.output = output; - } - - public void write(byte[] b, int off, int len) throws IOException - { - output.write(b, off, len); - } - - public void write(byte[] b) throws IOException - { - output.write(b); - } - - public void write(int b) throws IOException - { - output.write(b); - } - - public void writeBoolean(boolean v) throws IOException - { - output.writeBoolean(v); - } - - public void writeByte(int v) throws IOException - { - output.writeByte(v); - } - - public void writeBytes(String s) throws IOException - { - output.writeBytes(s); - } - - public void writeChar(int v) throws IOException - { - output.writeChar(v); - } - - public void writeChars(String s) throws IOException - { - output.writeChars(s); - } - - public void writeDouble(double v) throws IOException - { - output.writeDouble(v); - } - - public void writeFloat(float v) throws IOException - { - output.writeFloat(v); - } - - public void writeInt(int v) throws IOException - { - output.writeInt(v); - } - - public void writeLong(long v) throws IOException - { - output.writeLong(v); - } - - public void writeShort(int v) throws IOException - { - output.writeShort(v); - } - - public void writeUTF(String str) throws IOException - { - output.writeUTF(str); - } - - public void writeByteArray(byte[] b) throws IOException - { - ExtendedIOUtil.writeByteArray(output, b); - } - - public void writeObject(Object object) throws IOException - { - ExtendedIOUtil.writeObject(output, object); - } - - public void writeString(String str) throws IOException - { - ExtendedIOUtil.writeString(output, str); - } - - /** - * @since 3.0 - */ - public void writeEnum(Enum<?> literal) throws IOException - { - ExtendedIOUtil.writeEnum(output, literal); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.DataOutput;
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ */
+public class DataOutputExtender implements ExtendedDataOutput
+{
+ private DataOutput output;
+
+ public DataOutputExtender(DataOutput output)
+ {
+ this.output = output;
+ }
+
+ public void write(byte[] b, int off, int len) throws IOException
+ {
+ output.write(b, off, len);
+ }
+
+ public void write(byte[] b) throws IOException
+ {
+ output.write(b);
+ }
+
+ public void write(int b) throws IOException
+ {
+ output.write(b);
+ }
+
+ public void writeBoolean(boolean v) throws IOException
+ {
+ output.writeBoolean(v);
+ }
+
+ public void writeByte(int v) throws IOException
+ {
+ output.writeByte(v);
+ }
+
+ public void writeBytes(String s) throws IOException
+ {
+ output.writeBytes(s);
+ }
+
+ public void writeChar(int v) throws IOException
+ {
+ output.writeChar(v);
+ }
+
+ public void writeChars(String s) throws IOException
+ {
+ output.writeChars(s);
+ }
+
+ public void writeDouble(double v) throws IOException
+ {
+ output.writeDouble(v);
+ }
+
+ public void writeFloat(float v) throws IOException
+ {
+ output.writeFloat(v);
+ }
+
+ public void writeInt(int v) throws IOException
+ {
+ output.writeInt(v);
+ }
+
+ public void writeLong(long v) throws IOException
+ {
+ output.writeLong(v);
+ }
+
+ public void writeShort(int v) throws IOException
+ {
+ output.writeShort(v);
+ }
+
+ public void writeUTF(String str) throws IOException
+ {
+ output.writeUTF(str);
+ }
+
+ public void writeByteArray(byte[] b) throws IOException
+ {
+ ExtendedIOUtil.writeByteArray(output, b);
+ }
+
+ public void writeObject(Object object) throws IOException
+ {
+ ExtendedIOUtil.writeObject(output, object);
+ }
+
+ public void writeString(String str) throws IOException
+ {
+ ExtendedIOUtil.writeString(output, str);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void writeEnum(Enum<?> literal) throws IOException
+ {
+ ExtendedIOUtil.writeEnum(output, literal);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java index faa4f539d5..04cfa9a4bd 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java @@ -1,179 +1,179 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * A <code>DelegatingInputStream</code> contains some other input stream, which it uses as its basic source of data, - * possibly transforming the data along the way or providing additional functionality. The class - * <code>DelegatingInputStream</code> itself simply overrides all (see note below) methods of <code>InputStream</code> - * with versions that pass all requests to the contained input stream. Subclasses of <code>DelegatingInputStream</code> - * may further override some of these methods and may also provide additional methods and fields. - * <p> - * <b>Note:</b> The only difference to {@link java.io.FilterInputStream} is that <code>DelegatingInputStream</code> does - * <b>not</b> override {@link #read(byte[])} or {@link #read(byte[], int, int)} but rather exposes the original - * implementations of <code>InputStream</code> which call {@link #read()} instead of their delegate counterparts. - * - * @author Eike Stepper - */ -public class DelegatingInputStream extends InputStream -{ - /** - * The input stream to be filtered. - */ - protected volatile InputStream in; - - /** - * Creates a <code>DelegatingInputStream</code> by assigning the argument <code>in</code> to the field - * <code>this.in</code> so as to remember it for later use. - * - * @param in - * the underlying input stream, or <code>null</code> if this instance is to be created without an underlying - * stream. - */ - protected DelegatingInputStream(InputStream in) - { - this.in = in; - } - - public InputStream getDelegate() - { - return in; - } - - /** - * Reads the next byte of data from this input stream. The value byte is returned as an <code>int</code> in the range - * <code>0</code> to <code>255</code>. If no byte is available because the end of the stream has been reached, the - * value <code>-1</code> is returned. This method blocks until input data is available, the end of the stream is - * detected, or an exception is thrown. - * <p> - * This method simply performs <code>in.read()</code> and returns the result. - * - * @return the next byte of data, or <code>-1</code> if the end of the stream is reached. - * @exception IOException - * if an I/O error occurs. - * @see DelegatingInputStream#in - */ - @Override - public int read() throws IOException - { - return in.read(); - } - - /** - * Skips over and discards <code>n</code> bytes of data from the input stream. The <code>skip</code> method may, for a - * variety of reasons, end up skipping over some smaller number of bytes, possibly <code>0</code>. The actual number - * of bytes skipped is returned. - * <p> - * This method simply performs <code>in.skip(n)</code>. - * - * @param n - * the number of bytes to be skipped. - * @return the actual number of bytes skipped. - * @exception IOException - * if an I/O error occurs. - */ - @Override - public long skip(long n) throws IOException - { - return in.skip(n); - } - - /** - * Returns the number of bytes that can be read from this input stream without blocking. - * <p> - * This method simply performs <code>in.available()</code> and returns the result. - * - * @return the number of bytes that can be read from the input stream without blocking. - * @exception IOException - * if an I/O error occurs. - * @see DelegatingInputStream#in - */ - @Override - public int available() throws IOException - { - return in.available(); - } - - /** - * Closes this input stream and releases any system resources associated with the stream. This method simply performs - * <code>in.close()</code>. - * - * @exception IOException - * if an I/O error occurs. - * @see DelegatingInputStream#in - */ - @Override - public void close() throws IOException - { - in.close(); - } - - /** - * Marks the current position in this input stream. A subsequent call to the <code>reset</code> method repositions - * this stream at the last marked position so that subsequent reads re-read the same bytes. - * <p> - * The <code>readlimit</code> argument tells this input stream to allow that many bytes to be read before the mark - * position gets invalidated. - * <p> - * This method simply performs <code>in.mark(readlimit)</code>. - * - * @param readlimit - * the maximum limit of bytes that can be read before the mark position becomes invalid. - * @see DelegatingInputStream#in - * @see DelegatingInputStream#reset() - */ - @Override - public synchronized void mark(int readlimit) - { - in.mark(readlimit); - } - - /** - * Repositions this stream to the position at the time the <code>mark</code> method was last called on this input - * stream. - * <p> - * This method simply performs <code>in.reset()</code>. - * <p> - * Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the - * stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the - * parse, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it - * fails. If this happens within readlimit bytes, it allows the outer code to reset the stream and try another parser. - * - * @exception IOException - * if the stream has not been marked or if the mark has been invalidated. - * @see DelegatingInputStream#in - * @see DelegatingInputStream#mark(int) - */ - @Override - public synchronized void reset() throws IOException - { - in.reset(); - } - - /** - * Tests if this input stream supports the <code>mark</code> and <code>reset</code> methods. This method simply - * performs <code>in.markSupported()</code>. - * - * @return <code>true</code> if this stream type supports the <code>mark</code> and <code>reset</code> method; - * <code>false</code> otherwise. - * @see DelegatingInputStream#in - * @see java.io.InputStream#mark(int) - * @see java.io.InputStream#reset() - */ - @Override - public boolean markSupported() - { - return in.markSupported(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * A <code>DelegatingInputStream</code> contains some other input stream, which it uses as its basic source of data,
+ * possibly transforming the data along the way or providing additional functionality. The class
+ * <code>DelegatingInputStream</code> itself simply overrides all (see note below) methods of <code>InputStream</code>
+ * with versions that pass all requests to the contained input stream. Subclasses of <code>DelegatingInputStream</code>
+ * may further override some of these methods and may also provide additional methods and fields.
+ * <p>
+ * <b>Note:</b> The only difference to {@link java.io.FilterInputStream} is that <code>DelegatingInputStream</code> does
+ * <b>not</b> override {@link #read(byte[])} or {@link #read(byte[], int, int)} but rather exposes the original
+ * implementations of <code>InputStream</code> which call {@link #read()} instead of their delegate counterparts.
+ *
+ * @author Eike Stepper
+ */
+public class DelegatingInputStream extends InputStream
+{
+ /**
+ * The input stream to be filtered.
+ */
+ protected volatile InputStream in;
+
+ /**
+ * Creates a <code>DelegatingInputStream</code> by assigning the argument <code>in</code> to the field
+ * <code>this.in</code> so as to remember it for later use.
+ *
+ * @param in
+ * the underlying input stream, or <code>null</code> if this instance is to be created without an underlying
+ * stream.
+ */
+ protected DelegatingInputStream(InputStream in)
+ {
+ this.in = in;
+ }
+
+ public InputStream getDelegate()
+ {
+ return in;
+ }
+
+ /**
+ * Reads the next byte of data from this input stream. The value byte is returned as an <code>int</code> in the range
+ * <code>0</code> to <code>255</code>. If no byte is available because the end of the stream has been reached, the
+ * value <code>-1</code> is returned. This method blocks until input data is available, the end of the stream is
+ * detected, or an exception is thrown.
+ * <p>
+ * This method simply performs <code>in.read()</code> and returns the result.
+ *
+ * @return the next byte of data, or <code>-1</code> if the end of the stream is reached.
+ * @exception IOException
+ * if an I/O error occurs.
+ * @see DelegatingInputStream#in
+ */
+ @Override
+ public int read() throws IOException
+ {
+ return in.read();
+ }
+
+ /**
+ * Skips over and discards <code>n</code> bytes of data from the input stream. The <code>skip</code> method may, for a
+ * variety of reasons, end up skipping over some smaller number of bytes, possibly <code>0</code>. The actual number
+ * of bytes skipped is returned.
+ * <p>
+ * This method simply performs <code>in.skip(n)</code>.
+ *
+ * @param n
+ * the number of bytes to be skipped.
+ * @return the actual number of bytes skipped.
+ * @exception IOException
+ * if an I/O error occurs.
+ */
+ @Override
+ public long skip(long n) throws IOException
+ {
+ return in.skip(n);
+ }
+
+ /**
+ * Returns the number of bytes that can be read from this input stream without blocking.
+ * <p>
+ * This method simply performs <code>in.available()</code> and returns the result.
+ *
+ * @return the number of bytes that can be read from the input stream without blocking.
+ * @exception IOException
+ * if an I/O error occurs.
+ * @see DelegatingInputStream#in
+ */
+ @Override
+ public int available() throws IOException
+ {
+ return in.available();
+ }
+
+ /**
+ * Closes this input stream and releases any system resources associated with the stream. This method simply performs
+ * <code>in.close()</code>.
+ *
+ * @exception IOException
+ * if an I/O error occurs.
+ * @see DelegatingInputStream#in
+ */
+ @Override
+ public void close() throws IOException
+ {
+ in.close();
+ }
+
+ /**
+ * Marks the current position in this input stream. A subsequent call to the <code>reset</code> method repositions
+ * this stream at the last marked position so that subsequent reads re-read the same bytes.
+ * <p>
+ * The <code>readlimit</code> argument tells this input stream to allow that many bytes to be read before the mark
+ * position gets invalidated.
+ * <p>
+ * This method simply performs <code>in.mark(readlimit)</code>.
+ *
+ * @param readlimit
+ * the maximum limit of bytes that can be read before the mark position becomes invalid.
+ * @see DelegatingInputStream#in
+ * @see DelegatingInputStream#reset()
+ */
+ @Override
+ public synchronized void mark(int readlimit)
+ {
+ in.mark(readlimit);
+ }
+
+ /**
+ * Repositions this stream to the position at the time the <code>mark</code> method was last called on this input
+ * stream.
+ * <p>
+ * This method simply performs <code>in.reset()</code>.
+ * <p>
+ * Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the
+ * stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the
+ * parse, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it
+ * fails. If this happens within readlimit bytes, it allows the outer code to reset the stream and try another parser.
+ *
+ * @exception IOException
+ * if the stream has not been marked or if the mark has been invalidated.
+ * @see DelegatingInputStream#in
+ * @see DelegatingInputStream#mark(int)
+ */
+ @Override
+ public synchronized void reset() throws IOException
+ {
+ in.reset();
+ }
+
+ /**
+ * Tests if this input stream supports the <code>mark</code> and <code>reset</code> methods. This method simply
+ * performs <code>in.markSupported()</code>.
+ *
+ * @return <code>true</code> if this stream type supports the <code>mark</code> and <code>reset</code> method;
+ * <code>false</code> otherwise.
+ * @see DelegatingInputStream#in
+ * @see java.io.InputStream#mark(int)
+ * @see java.io.InputStream#reset()
+ */
+ @Override
+ public boolean markSupported()
+ {
+ return in.markSupported();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java index 25a0c7287c..709f630057 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java @@ -1,114 +1,114 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * This class is the superclass of all classes that filter output streams. These streams sit on top of an already - * existing output stream (the <i>underlying</i> output stream) which it uses as its basic sink of data, but possibly - * transforming the data along the way or providing additional functionality. - * <p> - * The class <code>DelegatingOutputStream</code> itself simply overrides all methods of <code>OutputStream</code> with - * versions that pass all requests to the underlying output stream. Subclasses of <code>DelegatingOutputStream</code> - * may further override some of these methods as well as provide additional methods and fields. - * <p> - * <b>Note:</b> The only difference to {@link java.io.FilterOutputStream} is that <code>DelegatingOutputStream</code> - * does <b>not</b> override {@link #write(byte[])} or {@link #write(byte[], int, int)} but rather exposes the original - * implementations of <code>InputStream</code> which call {@link #write(int)} instead of their delegate counterparts. - * - * @author Eike Stepper - */ -public class DelegatingOutputStream extends OutputStream -{ - /** - * The underlying output stream to be filtered. - */ - protected OutputStream out; - - /** - * Creates an output stream filter built on top of the specified underlying output stream. - * - * @param out - * the underlying output stream to be assigned to the field <tt>this.out</tt> for later use, or - * <code>null</code> if this instance is to be created without an underlying stream. - */ - public DelegatingOutputStream(OutputStream out) - { - this.out = out; - } - - public OutputStream getDelegate() - { - return out; - } - - /** - * Writes the specified <code>byte</code> to this output stream. - * <p> - * The <code>write</code> method of <code>DelegatingOutputStream</code> calls the <code>write</code> method of its - * underlying output stream, that is, it performs <tt>out.write(b)</tt>. - * <p> - * Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>. - * - * @param b - * the <code>byte</code>. - * @exception IOException - * if an I/O error occurs. - */ - @Override - public void write(int b) throws IOException - { - out.write(b); - } - - /** - * Flushes this output stream and forces any buffered output bytes to be written out to the stream. - * <p> - * The <code>flush</code> method of <code>DelegatingOutputStream</code> calls the <code>flush</code> method of its - * underlying output stream. - * - * @exception IOException - * if an I/O error occurs. - * @see DelegatingOutputStream#out - */ - @Override - public void flush() throws IOException - { - out.flush(); - } - - /** - * Closes this output stream and releases any system resources associated with the stream. - * <p> - * The <code>close</code> method of <code>DelegatingOutputStream</code> calls its <code>flush</code> method, and then - * calls the <code>close</code> method of its underlying output stream. - * - * @exception IOException - * if an I/O error occurs. - * @see DelegatingOutputStream#flush() - * @see DelegatingOutputStream#out - */ - @Override - public void close() throws IOException - { - try - { - flush(); - } - catch (IOException ignored) - { - } - - out.close(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * This class is the superclass of all classes that filter output streams. These streams sit on top of an already
+ * existing output stream (the <i>underlying</i> output stream) which it uses as its basic sink of data, but possibly
+ * transforming the data along the way or providing additional functionality.
+ * <p>
+ * The class <code>DelegatingOutputStream</code> itself simply overrides all methods of <code>OutputStream</code> with
+ * versions that pass all requests to the underlying output stream. Subclasses of <code>DelegatingOutputStream</code>
+ * may further override some of these methods as well as provide additional methods and fields.
+ * <p>
+ * <b>Note:</b> The only difference to {@link java.io.FilterOutputStream} is that <code>DelegatingOutputStream</code>
+ * does <b>not</b> override {@link #write(byte[])} or {@link #write(byte[], int, int)} but rather exposes the original
+ * implementations of <code>InputStream</code> which call {@link #write(int)} instead of their delegate counterparts.
+ *
+ * @author Eike Stepper
+ */
+public class DelegatingOutputStream extends OutputStream
+{
+ /**
+ * The underlying output stream to be filtered.
+ */
+ protected OutputStream out;
+
+ /**
+ * Creates an output stream filter built on top of the specified underlying output stream.
+ *
+ * @param out
+ * the underlying output stream to be assigned to the field <tt>this.out</tt> for later use, or
+ * <code>null</code> if this instance is to be created without an underlying stream.
+ */
+ public DelegatingOutputStream(OutputStream out)
+ {
+ this.out = out;
+ }
+
+ public OutputStream getDelegate()
+ {
+ return out;
+ }
+
+ /**
+ * Writes the specified <code>byte</code> to this output stream.
+ * <p>
+ * The <code>write</code> method of <code>DelegatingOutputStream</code> calls the <code>write</code> method of its
+ * underlying output stream, that is, it performs <tt>out.write(b)</tt>.
+ * <p>
+ * Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>.
+ *
+ * @param b
+ * the <code>byte</code>.
+ * @exception IOException
+ * if an I/O error occurs.
+ */
+ @Override
+ public void write(int b) throws IOException
+ {
+ out.write(b);
+ }
+
+ /**
+ * Flushes this output stream and forces any buffered output bytes to be written out to the stream.
+ * <p>
+ * The <code>flush</code> method of <code>DelegatingOutputStream</code> calls the <code>flush</code> method of its
+ * underlying output stream.
+ *
+ * @exception IOException
+ * if an I/O error occurs.
+ * @see DelegatingOutputStream#out
+ */
+ @Override
+ public void flush() throws IOException
+ {
+ out.flush();
+ }
+
+ /**
+ * Closes this output stream and releases any system resources associated with the stream.
+ * <p>
+ * The <code>close</code> method of <code>DelegatingOutputStream</code> calls its <code>flush</code> method, and then
+ * calls the <code>close</code> method of its underlying output stream.
+ *
+ * @exception IOException
+ * if an I/O error occurs.
+ * @see DelegatingOutputStream#flush()
+ * @see DelegatingOutputStream#out
+ */
+ @Override
+ public void close() throws IOException
+ {
+ try
+ {
+ flush();
+ }
+ catch (IOException ignored)
+ {
+ }
+
+ out.close();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java index ed442832bd..7147cd7924 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java @@ -1,63 +1,63 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public abstract class DelegatingStreamWrapper implements IStreamWrapper -{ - private IStreamWrapper delegate; - - public DelegatingStreamWrapper(IStreamWrapper delegate) - { - this.delegate = delegate; - } - - public IStreamWrapper getDelegate() - { - return delegate; - } - - public InputStream wrapInputStream(InputStream in) throws IOException - { - return doWrapInputStream(delegate.wrapInputStream(in)); - } - - public OutputStream wrapOutputStream(OutputStream out) throws IOException - { - return doWrapOutputStream(delegate.wrapOutputStream(out)); - } - - public void finishInputStream(InputStream in) throws IOException - { - delegate.finishInputStream(in); - doFinishInputStream(in); - } - - public void finishOutputStream(OutputStream out) throws IOException - { - delegate.finishOutputStream(out); - doFinishOutputStream(out); - } - - protected abstract InputStream doWrapInputStream(InputStream in) throws IOException; - - protected abstract OutputStream doWrapOutputStream(OutputStream out) throws IOException; - - protected abstract void doFinishInputStream(InputStream in) throws IOException; - - protected abstract void doFinishOutputStream(OutputStream out) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class DelegatingStreamWrapper implements IStreamWrapper
+{
+ private IStreamWrapper delegate;
+
+ public DelegatingStreamWrapper(IStreamWrapper delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public IStreamWrapper getDelegate()
+ {
+ return delegate;
+ }
+
+ public InputStream wrapInputStream(InputStream in) throws IOException
+ {
+ return doWrapInputStream(delegate.wrapInputStream(in));
+ }
+
+ public OutputStream wrapOutputStream(OutputStream out) throws IOException
+ {
+ return doWrapOutputStream(delegate.wrapOutputStream(out));
+ }
+
+ public void finishInputStream(InputStream in) throws IOException
+ {
+ delegate.finishInputStream(in);
+ doFinishInputStream(in);
+ }
+
+ public void finishOutputStream(OutputStream out) throws IOException
+ {
+ delegate.finishOutputStream(out);
+ doFinishOutputStream(out);
+ }
+
+ protected abstract InputStream doWrapInputStream(InputStream in) throws IOException;
+
+ protected abstract OutputStream doWrapOutputStream(OutputStream out) throws IOException;
+
+ protected abstract void doFinishInputStream(InputStream in) throws IOException;
+
+ protected abstract void doFinishOutputStream(OutputStream out) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java index df429483f4..f6c1f324a6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java @@ -1,135 +1,135 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.FilterWriter; -import java.io.IOException; -import java.io.Writer; -import java.security.MessageDigest; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class DigestWriter extends FilterWriter -{ - private boolean on = true; - - /** - * The message digest associated with this stream. - */ - protected MessageDigest digest; - - /** - * Creates a digest writer, using the specified writer and message digest. - * - * @param writer - * the writer. - * @param digest - * the message digest to associate with this writer. - */ - public DigestWriter(Writer writer, MessageDigest digest) - { - super(writer); - setMessageDigest(digest); - } - - /** - * Returns the message digest associated with this writer. - * - * @return the message digest associated with this writer. - * @see #setMessageDigest(java.security.MessageDigest) - */ - public MessageDigest getMessageDigest() - { - return digest; - } - - /** - * Associates the specified message digest with this writer. - * - * @param digest - * the message digest to be associated with this writer. - * @see #getMessageDigest() - */ - public void setMessageDigest(MessageDigest digest) - { - this.digest = digest; - } - - @Override - public void write(int c) throws IOException - { - if (on) - { - updateDigest(c); - } - - out.write(c); - } - - @Override - public void write(char cbuf[], int off, int len) throws IOException - { - if (on) - { - int end = off + len; - for (int i = off; i < end; i++) - { - updateDigest(cbuf[i]); - } - } - - out.write(cbuf, off, len); - } - - @Override - public void write(String str, int off, int len) throws IOException - { - if (on) - { - int end = off + len; - for (int i = off; i < end; i++) - { - updateDigest(str.charAt(i)); - } - } - - out.write(str, off, len); - } - - private void updateDigest(int c) - { - digest.update((byte)(c >>> 8 & 0xFF)); - digest.update((byte)(c >>> 0 & 0xFF)); - } - - /** - * Turns the digest function on or off. The default is on. When it is on, a call to one of the <code>write</code> - * methods results in an update on the message digest. But when it is off, the message digest is not updated. - * - * @param on - * true to turn the digest function on, false to turn it off. - */ - public void on(boolean on) - { - this.on = on; - } - - /** - * Prints a string representation of this digest output stream and its associated message digest object. - */ - @Override - public String toString() - { - return "[Digest Writer] " + digest.toString(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.FilterWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.security.MessageDigest;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class DigestWriter extends FilterWriter
+{
+ private boolean on = true;
+
+ /**
+ * The message digest associated with this stream.
+ */
+ protected MessageDigest digest;
+
+ /**
+ * Creates a digest writer, using the specified writer and message digest.
+ *
+ * @param writer
+ * the writer.
+ * @param digest
+ * the message digest to associate with this writer.
+ */
+ public DigestWriter(Writer writer, MessageDigest digest)
+ {
+ super(writer);
+ setMessageDigest(digest);
+ }
+
+ /**
+ * Returns the message digest associated with this writer.
+ *
+ * @return the message digest associated with this writer.
+ * @see #setMessageDigest(java.security.MessageDigest)
+ */
+ public MessageDigest getMessageDigest()
+ {
+ return digest;
+ }
+
+ /**
+ * Associates the specified message digest with this writer.
+ *
+ * @param digest
+ * the message digest to be associated with this writer.
+ * @see #getMessageDigest()
+ */
+ public void setMessageDigest(MessageDigest digest)
+ {
+ this.digest = digest;
+ }
+
+ @Override
+ public void write(int c) throws IOException
+ {
+ if (on)
+ {
+ updateDigest(c);
+ }
+
+ out.write(c);
+ }
+
+ @Override
+ public void write(char cbuf[], int off, int len) throws IOException
+ {
+ if (on)
+ {
+ int end = off + len;
+ for (int i = off; i < end; i++)
+ {
+ updateDigest(cbuf[i]);
+ }
+ }
+
+ out.write(cbuf, off, len);
+ }
+
+ @Override
+ public void write(String str, int off, int len) throws IOException
+ {
+ if (on)
+ {
+ int end = off + len;
+ for (int i = off; i < end; i++)
+ {
+ updateDigest(str.charAt(i));
+ }
+ }
+
+ out.write(str, off, len);
+ }
+
+ private void updateDigest(int c)
+ {
+ digest.update((byte)(c >>> 8 & 0xFF));
+ digest.update((byte)(c >>> 0 & 0xFF));
+ }
+
+ /**
+ * Turns the digest function on or off. The default is on. When it is on, a call to one of the <code>write</code>
+ * methods results in an update on the message digest. But when it is off, the message digest is not updated.
+ *
+ * @param on
+ * true to turn the digest function on, false to turn it off.
+ */
+ public void on(boolean on)
+ {
+ this.on = on;
+ }
+
+ /**
+ * Prints a string representation of this digest output stream and its associated message digest object.
+ */
+ @Override
+ public String toString()
+ {
+ return "[Digest Writer] " + digest.toString();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java index 634e0da9f9..d8ded5810d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java @@ -1,120 +1,120 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class ExpectedFileInputStream extends FileInputStream -{ - private long timeout = IOUtil.DEFAULT_TIMEOUT; - - private File file; - - private long expectedSize; - - private long pos; - - public ExpectedFileInputStream(File file, long expectedSize) throws FileNotFoundException - { - super(file); - this.file = file; - this.expectedSize = expectedSize; - } - - public long getTimeout() - { - return timeout; - } - - public void setTimeout(long timeout) - { - this.timeout = timeout; - } - - @Override - public long skip(long n) throws IOException - { - waitForInput(n); - return super.skip(n); - } - - @Override - public int read() throws IOException - { - waitForInput(1L); - return super.read(); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException - { - waitForInput(len); - return super.read(b, off, len); - } - - @Override - public int read(byte[] b) throws IOException - { - return read(b, 0, b.length); - } - - private void waitForInput(long n) throws IOException - { - synchronized (this) - { - n = Math.min(n, expectedSize - pos); - long restSize = file.length() - pos; - long endTime = 0; - - while (restSize < n) - { - long restTime; - if (endTime == 0) - { - endTime = System.currentTimeMillis() + timeout; - restTime = timeout; - } - else - { - restTime = endTime - System.currentTimeMillis(); - } - - if (restTime <= 0) - { - throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath()); - } - - try - { - wait(Math.min(100L, restTime)); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - - restSize = file.length() - pos; - } - - pos += n; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class ExpectedFileInputStream extends FileInputStream
+{
+ private long timeout = IOUtil.DEFAULT_TIMEOUT;
+
+ private File file;
+
+ private long expectedSize;
+
+ private long pos;
+
+ public ExpectedFileInputStream(File file, long expectedSize) throws FileNotFoundException
+ {
+ super(file);
+ this.file = file;
+ this.expectedSize = expectedSize;
+ }
+
+ public long getTimeout()
+ {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout)
+ {
+ this.timeout = timeout;
+ }
+
+ @Override
+ public long skip(long n) throws IOException
+ {
+ waitForInput(n);
+ return super.skip(n);
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ waitForInput(1L);
+ return super.read();
+ }
+
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException
+ {
+ waitForInput(len);
+ return super.read(b, off, len);
+ }
+
+ @Override
+ public int read(byte[] b) throws IOException
+ {
+ return read(b, 0, b.length);
+ }
+
+ private void waitForInput(long n) throws IOException
+ {
+ synchronized (this)
+ {
+ n = Math.min(n, expectedSize - pos);
+ long restSize = file.length() - pos;
+ long endTime = 0;
+
+ while (restSize < n)
+ {
+ long restTime;
+ if (endTime == 0)
+ {
+ endTime = System.currentTimeMillis() + timeout;
+ restTime = timeout;
+ }
+ else
+ {
+ restTime = endTime - System.currentTimeMillis();
+ }
+
+ if (restTime <= 0)
+ {
+ throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath());
+ }
+
+ try
+ {
+ wait(Math.min(100L, restTime));
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+
+ restSize = file.length() - pos;
+ }
+
+ pos += n;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java index 979a758ed9..7692feab8d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java @@ -1,129 +1,129 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.nio.CharBuffer; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class ExpectedFileReader extends FileReader -{ - private long timeout = IOUtil.DEFAULT_TIMEOUT; - - private File file; - - private long expectedSize; - - private long pos; - - public ExpectedFileReader(File file, long expectedSize) throws FileNotFoundException - { - super(file); - this.file = file; - this.expectedSize = expectedSize; - } - - public long getTimeout() - { - return timeout; - } - - public void setTimeout(long timeout) - { - this.timeout = timeout; - } - - @Override - public long skip(long n) throws IOException - { - waitForInput(n); - return super.skip(n); - } - - @Override - public int read() throws IOException - { - waitForInput(1L); - return super.read(); - } - - @Override - public int read(char[] cbuf, int offset, int length) throws IOException - { - waitForInput(length); - return super.read(cbuf, offset, length); - } - - @Override - public int read(CharBuffer target) throws IOException - { - waitForInput(target.remaining()); - return super.read(target); - } - - @Override - public int read(char[] cbuf) throws IOException - { - waitForInput(cbuf.length); - return super.read(cbuf); - } - - private void waitForInput(long n) throws IOException - { - synchronized (this) - { - n = Math.min(n, expectedSize - pos); - long restSize = file.length() - pos; - long endTime = 0; - - while (restSize < n) - { - long restTime; - if (endTime == 0) - { - endTime = System.currentTimeMillis() + timeout; - restTime = timeout; - } - else - { - restTime = endTime - System.currentTimeMillis(); - } - - if (restTime <= 0) - { - throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath()); - } - - try - { - wait(Math.max(100L, restTime)); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - - restSize = file.length() - pos; - } - - pos += n; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.nio.CharBuffer;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class ExpectedFileReader extends FileReader
+{
+ private long timeout = IOUtil.DEFAULT_TIMEOUT;
+
+ private File file;
+
+ private long expectedSize;
+
+ private long pos;
+
+ public ExpectedFileReader(File file, long expectedSize) throws FileNotFoundException
+ {
+ super(file);
+ this.file = file;
+ this.expectedSize = expectedSize;
+ }
+
+ public long getTimeout()
+ {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout)
+ {
+ this.timeout = timeout;
+ }
+
+ @Override
+ public long skip(long n) throws IOException
+ {
+ waitForInput(n);
+ return super.skip(n);
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ waitForInput(1L);
+ return super.read();
+ }
+
+ @Override
+ public int read(char[] cbuf, int offset, int length) throws IOException
+ {
+ waitForInput(length);
+ return super.read(cbuf, offset, length);
+ }
+
+ @Override
+ public int read(CharBuffer target) throws IOException
+ {
+ waitForInput(target.remaining());
+ return super.read(target);
+ }
+
+ @Override
+ public int read(char[] cbuf) throws IOException
+ {
+ waitForInput(cbuf.length);
+ return super.read(cbuf);
+ }
+
+ private void waitForInput(long n) throws IOException
+ {
+ synchronized (this)
+ {
+ n = Math.min(n, expectedSize - pos);
+ long restSize = file.length() - pos;
+ long endTime = 0;
+
+ while (restSize < n)
+ {
+ long restTime;
+ if (endTime == 0)
+ {
+ endTime = System.currentTimeMillis() + timeout;
+ restTime = timeout;
+ }
+ else
+ {
+ restTime = endTime - System.currentTimeMillis();
+ }
+
+ if (restTime <= 0)
+ {
+ throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath());
+ }
+
+ try
+ {
+ wait(Math.max(100L, restTime));
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+
+ restSize = file.length() - pos;
+ }
+
+ pos += n;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java index ad497fed9e..fd731d5f04 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java @@ -1,199 +1,199 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver; - -import java.io.DataInput; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author Eike Stepper - */ -public interface ExtendedDataInput extends DataInput -{ - public byte[] readByteArray() throws IOException; - - public Object readObject() throws IOException; - - public Object readObject(ClassLoader classLoader) throws IOException; - - public Object readObject(ClassResolver classResolver) throws IOException; - - public String readString() throws IOException; - - /** - * @since 3.0 - */ - public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException; - - /** - * @author Eike Stepper - * @since 2.0 - */ - public static class Delegating implements ExtendedDataInput - { - private ExtendedDataInput delegate; - - public Delegating(ExtendedDataInput delegate) - { - this.delegate = delegate; - } - - public ExtendedDataInput getDelegate() - { - return delegate; - } - - public boolean readBoolean() throws IOException - { - return delegate.readBoolean(); - } - - public byte readByte() throws IOException - { - return delegate.readByte(); - } - - public byte[] readByteArray() throws IOException - { - return delegate.readByteArray(); - } - - public char readChar() throws IOException - { - return delegate.readChar(); - } - - public double readDouble() throws IOException - { - return delegate.readDouble(); - } - - public float readFloat() throws IOException - { - return delegate.readFloat(); - } - - public void readFully(byte[] b, int off, int len) throws IOException - { - delegate.readFully(b, off, len); - } - - public void readFully(byte[] b) throws IOException - { - delegate.readFully(b); - } - - public int readInt() throws IOException - { - return delegate.readInt(); - } - - public String readLine() throws IOException - { - return delegate.readLine(); - } - - public long readLong() throws IOException - { - return delegate.readLong(); - } - - public Object readObject() throws IOException - { - return delegate.readObject(); - } - - public Object readObject(ClassLoader classLoader) throws IOException - { - return delegate.readObject(classLoader); - } - - public Object readObject(ClassResolver classResolver) throws IOException - { - return delegate.readObject(classResolver); - } - - public short readShort() throws IOException - { - return delegate.readShort(); - } - - public String readString() throws IOException - { - return delegate.readString(); - } - - /** - * @since 3.0 - */ - public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException - { - return delegate.readEnum(type); - } - - public int readUnsignedByte() throws IOException - { - return delegate.readUnsignedByte(); - } - - public int readUnsignedShort() throws IOException - { - return delegate.readUnsignedShort(); - } - - public String readUTF() throws IOException - { - return delegate.readUTF(); - } - - public int skipBytes(int n) throws IOException - { - return delegate.skipBytes(n); - } - } - - /** - * @author Eike Stepper - * @since 2.0 - */ - @Deprecated - public static class Stream extends InputStream - { - private ExtendedDataInput delegate; - - public Stream(ExtendedDataInput delegate) - { - this.delegate = delegate; - } - - public ExtendedDataInput getDelegate() - { - return delegate; - } - - @Override - public int read() throws IOException - { - try - { - return delegate.readUnsignedByte(); - } - catch (EOFException ex) - { - return -1; - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver;
+
+import java.io.DataInput;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ExtendedDataInput extends DataInput
+{
+ public byte[] readByteArray() throws IOException;
+
+ public Object readObject() throws IOException;
+
+ public Object readObject(ClassLoader classLoader) throws IOException;
+
+ public Object readObject(ClassResolver classResolver) throws IOException;
+
+ public String readString() throws IOException;
+
+ /**
+ * @since 3.0
+ */
+ public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException;
+
+ /**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+ public static class Delegating implements ExtendedDataInput
+ {
+ private ExtendedDataInput delegate;
+
+ public Delegating(ExtendedDataInput delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public ExtendedDataInput getDelegate()
+ {
+ return delegate;
+ }
+
+ public boolean readBoolean() throws IOException
+ {
+ return delegate.readBoolean();
+ }
+
+ public byte readByte() throws IOException
+ {
+ return delegate.readByte();
+ }
+
+ public byte[] readByteArray() throws IOException
+ {
+ return delegate.readByteArray();
+ }
+
+ public char readChar() throws IOException
+ {
+ return delegate.readChar();
+ }
+
+ public double readDouble() throws IOException
+ {
+ return delegate.readDouble();
+ }
+
+ public float readFloat() throws IOException
+ {
+ return delegate.readFloat();
+ }
+
+ public void readFully(byte[] b, int off, int len) throws IOException
+ {
+ delegate.readFully(b, off, len);
+ }
+
+ public void readFully(byte[] b) throws IOException
+ {
+ delegate.readFully(b);
+ }
+
+ public int readInt() throws IOException
+ {
+ return delegate.readInt();
+ }
+
+ public String readLine() throws IOException
+ {
+ return delegate.readLine();
+ }
+
+ public long readLong() throws IOException
+ {
+ return delegate.readLong();
+ }
+
+ public Object readObject() throws IOException
+ {
+ return delegate.readObject();
+ }
+
+ public Object readObject(ClassLoader classLoader) throws IOException
+ {
+ return delegate.readObject(classLoader);
+ }
+
+ public Object readObject(ClassResolver classResolver) throws IOException
+ {
+ return delegate.readObject(classResolver);
+ }
+
+ public short readShort() throws IOException
+ {
+ return delegate.readShort();
+ }
+
+ public String readString() throws IOException
+ {
+ return delegate.readString();
+ }
+
+ /**
+ * @since 3.0
+ */
+ public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException
+ {
+ return delegate.readEnum(type);
+ }
+
+ public int readUnsignedByte() throws IOException
+ {
+ return delegate.readUnsignedByte();
+ }
+
+ public int readUnsignedShort() throws IOException
+ {
+ return delegate.readUnsignedShort();
+ }
+
+ public String readUTF() throws IOException
+ {
+ return delegate.readUTF();
+ }
+
+ public int skipBytes(int n) throws IOException
+ {
+ return delegate.skipBytes(n);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+ @Deprecated
+ public static class Stream extends InputStream
+ {
+ private ExtendedDataInput delegate;
+
+ public Stream(ExtendedDataInput delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public ExtendedDataInput getDelegate()
+ {
+ return delegate;
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ try
+ {
+ return delegate.readUnsignedByte();
+ }
+ catch (EOFException ex)
+ {
+ return -1;
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java index d01ff5199a..1f9b61a241 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java @@ -1,81 +1,81 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * @author Eike Stepper - */ -public class ExtendedDataInputStream extends DataInputStream implements ExtendedDataInput -{ - public ExtendedDataInputStream(InputStream in) - { - super(in); - } - - public byte[] readByteArray() throws IOException - { - return ExtendedIOUtil.readByteArray(this); - } - - public String readString() throws IOException - { - return ExtendedIOUtil.readString(this); - } - - public Object readObject() throws IOException - { - return ExtendedIOUtil.readObject(this); - } - - /** - * @since 3.0 - */ - public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException - { - return ExtendedIOUtil.readEnum(this, type); - } - - public Object readObject(ClassLoader classLoader) throws IOException - { - return ExtendedIOUtil.readObject(this, classLoader); - } - - public Object readObject(ClassResolver classResolver) throws IOException - { - return ExtendedIOUtil.readObject(this, classResolver); - } - - public static ExtendedDataInputStream wrap(InputStream stream) - { - if (stream instanceof ExtendedDataInputStream) - { - return (ExtendedDataInputStream)stream; - } - - return new ExtendedDataInputStream(stream); - } - - public static InputStream unwrap(InputStream stream) - { - if (stream instanceof ExtendedDataInputStream) - { - return ((ExtendedDataInputStream)stream).in; - } - - return stream; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class ExtendedDataInputStream extends DataInputStream implements ExtendedDataInput
+{
+ public ExtendedDataInputStream(InputStream in)
+ {
+ super(in);
+ }
+
+ public byte[] readByteArray() throws IOException
+ {
+ return ExtendedIOUtil.readByteArray(this);
+ }
+
+ public String readString() throws IOException
+ {
+ return ExtendedIOUtil.readString(this);
+ }
+
+ public Object readObject() throws IOException
+ {
+ return ExtendedIOUtil.readObject(this);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException
+ {
+ return ExtendedIOUtil.readEnum(this, type);
+ }
+
+ public Object readObject(ClassLoader classLoader) throws IOException
+ {
+ return ExtendedIOUtil.readObject(this, classLoader);
+ }
+
+ public Object readObject(ClassResolver classResolver) throws IOException
+ {
+ return ExtendedIOUtil.readObject(this, classResolver);
+ }
+
+ public static ExtendedDataInputStream wrap(InputStream stream)
+ {
+ if (stream instanceof ExtendedDataInputStream)
+ {
+ return (ExtendedDataInputStream)stream;
+ }
+
+ return new ExtendedDataInputStream(stream);
+ }
+
+ public static InputStream unwrap(InputStream stream)
+ {
+ if (stream instanceof ExtendedDataInputStream)
+ {
+ return ((ExtendedDataInputStream)stream).in;
+ }
+
+ return stream;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java index b8436d996a..fdf50ae47d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java @@ -1,170 +1,170 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.DataOutput; -import java.io.IOException; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public interface ExtendedDataOutput extends DataOutput -{ - public void writeByteArray(byte[] b) throws IOException; - - public void writeObject(Object object) throws IOException; - - public void writeString(String str) throws IOException; - - /** - * @since 3.0 - */ - public void writeEnum(Enum<?> literal) throws IOException; - - /** - * @author Eike Stepper - * @since 2.0 - */ - public static class Delegating implements ExtendedDataOutput - { - private ExtendedDataOutput delegate; - - public Delegating(ExtendedDataOutput delegate) - { - this.delegate = delegate; - } - - public ExtendedDataOutput getDelegate() - { - return delegate; - } - - public void write(byte[] b, int off, int len) throws IOException - { - delegate.write(b, off, len); - } - - public void write(byte[] b) throws IOException - { - delegate.write(b); - } - - public void write(int b) throws IOException - { - delegate.write(b); - } - - public void writeBoolean(boolean v) throws IOException - { - delegate.writeBoolean(v); - } - - public void writeByte(int v) throws IOException - { - delegate.writeByte(v); - } - - public void writeByteArray(byte[] b) throws IOException - { - delegate.writeByteArray(b); - } - - public void writeBytes(String s) throws IOException - { - delegate.writeBytes(s); - } - - public void writeChar(int v) throws IOException - { - delegate.writeChar(v); - } - - public void writeChars(String s) throws IOException - { - delegate.writeChars(s); - } - - public void writeDouble(double v) throws IOException - { - delegate.writeDouble(v); - } - - public void writeFloat(float v) throws IOException - { - delegate.writeFloat(v); - } - - public void writeInt(int v) throws IOException - { - delegate.writeInt(v); - } - - public void writeLong(long v) throws IOException - { - delegate.writeLong(v); - } - - public void writeObject(Object object) throws IOException - { - delegate.writeObject(object); - } - - public void writeShort(int v) throws IOException - { - delegate.writeShort(v); - } - - public void writeString(String str) throws IOException - { - delegate.writeString(str); - } - - /** - * @since 3.0 - */ - public void writeEnum(Enum<?> literal) throws IOException - { - delegate.writeEnum(literal); - } - - public void writeUTF(String str) throws IOException - { - delegate.writeUTF(str); - } - } - - /** - * @author Eike Stepper - * @since 2.0 - */ - @Deprecated - public static class Stream extends OutputStream - { - private ExtendedDataOutput delegate; - - public Stream(ExtendedDataOutput delegate) - { - this.delegate = delegate; - } - - public ExtendedDataOutput getDelegate() - { - return delegate; - } - - @Override - public void write(int b) throws IOException - { - delegate.write(b); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ExtendedDataOutput extends DataOutput
+{
+ public void writeByteArray(byte[] b) throws IOException;
+
+ public void writeObject(Object object) throws IOException;
+
+ public void writeString(String str) throws IOException;
+
+ /**
+ * @since 3.0
+ */
+ public void writeEnum(Enum<?> literal) throws IOException;
+
+ /**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+ public static class Delegating implements ExtendedDataOutput
+ {
+ private ExtendedDataOutput delegate;
+
+ public Delegating(ExtendedDataOutput delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public ExtendedDataOutput getDelegate()
+ {
+ return delegate;
+ }
+
+ public void write(byte[] b, int off, int len) throws IOException
+ {
+ delegate.write(b, off, len);
+ }
+
+ public void write(byte[] b) throws IOException
+ {
+ delegate.write(b);
+ }
+
+ public void write(int b) throws IOException
+ {
+ delegate.write(b);
+ }
+
+ public void writeBoolean(boolean v) throws IOException
+ {
+ delegate.writeBoolean(v);
+ }
+
+ public void writeByte(int v) throws IOException
+ {
+ delegate.writeByte(v);
+ }
+
+ public void writeByteArray(byte[] b) throws IOException
+ {
+ delegate.writeByteArray(b);
+ }
+
+ public void writeBytes(String s) throws IOException
+ {
+ delegate.writeBytes(s);
+ }
+
+ public void writeChar(int v) throws IOException
+ {
+ delegate.writeChar(v);
+ }
+
+ public void writeChars(String s) throws IOException
+ {
+ delegate.writeChars(s);
+ }
+
+ public void writeDouble(double v) throws IOException
+ {
+ delegate.writeDouble(v);
+ }
+
+ public void writeFloat(float v) throws IOException
+ {
+ delegate.writeFloat(v);
+ }
+
+ public void writeInt(int v) throws IOException
+ {
+ delegate.writeInt(v);
+ }
+
+ public void writeLong(long v) throws IOException
+ {
+ delegate.writeLong(v);
+ }
+
+ public void writeObject(Object object) throws IOException
+ {
+ delegate.writeObject(object);
+ }
+
+ public void writeShort(int v) throws IOException
+ {
+ delegate.writeShort(v);
+ }
+
+ public void writeString(String str) throws IOException
+ {
+ delegate.writeString(str);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void writeEnum(Enum<?> literal) throws IOException
+ {
+ delegate.writeEnum(literal);
+ }
+
+ public void writeUTF(String str) throws IOException
+ {
+ delegate.writeUTF(str);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+ @Deprecated
+ public static class Stream extends OutputStream
+ {
+ private ExtendedDataOutput delegate;
+
+ public Stream(ExtendedDataOutput delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public ExtendedDataOutput getDelegate()
+ {
+ return delegate;
+ }
+
+ @Override
+ public void write(int b) throws IOException
+ {
+ delegate.write(b);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java index 37d883626e..df8d5ec590 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java @@ -1,69 +1,69 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public class ExtendedDataOutputStream extends DataOutputStream implements ExtendedDataOutput -{ - public ExtendedDataOutputStream(OutputStream out) - { - super(out); - } - - public void writeByteArray(byte[] b) throws IOException - { - ExtendedIOUtil.writeByteArray(this, b); - } - - public void writeString(String str) throws IOException - { - ExtendedIOUtil.writeString(this, str); - } - - /** - * @since 3.0 - */ - public void writeEnum(Enum<?> literal) throws IOException - { - ExtendedIOUtil.writeEnum(this, literal); - } - - public void writeObject(Object object) throws IOException - { - ExtendedIOUtil.writeObject(this, object); - } - - public static ExtendedDataOutputStream wrap(OutputStream stream) - { - if (stream instanceof ExtendedDataOutputStream) - { - return (ExtendedDataOutputStream)stream; - } - - return new ExtendedDataOutputStream(stream); - } - - public static OutputStream unwrap(OutputStream stream) - { - if (stream instanceof ExtendedDataOutputStream) - { - return ((ExtendedDataOutputStream)stream).out; - } - - return stream; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class ExtendedDataOutputStream extends DataOutputStream implements ExtendedDataOutput
+{
+ public ExtendedDataOutputStream(OutputStream out)
+ {
+ super(out);
+ }
+
+ public void writeByteArray(byte[] b) throws IOException
+ {
+ ExtendedIOUtil.writeByteArray(this, b);
+ }
+
+ public void writeString(String str) throws IOException
+ {
+ ExtendedIOUtil.writeString(this, str);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void writeEnum(Enum<?> literal) throws IOException
+ {
+ ExtendedIOUtil.writeEnum(this, literal);
+ }
+
+ public void writeObject(Object object) throws IOException
+ {
+ ExtendedIOUtil.writeObject(this, object);
+ }
+
+ public static ExtendedDataOutputStream wrap(OutputStream stream)
+ {
+ if (stream instanceof ExtendedDataOutputStream)
+ {
+ return (ExtendedDataOutputStream)stream;
+ }
+
+ return new ExtendedDataOutputStream(stream);
+ }
+
+ public static OutputStream unwrap(OutputStream stream)
+ {
+ if (stream instanceof ExtendedDataOutputStream)
+ {
+ return ((ExtendedDataOutputStream)stream).out;
+ }
+
+ return stream;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java index 26189cff97..d7d6e940e6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java @@ -1,32 +1,32 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class ExtendedIOAdapter implements ExtendedIOHandler -{ - public ExtendedIOAdapter() - { - } - - public void handleIn(ExtendedDataInputStream in) throws IOException - { - } - - public void handleOut(ExtendedDataOutputStream out) throws IOException - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class ExtendedIOAdapter implements ExtendedIOHandler
+{
+ public ExtendedIOAdapter()
+ {
+ }
+
+ public void handleIn(ExtendedDataInputStream in) throws IOException
+ {
+ }
+
+ public void handleOut(ExtendedDataOutputStream out) throws IOException
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java index 2e628195a1..398a395d66 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface ExtendedIOHandler extends ExtendedInputHandler, ExtendedOutputHandler -{ -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface ExtendedIOHandler extends ExtendedInputHandler, ExtendedOutputHandler
+{
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java index 3b9fd34b9f..70fa06290c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java @@ -1,297 +1,297 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInput; -import java.io.ObjectInputStream; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamClass; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public final class ExtendedIOUtil -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ExtendedIOUtil.class); - - private static final int UTF_HEADER_SIZE = 2; - - private static final int MAX_16_BIT = (1 << 16) - 1; - - private static final int MAX_UTF_LENGTH = MAX_16_BIT - UTF_HEADER_SIZE; - - private static final int MAX_UTF_CHARS = MAX_UTF_LENGTH / 3; - - private static final int MAX_ENUM_LITERALS = Byte.MAX_VALUE - Byte.MIN_VALUE; - - private static final byte NO_ENUM_LITERAL = Byte.MIN_VALUE; - - private ExtendedIOUtil() - { - } - - public static void writeByteArray(DataOutput out, byte[] b) throws IOException - { - if (b != null) - { - out.writeInt(b.length); - out.write(b); - } - else - { - out.writeInt(-1); - } - } - - public static byte[] readByteArray(DataInput in) throws IOException - { - int length = in.readInt(); - if (length < 0) - { - return null; - } - - byte[] b; - try - { - b = new byte[length]; - } - catch (Throwable t) - { - throw new IOException("Unable to allocate " + length + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - in.readFully(b); - return b; - } - - public static void writeObject(final DataOutput out, Object object) throws IOException - { - ObjectOutput wrapper = null; - if (out instanceof ObjectOutput) - { - wrapper = (ObjectOutput)out; - } - else - { - wrapper = new ObjectOutputStream(new OutputStream() - { - @Override - public void write(int b) throws IOException - { - out.writeByte((b & 0xff) + Byte.MIN_VALUE); - } - }); - } - - wrapper.writeObject(object); - } - - public static Object readObject(final DataInput in) throws IOException - { - return readObject(in, (ClassResolver)null); - } - - public static Object readObject(final DataInput in, ClassLoader classLoader) throws IOException - { - return readObject(in, new ClassLoaderClassResolver(classLoader)); - } - - public static Object readObject(final DataInput in, final ClassResolver classResolver) throws IOException - { - ObjectInput wrapper = null; - if (in instanceof ObjectInput) - { - wrapper = (ObjectInput)in; - } - else - { - wrapper = new ObjectInputStream(new InputStream() - { - @Override - public int read() throws IOException - { - return in.readByte() - Byte.MIN_VALUE; - } - }) - - { - @Override - protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException - { - if (classResolver != null) - { - if (TRACER.isEnabled()) - { - TRACER.format("Deserializing class {0}", desc.getName()); //$NON-NLS-1$ - } - - Class<?> c = classResolver.resolveClass(desc); - if (c != null) - { - return c; - } - } - - return super.resolveClass(desc); - } - }; - } - - try - { - return wrapper.readObject(); - } - catch (ClassNotFoundException ex) - { - OM.LOG.error(ex); - throw WrappedException.wrap(ex); - } - } - - public static void writeString(DataOutput out, String str) throws IOException - { - if (str != null) - { - int size = str.length(); - int start = 0; - do - { - out.writeBoolean(true); - int chunk = Math.min(size, MAX_UTF_CHARS); - int end = start + chunk; - out.writeUTF(str.substring(start, end)); - start = end; - size -= chunk; - } while (size > 0); - } - - out.writeBoolean(false); - } - - public static String readString(DataInput in) throws IOException - { - boolean more = in.readBoolean(); - if (!more) - { - return null; - } - - StringBuilder builder = new StringBuilder(); - do - { - String chunk = in.readUTF(); - builder.append(chunk); - more = in.readBoolean(); - } while (more); - - return builder.toString(); - } - - /** - * @since 3.0 - */ - public static void writeEnum(DataOutput out, Enum<?> literal) throws IOException - { - if (literal == null) - { - out.writeByte(NO_ENUM_LITERAL); - } - else - { - getEnumLiterals(literal.getDeclaringClass()); // Check valid size - - int ordinal = literal.ordinal(); - out.writeByte(ordinal + Byte.MIN_VALUE + 1); - } - } - - /** - * @since 3.0 - */ - public static <T extends Enum<?>> T readEnum(DataInput in, Class<T> type) throws IOException - { - T[] literals = getEnumLiterals(type); - - int ordinal = in.readByte(); - if (ordinal == NO_ENUM_LITERAL) - { - return null; - } - - return literals[ordinal - Byte.MIN_VALUE - 1]; - } - - private static <T> T[] getEnumLiterals(Class<T> type) - { - T[] literals = type.getEnumConstants(); - - int size = literals.length; - if (size > MAX_ENUM_LITERALS) - { - throw new AssertionError("Enum too large: " + size + " literals"); - } - - return literals; - } - - /** - * @author Eike Stepper - */ - public interface ClassResolver - { - public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException; - } - - /** - * @author Eike Stepper - */ - public static class ClassLoaderClassResolver implements ClassResolver - { - private static final String STACK_TRACE_ELEMENT = StackTraceElement[].class.getName(); - - private ClassLoader classLoader; - - public ClassLoaderClassResolver(ClassLoader classLoader) - { - this.classLoader = classLoader; - } - - public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException - { - String className = v.getName(); - - try - { - return classLoader.loadClass(className); - } - catch (ClassNotFoundException ex) - { - if (!STACK_TRACE_ELEMENT.equals(className)) - { - OM.LOG.error(ex); - } - - return null; - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public final class ExtendedIOUtil
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ExtendedIOUtil.class);
+
+ private static final int UTF_HEADER_SIZE = 2;
+
+ private static final int MAX_16_BIT = (1 << 16) - 1;
+
+ private static final int MAX_UTF_LENGTH = MAX_16_BIT - UTF_HEADER_SIZE;
+
+ private static final int MAX_UTF_CHARS = MAX_UTF_LENGTH / 3;
+
+ private static final int MAX_ENUM_LITERALS = Byte.MAX_VALUE - Byte.MIN_VALUE;
+
+ private static final byte NO_ENUM_LITERAL = Byte.MIN_VALUE;
+
+ private ExtendedIOUtil()
+ {
+ }
+
+ public static void writeByteArray(DataOutput out, byte[] b) throws IOException
+ {
+ if (b != null)
+ {
+ out.writeInt(b.length);
+ out.write(b);
+ }
+ else
+ {
+ out.writeInt(-1);
+ }
+ }
+
+ public static byte[] readByteArray(DataInput in) throws IOException
+ {
+ int length = in.readInt();
+ if (length < 0)
+ {
+ return null;
+ }
+
+ byte[] b;
+ try
+ {
+ b = new byte[length];
+ }
+ catch (Throwable t)
+ {
+ throw new IOException("Unable to allocate " + length + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ in.readFully(b);
+ return b;
+ }
+
+ public static void writeObject(final DataOutput out, Object object) throws IOException
+ {
+ ObjectOutput wrapper = null;
+ if (out instanceof ObjectOutput)
+ {
+ wrapper = (ObjectOutput)out;
+ }
+ else
+ {
+ wrapper = new ObjectOutputStream(new OutputStream()
+ {
+ @Override
+ public void write(int b) throws IOException
+ {
+ out.writeByte((b & 0xff) + Byte.MIN_VALUE);
+ }
+ });
+ }
+
+ wrapper.writeObject(object);
+ }
+
+ public static Object readObject(final DataInput in) throws IOException
+ {
+ return readObject(in, (ClassResolver)null);
+ }
+
+ public static Object readObject(final DataInput in, ClassLoader classLoader) throws IOException
+ {
+ return readObject(in, new ClassLoaderClassResolver(classLoader));
+ }
+
+ public static Object readObject(final DataInput in, final ClassResolver classResolver) throws IOException
+ {
+ ObjectInput wrapper = null;
+ if (in instanceof ObjectInput)
+ {
+ wrapper = (ObjectInput)in;
+ }
+ else
+ {
+ wrapper = new ObjectInputStream(new InputStream()
+ {
+ @Override
+ public int read() throws IOException
+ {
+ return in.readByte() - Byte.MIN_VALUE;
+ }
+ })
+
+ {
+ @Override
+ protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException
+ {
+ if (classResolver != null)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Deserializing class {0}", desc.getName()); //$NON-NLS-1$
+ }
+
+ Class<?> c = classResolver.resolveClass(desc);
+ if (c != null)
+ {
+ return c;
+ }
+ }
+
+ return super.resolveClass(desc);
+ }
+ };
+ }
+
+ try
+ {
+ return wrapper.readObject();
+ }
+ catch (ClassNotFoundException ex)
+ {
+ OM.LOG.error(ex);
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static void writeString(DataOutput out, String str) throws IOException
+ {
+ if (str != null)
+ {
+ int size = str.length();
+ int start = 0;
+ do
+ {
+ out.writeBoolean(true);
+ int chunk = Math.min(size, MAX_UTF_CHARS);
+ int end = start + chunk;
+ out.writeUTF(str.substring(start, end));
+ start = end;
+ size -= chunk;
+ } while (size > 0);
+ }
+
+ out.writeBoolean(false);
+ }
+
+ public static String readString(DataInput in) throws IOException
+ {
+ boolean more = in.readBoolean();
+ if (!more)
+ {
+ return null;
+ }
+
+ StringBuilder builder = new StringBuilder();
+ do
+ {
+ String chunk = in.readUTF();
+ builder.append(chunk);
+ more = in.readBoolean();
+ } while (more);
+
+ return builder.toString();
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static void writeEnum(DataOutput out, Enum<?> literal) throws IOException
+ {
+ if (literal == null)
+ {
+ out.writeByte(NO_ENUM_LITERAL);
+ }
+ else
+ {
+ getEnumLiterals(literal.getDeclaringClass()); // Check valid size
+
+ int ordinal = literal.ordinal();
+ out.writeByte(ordinal + Byte.MIN_VALUE + 1);
+ }
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static <T extends Enum<?>> T readEnum(DataInput in, Class<T> type) throws IOException
+ {
+ T[] literals = getEnumLiterals(type);
+
+ int ordinal = in.readByte();
+ if (ordinal == NO_ENUM_LITERAL)
+ {
+ return null;
+ }
+
+ return literals[ordinal - Byte.MIN_VALUE - 1];
+ }
+
+ private static <T> T[] getEnumLiterals(Class<T> type)
+ {
+ T[] literals = type.getEnumConstants();
+
+ int size = literals.length;
+ if (size > MAX_ENUM_LITERALS)
+ {
+ throw new AssertionError("Enum too large: " + size + " literals");
+ }
+
+ return literals;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public interface ClassResolver
+ {
+ public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class ClassLoaderClassResolver implements ClassResolver
+ {
+ private static final String STACK_TRACE_ELEMENT = StackTraceElement[].class.getName();
+
+ private ClassLoader classLoader;
+
+ public ClassLoaderClassResolver(ClassLoader classLoader)
+ {
+ this.classLoader = classLoader;
+ }
+
+ public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException
+ {
+ String className = v.getName();
+
+ try
+ {
+ return classLoader.loadClass(className);
+ }
+ catch (ClassNotFoundException ex)
+ {
+ if (!STACK_TRACE_ELEMENT.equals(className))
+ {
+ OM.LOG.error(ex);
+ }
+
+ return null;
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java index 9dc1767785..acbfd304e7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface ExtendedInputHandler -{ - public void handleIn(ExtendedDataInputStream in) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface ExtendedInputHandler
+{
+ public void handleIn(ExtendedDataInputStream in) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java index b83884cb58..f5f4f8fcd8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface ExtendedOutputHandler -{ - public void handleOut(ExtendedDataOutputStream out) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface ExtendedOutputHandler
+{
+ public void handleOut(ExtendedDataOutputStream out) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java index abd0a2e898..5db6013e2a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java @@ -1,100 +1,100 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -/** - * @author Eike Stepper - */ -public class GZIPStreamWrapper implements IStreamWrapper -{ - public GZIPStreamWrapper() - { - } - - public GZIPInputStream wrapInputStream(InputStream in) throws IOException - { - if (in instanceof GZIPInputStream) - { - return (GZIPInputStream)in; - } - - return new GZIPInputStream(in); - } - - public GZIPOutputStream wrapOutputStream(OutputStream out) throws IOException - { - if (out instanceof GZIPOutputStream) - { - return (GZIPOutputStream)out; - } - - return new GZIPOutputStream(out); - } - - public void finishInputStream(InputStream in) throws IOException - { - } - - public void finishOutputStream(OutputStream out) throws IOException - { - ((GZIPOutputStream)out).finish(); - } - - /** - * TODO Move or remove me - */ - public static void main(String[] args) throws Exception - { - final PipedOutputStream pos = new PipedOutputStream(); - final PipedInputStream pis = new PipedInputStream(pos); - - final GZIPOutputStream gos = new GZIPOutputStream(pos); - final byte[] out = "eike".getBytes(); //$NON-NLS-1$ - - Thread thread = new Thread() - { - @Override - public void run() - { - try - { - GZIPInputStream gis = new GZIPInputStream(pis); - - byte[] in = new byte[out.length]; - gis.read(in); - gis.close(); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - }; - - thread.start(); - ConcurrencyUtil.sleep(1000); - - gos.write(out); - gos.close(); - - ConcurrencyUtil.sleep(2000); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class GZIPStreamWrapper implements IStreamWrapper
+{
+ public GZIPStreamWrapper()
+ {
+ }
+
+ public GZIPInputStream wrapInputStream(InputStream in) throws IOException
+ {
+ if (in instanceof GZIPInputStream)
+ {
+ return (GZIPInputStream)in;
+ }
+
+ return new GZIPInputStream(in);
+ }
+
+ public GZIPOutputStream wrapOutputStream(OutputStream out) throws IOException
+ {
+ if (out instanceof GZIPOutputStream)
+ {
+ return (GZIPOutputStream)out;
+ }
+
+ return new GZIPOutputStream(out);
+ }
+
+ public void finishInputStream(InputStream in) throws IOException
+ {
+ }
+
+ public void finishOutputStream(OutputStream out) throws IOException
+ {
+ ((GZIPOutputStream)out).finish();
+ }
+
+ /**
+ * TODO Move or remove me
+ */
+ public static void main(String[] args) throws Exception
+ {
+ final PipedOutputStream pos = new PipedOutputStream();
+ final PipedInputStream pis = new PipedInputStream(pos);
+
+ final GZIPOutputStream gos = new GZIPOutputStream(pos);
+ final byte[] out = "eike".getBytes(); //$NON-NLS-1$
+
+ Thread thread = new Thread()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ GZIPInputStream gis = new GZIPInputStream(pis);
+
+ byte[] in = new byte[out.length];
+ gis.read(in);
+ gis.close();
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+ };
+
+ thread.start();
+ ConcurrencyUtil.sleep(1000);
+
+ gos.write(out);
+ gos.close();
+
+ ConcurrencyUtil.sleep(2000);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java index c5caae83bb..07ecb2bf20 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -/** - * @author Eike Stepper - */ -public interface IOFilter<T> -{ - public T filter(T data); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IOFilter<T>
+{
+ public T filter(T data);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java index 9b954271e2..51c4bfc9cb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.Closeable; -import java.io.IOException; - -/** - * @author Eike Stepper - */ -public interface IORunnable<IO extends Closeable> -{ - public void run(IO io) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IORunnable<IO extends Closeable>
+{
+ public void run(IO io) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java index cb0df1a73d..d2055ce440 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java @@ -1,38 +1,38 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -/** - * @author Eike Stepper - */ -public class IORuntimeException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public IORuntimeException() - { - } - - public IORuntimeException(String message) - { - super(message); - } - - public IORuntimeException(Throwable cause) - { - super(cause); - } - - public IORuntimeException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+/**
+ * @author Eike Stepper
+ */
+public class IORuntimeException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public IORuntimeException()
+ {
+ }
+
+ public IORuntimeException(String message)
+ {
+ super(message);
+ }
+
+ public IORuntimeException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public IORuntimeException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java index 771a72bace..94bf7053ba 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java @@ -1,50 +1,50 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -/** - * @author Eike Stepper - * @since 3.0 - */ -public class IOTimeoutException extends IOException -{ - private static final long serialVersionUID = 1L; - - public IOTimeoutException() - { - } - - public IOTimeoutException(String message, Throwable cause) - { - super(message); - initCause(cause); - } - - public IOTimeoutException(String message) - { - super(message); - } - - public IOTimeoutException(Throwable cause) - { - initCause(cause); - } - - public TimeoutException createTimeoutException() - { - TimeoutException timeoutException = new TimeoutException(getMessage()); - timeoutException.initCause(this); - return timeoutException; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public class IOTimeoutException extends IOException
+{
+ private static final long serialVersionUID = 1L;
+
+ public IOTimeoutException()
+ {
+ }
+
+ public IOTimeoutException(String message, Throwable cause)
+ {
+ super(message);
+ initCause(cause);
+ }
+
+ public IOTimeoutException(String message)
+ {
+ super(message);
+ }
+
+ public IOTimeoutException(Throwable cause)
+ {
+ initCause(cause);
+ }
+
+ public TimeoutException createTimeoutException()
+ {
+ TimeoutException timeoutException = new TimeoutException(getMessage());
+ timeoutException.initCause(this);
+ return timeoutException;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java index 7276328225..935a4dbbd1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java @@ -1,915 +1,915 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.StringUtil; -import org.eclipse.net4j.util.WrappedException; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.CharArrayReader; -import java.io.CharArrayWriter; -import java.io.Closeable; -import java.io.EOFException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.Reader; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * @author Eike Stepper - */ -public final class IOUtil -{ - /** - * @since 3.1 - */ - public static final int EOF = -1; - - /** - * @since 3.1 - */ - public static final long DEFAULT_TIMEOUT = 2500; - - public static final int DEFAULT_BUFFER_SIZE = 8192; - - /** - * @since 2.0 - */ - public static final String WILDCARD_SINGLE_CHAR = "?"; //$NON-NLS-1$ - - /** - * @since 2.0 - */ - public static final String WILDCARD_MULTI_CHARS = "*"; //$NON-NLS-1$ - - /** - * @since 2.0 - */ - public static final String WILDCARD_MULTI_DIRS = "**"; //$NON-NLS-1$ - - private static final char SEP = File.separatorChar; - - private static final char SEP_UNIX = '/'; - - private static final char SEP_WINDOWS = '\\'; - - private IOUtil() - { - } - - public static InputStream IN() - { - return System.in; - } - - public static PrintStream OUT() - { - return System.out; - } - - public static PrintStream ERR() - { - return System.err; - } - - /** - * @since 3.1 - */ - public static void print(StackTraceElement[] elements) - { - print(elements, System.err); - } - - /** - * @since 3.1 - */ - public static void print(StackTraceElement[] elements, PrintStream stream) - { - synchronized (stream) - { - for (int i = 0; i < elements.length; i++) - { - stream.println("\tat " + elements[i]); - } - } - } - - public static void print(Throwable t, PrintStream stream) - { - t.printStackTrace(stream); - } - - public static void print(Throwable t) - { - print(t, System.err); - } - - /** - * @since 2.0 - */ - public static String toString(Throwable t) - { - try - { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - String message = t.getMessage() + "\n"; //$NON-NLS-1$ - bytes.write(message.getBytes()); - print(t, new PrintStream(bytes)); - - return bytes.toString(); - } - catch (IOException ex) - { - throw WrappedException.wrap(ex); - } - } - - public static FileInputStream openInputStream(String fileName) throws IORuntimeException - { - return openInputStream(new File(fileName)); - } - - public static FileInputStream openInputStream(File file) throws IORuntimeException - { - try - { - return new FileInputStream(file); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static FileOutputStream openOutputStream(String fileName) throws IORuntimeException - { - return openOutputStream(new File(fileName)); - } - - public static FileOutputStream openOutputStream(File file) throws IORuntimeException - { - try - { - return new FileOutputStream(file); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static FileReader openReader(String fileName) throws IORuntimeException - { - return openReader(new File(fileName)); - } - - public static FileReader openReader(File file) throws IORuntimeException - { - try - { - return new FileReader(file); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static FileWriter openWriter(String fileName) throws IORuntimeException - { - return openWriter(new File(fileName)); - } - - public static FileWriter openWriter(File file) throws IORuntimeException - { - try - { - return new FileWriter(file); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static Exception closeSilent(Closeable closeable) - { - try - { - if (closeable != null) - { - closeable.close(); - } - - return null; - } - catch (Exception ex) - { - OM.LOG.error(ex); - return ex; - } - } - - public static void close(Closeable closeable) throws IORuntimeException - { - try - { - if (closeable != null) - { - closeable.close(); - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static Exception closeSilent(org.eclipse.net4j.util.collection.Closeable closeable) - { - try - { - if (closeable != null) - { - closeable.close(); - } - - return null; - } - catch (Exception ex) - { - OM.LOG.error(ex); - return ex; - } - } - - public static void close(org.eclipse.net4j.util.collection.Closeable closeable) throws IORuntimeException - { - if (closeable != null) - { - closeable.close(); - } - } - - /** - * @since 2.0 - */ - public static String makeRelative(File file, File toFolder) - { - String fileName = normalizeSeparator(file.getAbsolutePath()); - String folderName = normalizeSeparator(toFolder.getAbsolutePath()); - if (fileName.startsWith(folderName)) - { - String relative = fileName.substring(folderName.length()); - if (relative.startsWith(File.separator)) - { - relative = relative.substring(1); - } - - return relative; - } - - throw new IllegalArgumentException("Different prefixes: " + fileName + " != " + folderName); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /** - * @since 2.0 - */ - public static String normalizeSeparator(String string) - { - if (SEP == SEP_UNIX) - { - return string.replace(SEP_WINDOWS, SEP_UNIX); - } - else if (SEP == SEP_WINDOWS) - { - return string.replace(SEP_UNIX, SEP_WINDOWS); - } - - return string; - } - - public static void mkdirs(File folder) - { - if (!folder.exists()) - { - if (!folder.mkdirs()) - { - throw new IORuntimeException("Unable to create directory " + folder.getAbsolutePath()); //$NON-NLS-1$ - } - } - } - - public static int delete(File file) - { - if (file == null) - { - return 0; - } - - int deleted = 0; - if (file.isDirectory()) - { - for (File child : file.listFiles()) - { - deleted += delete(child); - } - } - - if (file.delete()) - { - return deleted + 1; - } - - file.deleteOnExit(); - return deleted; - } - - public static void copyTree(File source, File target) throws IORuntimeException - { - if (source.isDirectory()) - { - mkdirs(target); - File[] files = source.listFiles(); - for (File file : files) - { - String name = file.getName(); - copyTree(new File(source, name), new File(target, name)); - } - } - else - { - copyFile(source, target); - } - } - - public static void copyTrees(Collection<File> sources, File target) throws IORuntimeException - { - for (File source : sources) - { - copyTree(source, target); - } - } - - public static void copyText(File source, File target, IOFilter<String>... lineFilters) throws IORuntimeException - { - BufferedReader reader = null; - BufferedWriter writer = null; - - try - { - reader = new BufferedReader(openReader(source)); - writer = new BufferedWriter(openWriter(target)); - copyText(reader, writer, lineFilters); - } - finally - { - closeSilent(reader); - closeSilent(writer); - } - } - - public static void copyText(BufferedReader reader, BufferedWriter writer, IOFilter<String>... lineFilters) - { - try - { - String line; - while ((line = reader.readLine()) != null) - { - for (IOFilter<String> lineFilter : lineFilters) - { - line = lineFilter.filter(line); - } - - writer.write(line); - writer.newLine(); - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - /** - * @since 3.1 - */ - public static long copyBinary(InputStream inputStream, OutputStream outputStream) throws IOException - { - if (!(inputStream instanceof BufferedInputStream) && !(inputStream instanceof ByteArrayInputStream)) - { - inputStream = new BufferedInputStream(inputStream); - } - - if (!(outputStream instanceof BufferedOutputStream) && !(outputStream instanceof ByteArrayOutputStream)) - { - outputStream = new BufferedOutputStream(outputStream); - } - - long size = 0; - int b; - while ((b = inputStream.read()) != EOF) - { - outputStream.write(b); - ++size; - } - - outputStream.flush(); - return size; - } - - /** - * @since 3.1 - */ - public static void copyBinary(InputStream inputStream, OutputStream outputStream, long size) throws IOException - { - if (!(inputStream instanceof BufferedInputStream) && !(inputStream instanceof ByteArrayInputStream)) - { - inputStream = new BufferedInputStream(inputStream); - } - - if (!(outputStream instanceof BufferedOutputStream) && !(outputStream instanceof ByteArrayOutputStream)) - { - outputStream = new BufferedOutputStream(outputStream); - } - - while (size > 0L) - { - int b = inputStream.read(); - if (b == EOF) - { - throw new EOFException(); - } - - outputStream.write(b); - --size; - } - - outputStream.flush(); - } - - /** - * @since 3.1 - */ - public static long copyCharacter(Reader reader, Writer writer) throws IOException - { - if (!(reader instanceof BufferedReader) && !(reader instanceof CharArrayReader)) - { - reader = new BufferedReader(reader); - } - - if (!(writer instanceof BufferedWriter) && !(writer instanceof CharArrayWriter)) - { - writer = new BufferedWriter(writer); - } - - long size = 0; - int c; - while ((c = reader.read()) != EOF) - { - writer.write(c); - ++size; - } - - writer.flush(); - return size; - } - - /** - * @since 3.1 - */ - public static void copyCharacter(Reader reader, Writer writer, long size) throws IOException - { - if (!(reader instanceof BufferedReader) && !(reader instanceof CharArrayReader)) - { - reader = new BufferedReader(reader); - } - - if (!(writer instanceof BufferedWriter) && !(writer instanceof CharArrayWriter)) - { - writer = new BufferedWriter(writer); - } - - while (size > 0L) - { - int c = reader.read(); - if (c == EOF) - { - throw new EOFException(); - } - - writer.write(c); - --size; - } - - writer.flush(); - } - - public static int copy(InputStream input, OutputStream output, int size, byte buffer[]) throws IORuntimeException - { - try - { - int written = 0; - int bufferSize = buffer.length; - int n = Math.min(size, bufferSize); - while (n > 0 && (n = input.read(buffer, 0, n)) != -1) - { - output.write(buffer, 0, n); - written += n; - size -= n; - n = Math.min(size, bufferSize); - } - - return written; - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static void copy(InputStream input, OutputStream output, byte buffer[]) throws IORuntimeException - { - try - { - int n; - while ((n = input.read(buffer)) != -1) - { - output.write(buffer, 0, n); - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static void copy(InputStream input, OutputStream output, int bufferSize) throws IORuntimeException - { - copy(input, output, new byte[bufferSize]); - } - - public static void copy(InputStream input, OutputStream output) throws IORuntimeException - { - copy(input, output, DEFAULT_BUFFER_SIZE); - } - - /** - * @see NIOUtil#copyFile(File, File) - */ - public static void copyFile(File source, File target) throws IORuntimeException - { - mkdirs(target.getParentFile()); - FileInputStream input = null; - FileOutputStream output = null; - - try - { - input = openInputStream(source); - output = openOutputStream(target); - copy(input, output); - } - finally - { - closeSilent(input); - closeSilent(output); - } - } - - /** - * @since 3.1 - */ - public static String readTextFile(File file) throws IORuntimeException - { - Reader input = openReader(file); - - try - { - CharArrayWriter output = new CharArrayWriter(); - copyCharacter(input, output); - return output.toString(); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - closeSilent(input); - } - } - - public static byte[] readFile(File file) throws IORuntimeException - { - if (file.length() > Integer.MAX_VALUE) - { - throw new IllegalArgumentException("File too long: " + file.length()); //$NON-NLS-1$ - } - - int size = (int)file.length(); - FileInputStream input = openInputStream(file); - - try - { - ByteArrayOutputStream output = new ByteArrayOutputStream(size); - copy(input, output); - return output.toByteArray(); - } - finally - { - closeSilent(input); - } - } - - public static void writeFile(File file, byte[] bytes) throws IORuntimeException - { - FileOutputStream output = openOutputStream(file); - - try - { - ByteArrayInputStream input = new ByteArrayInputStream(bytes); - copy(input, output); - } - finally - { - closeSilent(output); - } - } - - public static List<File> listDepthFirst(File file) - { - FileCollector collector = new FileCollector(); - visitDepthFirst(file, collector); - return collector.getFiles(); - } - - public static List<File> listBreadthFirst(File file) - { - FileCollector collector = new FileCollector(); - visitBreadthFirst(file, collector); - return collector.getFiles(); - } - - public static void visitDepthFirst(File file, IOVisitor visitor) throws IORuntimeException - { - try - { - boolean recurse = visitor.visit(file); - if (recurse && file.isDirectory()) - { - visitDepthFirst(file.listFiles(), visitor); - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static void visitDepthFirst(File[] files, IOVisitor visitor) - { - for (File file : files) - { - visitDepthFirst(file, visitor); - } - } - - public static void visitBreadthFirst(File file, IOVisitor visitor) throws IORuntimeException - { - File[] files = { file }; - visitBreadthFirst(files, visitor); - } - - public static void visitBreadthFirst(File[] files, IOVisitor visitor) throws IORuntimeException - { - try - { - boolean[] recurse = new boolean[files.length]; - for (int i = 0; i < files.length; i++) - { - File file = files[i]; - recurse[i] = visitor.visit(file); - } - - for (int i = 0; i < files.length; i++) - { - File file = files[i]; - if (file.isDirectory() && recurse[i]) - { - File[] children = file.listFiles(); - for (File child : children) - { - visitBreadthFirst(child, visitor); - } - } - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static <IO extends Closeable> void safeRun(IO io, IORunnable<IO> runnable) throws IORuntimeException - { - try - { - runnable.run(io); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - close(io); - } - } - - public static void safeInput(File file, IORunnable<FileInputStream> runnable) throws IORuntimeException - { - safeRun(openInputStream(file), runnable); - } - - public static void safeOutput(File file, IORunnable<FileOutputStream> runnable) throws IORuntimeException - { - safeRun(openOutputStream(file), runnable); - } - - public static void safeRead(File file, IORunnable<FileReader> runnable) throws IORuntimeException - { - safeRun(openReader(file), runnable); - } - - public static void safeWrite(File file, IORunnable<FileWriter> runnable) throws IORuntimeException - { - safeRun(openWriter(file), runnable); - } - - public static boolean equals(InputStream stream1, InputStream stream2) throws IORuntimeException - { - try - { - for (;;) - { - int byte1 = stream1.read(); - int byte2 = stream2.read(); - - if (byte1 != byte2) - { - return false; - } - - if (byte1 == -1)// Implies byte2 == -1 - { - return true; - } - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public static boolean equals(File file1, File file2) throws IORuntimeException - { - if (file1.length() != file2.length()) - { - return false; - } - - FileInputStream stream1 = null; - FileInputStream stream2 = null; - - try - { - stream1 = new FileInputStream(file1); - stream2 = new FileInputStream(file2); - return equals(stream1, stream2); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - closeSilent(stream1); - closeSilent(stream2); - } - } - - /** - * @since 2.0 - */ - public static List<File> glob(String pattern, File folder) - { - List<File> result = new ArrayList<File>(); - pattern = normalizeSeparator(pattern); - if (pattern.endsWith(File.separator)) - { - pattern += WILDCARD_MULTI_DIRS; - } - - globRecurse(pattern, folder, result); - return result; - } - - private static void globRecurse(String pattern, File folder, List<File> result) - { - int sep = pattern.indexOf(SEP); - if (sep != -1) - { - globSegment(pattern.substring(0, sep), pattern.substring(sep + 1), folder, result); - } - else - { - globSegment(pattern, null, folder, result); - } - } - - private static void globSegment(String segment, String pattern, File folder, List<File> result) - { - boolean multiDirs = false; - if (segment.contains(WILDCARD_MULTI_DIRS)) - { - if (!segment.equals(WILDCARD_MULTI_DIRS)) - { - throw new IllegalArgumentException("Invalid pattern segment: " + segment); //$NON-NLS-1$ - } - - multiDirs = true; - } - - for (File file : folder.listFiles()) - { - String tmp = segment; - if (multiDirs && file.isDirectory()) - { - globRecurse(WILDCARD_MULTI_DIRS + File.separator + pattern, file, result); - tmp = WILDCARD_MULTI_CHARS; - } - - if (StringUtil.glob(tmp, file.getName())) - { - if (pattern == null) - { - // Match - result.add(file); - } - else if (file.isDirectory()) - { - // Recurse - globRecurse(pattern, file, result); - } - } - } - } - - /** - * @author Eike Stepper - */ - public static class FileCollector implements IOVisitor - { - private List<File> files = new ArrayList<File>(); - - public FileCollector() - { - } - - public List<File> getFiles() - { - return files; - } - - public boolean visit(File file) throws IOException - { - files.add(file); - return true; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.StringUtil;
+import org.eclipse.net4j.util.WrappedException;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.Closeable;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author Eike Stepper
+ */
+public final class IOUtil
+{
+ /**
+ * @since 3.1
+ */
+ public static final int EOF = -1;
+
+ /**
+ * @since 3.1
+ */
+ public static final long DEFAULT_TIMEOUT = 2500;
+
+ public static final int DEFAULT_BUFFER_SIZE = 8192;
+
+ /**
+ * @since 2.0
+ */
+ public static final String WILDCARD_SINGLE_CHAR = "?"; //$NON-NLS-1$
+
+ /**
+ * @since 2.0
+ */
+ public static final String WILDCARD_MULTI_CHARS = "*"; //$NON-NLS-1$
+
+ /**
+ * @since 2.0
+ */
+ public static final String WILDCARD_MULTI_DIRS = "**"; //$NON-NLS-1$
+
+ private static final char SEP = File.separatorChar;
+
+ private static final char SEP_UNIX = '/';
+
+ private static final char SEP_WINDOWS = '\\';
+
+ private IOUtil()
+ {
+ }
+
+ public static InputStream IN()
+ {
+ return System.in;
+ }
+
+ public static PrintStream OUT()
+ {
+ return System.out;
+ }
+
+ public static PrintStream ERR()
+ {
+ return System.err;
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static void print(StackTraceElement[] elements)
+ {
+ print(elements, System.err);
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static void print(StackTraceElement[] elements, PrintStream stream)
+ {
+ synchronized (stream)
+ {
+ for (int i = 0; i < elements.length; i++)
+ {
+ stream.println("\tat " + elements[i]);
+ }
+ }
+ }
+
+ public static void print(Throwable t, PrintStream stream)
+ {
+ t.printStackTrace(stream);
+ }
+
+ public static void print(Throwable t)
+ {
+ print(t, System.err);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static String toString(Throwable t)
+ {
+ try
+ {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ String message = t.getMessage() + "\n"; //$NON-NLS-1$
+ bytes.write(message.getBytes());
+ print(t, new PrintStream(bytes));
+
+ return bytes.toString();
+ }
+ catch (IOException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static FileInputStream openInputStream(String fileName) throws IORuntimeException
+ {
+ return openInputStream(new File(fileName));
+ }
+
+ public static FileInputStream openInputStream(File file) throws IORuntimeException
+ {
+ try
+ {
+ return new FileInputStream(file);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static FileOutputStream openOutputStream(String fileName) throws IORuntimeException
+ {
+ return openOutputStream(new File(fileName));
+ }
+
+ public static FileOutputStream openOutputStream(File file) throws IORuntimeException
+ {
+ try
+ {
+ return new FileOutputStream(file);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static FileReader openReader(String fileName) throws IORuntimeException
+ {
+ return openReader(new File(fileName));
+ }
+
+ public static FileReader openReader(File file) throws IORuntimeException
+ {
+ try
+ {
+ return new FileReader(file);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static FileWriter openWriter(String fileName) throws IORuntimeException
+ {
+ return openWriter(new File(fileName));
+ }
+
+ public static FileWriter openWriter(File file) throws IORuntimeException
+ {
+ try
+ {
+ return new FileWriter(file);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static Exception closeSilent(Closeable closeable)
+ {
+ try
+ {
+ if (closeable != null)
+ {
+ closeable.close();
+ }
+
+ return null;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ return ex;
+ }
+ }
+
+ public static void close(Closeable closeable) throws IORuntimeException
+ {
+ try
+ {
+ if (closeable != null)
+ {
+ closeable.close();
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static Exception closeSilent(org.eclipse.net4j.util.collection.Closeable closeable)
+ {
+ try
+ {
+ if (closeable != null)
+ {
+ closeable.close();
+ }
+
+ return null;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ return ex;
+ }
+ }
+
+ public static void close(org.eclipse.net4j.util.collection.Closeable closeable) throws IORuntimeException
+ {
+ if (closeable != null)
+ {
+ closeable.close();
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static String makeRelative(File file, File toFolder)
+ {
+ String fileName = normalizeSeparator(file.getAbsolutePath());
+ String folderName = normalizeSeparator(toFolder.getAbsolutePath());
+ if (fileName.startsWith(folderName))
+ {
+ String relative = fileName.substring(folderName.length());
+ if (relative.startsWith(File.separator))
+ {
+ relative = relative.substring(1);
+ }
+
+ return relative;
+ }
+
+ throw new IllegalArgumentException("Different prefixes: " + fileName + " != " + folderName); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static String normalizeSeparator(String string)
+ {
+ if (SEP == SEP_UNIX)
+ {
+ return string.replace(SEP_WINDOWS, SEP_UNIX);
+ }
+ else if (SEP == SEP_WINDOWS)
+ {
+ return string.replace(SEP_UNIX, SEP_WINDOWS);
+ }
+
+ return string;
+ }
+
+ public static void mkdirs(File folder)
+ {
+ if (!folder.exists())
+ {
+ if (!folder.mkdirs())
+ {
+ throw new IORuntimeException("Unable to create directory " + folder.getAbsolutePath()); //$NON-NLS-1$
+ }
+ }
+ }
+
+ public static int delete(File file)
+ {
+ if (file == null)
+ {
+ return 0;
+ }
+
+ int deleted = 0;
+ if (file.isDirectory())
+ {
+ for (File child : file.listFiles())
+ {
+ deleted += delete(child);
+ }
+ }
+
+ if (file.delete())
+ {
+ return deleted + 1;
+ }
+
+ file.deleteOnExit();
+ return deleted;
+ }
+
+ public static void copyTree(File source, File target) throws IORuntimeException
+ {
+ if (source.isDirectory())
+ {
+ mkdirs(target);
+ File[] files = source.listFiles();
+ for (File file : files)
+ {
+ String name = file.getName();
+ copyTree(new File(source, name), new File(target, name));
+ }
+ }
+ else
+ {
+ copyFile(source, target);
+ }
+ }
+
+ public static void copyTrees(Collection<File> sources, File target) throws IORuntimeException
+ {
+ for (File source : sources)
+ {
+ copyTree(source, target);
+ }
+ }
+
+ public static void copyText(File source, File target, IOFilter<String>... lineFilters) throws IORuntimeException
+ {
+ BufferedReader reader = null;
+ BufferedWriter writer = null;
+
+ try
+ {
+ reader = new BufferedReader(openReader(source));
+ writer = new BufferedWriter(openWriter(target));
+ copyText(reader, writer, lineFilters);
+ }
+ finally
+ {
+ closeSilent(reader);
+ closeSilent(writer);
+ }
+ }
+
+ public static void copyText(BufferedReader reader, BufferedWriter writer, IOFilter<String>... lineFilters)
+ {
+ try
+ {
+ String line;
+ while ((line = reader.readLine()) != null)
+ {
+ for (IOFilter<String> lineFilter : lineFilters)
+ {
+ line = lineFilter.filter(line);
+ }
+
+ writer.write(line);
+ writer.newLine();
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static long copyBinary(InputStream inputStream, OutputStream outputStream) throws IOException
+ {
+ if (!(inputStream instanceof BufferedInputStream) && !(inputStream instanceof ByteArrayInputStream))
+ {
+ inputStream = new BufferedInputStream(inputStream);
+ }
+
+ if (!(outputStream instanceof BufferedOutputStream) && !(outputStream instanceof ByteArrayOutputStream))
+ {
+ outputStream = new BufferedOutputStream(outputStream);
+ }
+
+ long size = 0;
+ int b;
+ while ((b = inputStream.read()) != EOF)
+ {
+ outputStream.write(b);
+ ++size;
+ }
+
+ outputStream.flush();
+ return size;
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static void copyBinary(InputStream inputStream, OutputStream outputStream, long size) throws IOException
+ {
+ if (!(inputStream instanceof BufferedInputStream) && !(inputStream instanceof ByteArrayInputStream))
+ {
+ inputStream = new BufferedInputStream(inputStream);
+ }
+
+ if (!(outputStream instanceof BufferedOutputStream) && !(outputStream instanceof ByteArrayOutputStream))
+ {
+ outputStream = new BufferedOutputStream(outputStream);
+ }
+
+ while (size > 0L)
+ {
+ int b = inputStream.read();
+ if (b == EOF)
+ {
+ throw new EOFException();
+ }
+
+ outputStream.write(b);
+ --size;
+ }
+
+ outputStream.flush();
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static long copyCharacter(Reader reader, Writer writer) throws IOException
+ {
+ if (!(reader instanceof BufferedReader) && !(reader instanceof CharArrayReader))
+ {
+ reader = new BufferedReader(reader);
+ }
+
+ if (!(writer instanceof BufferedWriter) && !(writer instanceof CharArrayWriter))
+ {
+ writer = new BufferedWriter(writer);
+ }
+
+ long size = 0;
+ int c;
+ while ((c = reader.read()) != EOF)
+ {
+ writer.write(c);
+ ++size;
+ }
+
+ writer.flush();
+ return size;
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static void copyCharacter(Reader reader, Writer writer, long size) throws IOException
+ {
+ if (!(reader instanceof BufferedReader) && !(reader instanceof CharArrayReader))
+ {
+ reader = new BufferedReader(reader);
+ }
+
+ if (!(writer instanceof BufferedWriter) && !(writer instanceof CharArrayWriter))
+ {
+ writer = new BufferedWriter(writer);
+ }
+
+ while (size > 0L)
+ {
+ int c = reader.read();
+ if (c == EOF)
+ {
+ throw new EOFException();
+ }
+
+ writer.write(c);
+ --size;
+ }
+
+ writer.flush();
+ }
+
+ public static int copy(InputStream input, OutputStream output, int size, byte buffer[]) throws IORuntimeException
+ {
+ try
+ {
+ int written = 0;
+ int bufferSize = buffer.length;
+ int n = Math.min(size, bufferSize);
+ while (n > 0 && (n = input.read(buffer, 0, n)) != -1)
+ {
+ output.write(buffer, 0, n);
+ written += n;
+ size -= n;
+ n = Math.min(size, bufferSize);
+ }
+
+ return written;
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static void copy(InputStream input, OutputStream output, byte buffer[]) throws IORuntimeException
+ {
+ try
+ {
+ int n;
+ while ((n = input.read(buffer)) != -1)
+ {
+ output.write(buffer, 0, n);
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static void copy(InputStream input, OutputStream output, int bufferSize) throws IORuntimeException
+ {
+ copy(input, output, new byte[bufferSize]);
+ }
+
+ public static void copy(InputStream input, OutputStream output) throws IORuntimeException
+ {
+ copy(input, output, DEFAULT_BUFFER_SIZE);
+ }
+
+ /**
+ * @see NIOUtil#copyFile(File, File)
+ */
+ public static void copyFile(File source, File target) throws IORuntimeException
+ {
+ mkdirs(target.getParentFile());
+ FileInputStream input = null;
+ FileOutputStream output = null;
+
+ try
+ {
+ input = openInputStream(source);
+ output = openOutputStream(target);
+ copy(input, output);
+ }
+ finally
+ {
+ closeSilent(input);
+ closeSilent(output);
+ }
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static String readTextFile(File file) throws IORuntimeException
+ {
+ Reader input = openReader(file);
+
+ try
+ {
+ CharArrayWriter output = new CharArrayWriter();
+ copyCharacter(input, output);
+ return output.toString();
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ closeSilent(input);
+ }
+ }
+
+ public static byte[] readFile(File file) throws IORuntimeException
+ {
+ if (file.length() > Integer.MAX_VALUE)
+ {
+ throw new IllegalArgumentException("File too long: " + file.length()); //$NON-NLS-1$
+ }
+
+ int size = (int)file.length();
+ FileInputStream input = openInputStream(file);
+
+ try
+ {
+ ByteArrayOutputStream output = new ByteArrayOutputStream(size);
+ copy(input, output);
+ return output.toByteArray();
+ }
+ finally
+ {
+ closeSilent(input);
+ }
+ }
+
+ public static void writeFile(File file, byte[] bytes) throws IORuntimeException
+ {
+ FileOutputStream output = openOutputStream(file);
+
+ try
+ {
+ ByteArrayInputStream input = new ByteArrayInputStream(bytes);
+ copy(input, output);
+ }
+ finally
+ {
+ closeSilent(output);
+ }
+ }
+
+ public static List<File> listDepthFirst(File file)
+ {
+ FileCollector collector = new FileCollector();
+ visitDepthFirst(file, collector);
+ return collector.getFiles();
+ }
+
+ public static List<File> listBreadthFirst(File file)
+ {
+ FileCollector collector = new FileCollector();
+ visitBreadthFirst(file, collector);
+ return collector.getFiles();
+ }
+
+ public static void visitDepthFirst(File file, IOVisitor visitor) throws IORuntimeException
+ {
+ try
+ {
+ boolean recurse = visitor.visit(file);
+ if (recurse && file.isDirectory())
+ {
+ visitDepthFirst(file.listFiles(), visitor);
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static void visitDepthFirst(File[] files, IOVisitor visitor)
+ {
+ for (File file : files)
+ {
+ visitDepthFirst(file, visitor);
+ }
+ }
+
+ public static void visitBreadthFirst(File file, IOVisitor visitor) throws IORuntimeException
+ {
+ File[] files = { file };
+ visitBreadthFirst(files, visitor);
+ }
+
+ public static void visitBreadthFirst(File[] files, IOVisitor visitor) throws IORuntimeException
+ {
+ try
+ {
+ boolean[] recurse = new boolean[files.length];
+ for (int i = 0; i < files.length; i++)
+ {
+ File file = files[i];
+ recurse[i] = visitor.visit(file);
+ }
+
+ for (int i = 0; i < files.length; i++)
+ {
+ File file = files[i];
+ if (file.isDirectory() && recurse[i])
+ {
+ File[] children = file.listFiles();
+ for (File child : children)
+ {
+ visitBreadthFirst(child, visitor);
+ }
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static <IO extends Closeable> void safeRun(IO io, IORunnable<IO> runnable) throws IORuntimeException
+ {
+ try
+ {
+ runnable.run(io);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ close(io);
+ }
+ }
+
+ public static void safeInput(File file, IORunnable<FileInputStream> runnable) throws IORuntimeException
+ {
+ safeRun(openInputStream(file), runnable);
+ }
+
+ public static void safeOutput(File file, IORunnable<FileOutputStream> runnable) throws IORuntimeException
+ {
+ safeRun(openOutputStream(file), runnable);
+ }
+
+ public static void safeRead(File file, IORunnable<FileReader> runnable) throws IORuntimeException
+ {
+ safeRun(openReader(file), runnable);
+ }
+
+ public static void safeWrite(File file, IORunnable<FileWriter> runnable) throws IORuntimeException
+ {
+ safeRun(openWriter(file), runnable);
+ }
+
+ public static boolean equals(InputStream stream1, InputStream stream2) throws IORuntimeException
+ {
+ try
+ {
+ for (;;)
+ {
+ int byte1 = stream1.read();
+ int byte2 = stream2.read();
+
+ if (byte1 != byte2)
+ {
+ return false;
+ }
+
+ if (byte1 == -1)// Implies byte2 == -1
+ {
+ return true;
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public static boolean equals(File file1, File file2) throws IORuntimeException
+ {
+ if (file1.length() != file2.length())
+ {
+ return false;
+ }
+
+ FileInputStream stream1 = null;
+ FileInputStream stream2 = null;
+
+ try
+ {
+ stream1 = new FileInputStream(file1);
+ stream2 = new FileInputStream(file2);
+ return equals(stream1, stream2);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ closeSilent(stream1);
+ closeSilent(stream2);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static List<File> glob(String pattern, File folder)
+ {
+ List<File> result = new ArrayList<File>();
+ pattern = normalizeSeparator(pattern);
+ if (pattern.endsWith(File.separator))
+ {
+ pattern += WILDCARD_MULTI_DIRS;
+ }
+
+ globRecurse(pattern, folder, result);
+ return result;
+ }
+
+ private static void globRecurse(String pattern, File folder, List<File> result)
+ {
+ int sep = pattern.indexOf(SEP);
+ if (sep != -1)
+ {
+ globSegment(pattern.substring(0, sep), pattern.substring(sep + 1), folder, result);
+ }
+ else
+ {
+ globSegment(pattern, null, folder, result);
+ }
+ }
+
+ private static void globSegment(String segment, String pattern, File folder, List<File> result)
+ {
+ boolean multiDirs = false;
+ if (segment.contains(WILDCARD_MULTI_DIRS))
+ {
+ if (!segment.equals(WILDCARD_MULTI_DIRS))
+ {
+ throw new IllegalArgumentException("Invalid pattern segment: " + segment); //$NON-NLS-1$
+ }
+
+ multiDirs = true;
+ }
+
+ for (File file : folder.listFiles())
+ {
+ String tmp = segment;
+ if (multiDirs && file.isDirectory())
+ {
+ globRecurse(WILDCARD_MULTI_DIRS + File.separator + pattern, file, result);
+ tmp = WILDCARD_MULTI_CHARS;
+ }
+
+ if (StringUtil.glob(tmp, file.getName()))
+ {
+ if (pattern == null)
+ {
+ // Match
+ result.add(file);
+ }
+ else if (file.isDirectory())
+ {
+ // Recurse
+ globRecurse(pattern, file, result);
+ }
+ }
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class FileCollector implements IOVisitor
+ {
+ private List<File> files = new ArrayList<File>();
+
+ public FileCollector()
+ {
+ }
+
+ public List<File> getFiles()
+ {
+ return files;
+ }
+
+ public boolean visit(File file) throws IOException
+ {
+ files.add(file);
+ return true;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java index 848e479b18..8a8679feb1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.File; -import java.io.IOException; - -/** - * @author Eike Stepper - */ -public interface IOVisitor -{ - public boolean visit(File file) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IOVisitor
+{
+ public boolean visit(File file) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java index 908671b82e..cd299367be 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public interface IStreamWrapper -{ - public InputStream wrapInputStream(InputStream in) throws IOException; - - public OutputStream wrapOutputStream(OutputStream out) throws IOException; - - public void finishInputStream(InputStream in) throws IOException; - - public void finishOutputStream(OutputStream out) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IStreamWrapper
+{
+ public InputStream wrapInputStream(InputStream in) throws IOException;
+
+ public OutputStream wrapOutputStream(OutputStream out) throws IOException;
+
+ public void finishInputStream(InputStream in) throws IOException;
+
+ public void finishOutputStream(OutputStream out) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java index 9f1866429c..0780744c0a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java @@ -1,112 +1,112 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * @author Eike Stepper - * @since 3.2 - */ -public class LimitedInputStream extends InputStream -{ - private InputStream in; - - private long remaining; - - private long remainingAtMark = 0; - - public LimitedInputStream(InputStream in, long length) - { - this.in = in; - remaining = length; - } - - @Override - public int read() throws IOException - { - if ((remaining -= 1) < 0) - { - return -1; - } - - return in.read(); - } - - @Override - public int read(byte[] cbuf, int off, int len) throws IOException - { - if (remaining <= 0) - { - return -1; - } - - if (len > remaining) - { - len = (int)remaining; - } - - len = in.read(cbuf, off, len); - if (len > 0) - { - remaining -= len; - } - else - { - remaining -= remaining; - } - - return len; - } - - @Override - public long skip(long n) throws IOException - { - if (n > remaining) - { - n = remaining; - } - - remaining -= n = in.skip(n); - return n; - } - - @Override - public boolean markSupported() - { - return in.markSupported(); - } - - @Override - public synchronized void mark(int readlimit) - { - if (markSupported()) - { - in.mark(readlimit); - remainingAtMark = remaining; - } - } - - @Override - public synchronized void reset() throws IOException - { - in.reset(); - remaining = remainingAtMark; - } - - @Override - public void close() throws IOException - { - remaining = 0; - in.close(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public class LimitedInputStream extends InputStream
+{
+ private InputStream in;
+
+ private long remaining;
+
+ private long remainingAtMark = 0;
+
+ public LimitedInputStream(InputStream in, long length)
+ {
+ this.in = in;
+ remaining = length;
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ if ((remaining -= 1) < 0)
+ {
+ return -1;
+ }
+
+ return in.read();
+ }
+
+ @Override
+ public int read(byte[] cbuf, int off, int len) throws IOException
+ {
+ if (remaining <= 0)
+ {
+ return -1;
+ }
+
+ if (len > remaining)
+ {
+ len = (int)remaining;
+ }
+
+ len = in.read(cbuf, off, len);
+ if (len > 0)
+ {
+ remaining -= len;
+ }
+ else
+ {
+ remaining -= remaining;
+ }
+
+ return len;
+ }
+
+ @Override
+ public long skip(long n) throws IOException
+ {
+ if (n > remaining)
+ {
+ n = remaining;
+ }
+
+ remaining -= n = in.skip(n);
+ return n;
+ }
+
+ @Override
+ public boolean markSupported()
+ {
+ return in.markSupported();
+ }
+
+ @Override
+ public synchronized void mark(int readlimit)
+ {
+ if (markSupported())
+ {
+ in.mark(readlimit);
+ remainingAtMark = remaining;
+ }
+ }
+
+ @Override
+ public synchronized void reset() throws IOException
+ {
+ in.reset();
+ remaining = remainingAtMark;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ remaining = 0;
+ in.close();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java index 0e3277c0f3..e1839cfbf9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java @@ -1,112 +1,112 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.Reader; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class LimitedReader extends Reader -{ - private Reader in; - - private long remaining; - - private long remainingAtMark = 0; - - public LimitedReader(Reader in, long length) - { - this.in = in; - remaining = length; - } - - @Override - public int read() throws IOException - { - if ((remaining -= 1) < 0) - { - return -1; - } - - return in.read(); - } - - @Override - public int read(char[] cbuf, int off, int len) throws IOException - { - if (remaining <= 0) - { - return -1; - } - - if (len > remaining) - { - len = (int)remaining; - } - - len = in.read(cbuf, off, len); - if (len > 0) - { - remaining -= len; - } - else - { - remaining -= remaining; - } - - return len; - } - - @Override - public long skip(long n) throws IOException - { - if (n > remaining) - { - n = remaining; - } - - remaining -= n = in.skip(n); - return n; - } - - @Override - public boolean markSupported() - { - return in.markSupported(); - } - - @Override - public void mark(int readlimit) throws IOException - { - if (markSupported()) - { - in.mark(readlimit); - remainingAtMark = remaining; - } - } - - @Override - public void reset() throws IOException - { - in.reset(); - remaining = remainingAtMark; - } - - @Override - public void close() throws IOException - { - remaining = 0; - in.close(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.Reader;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class LimitedReader extends Reader
+{
+ private Reader in;
+
+ private long remaining;
+
+ private long remainingAtMark = 0;
+
+ public LimitedReader(Reader in, long length)
+ {
+ this.in = in;
+ remaining = length;
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ if ((remaining -= 1) < 0)
+ {
+ return -1;
+ }
+
+ return in.read();
+ }
+
+ @Override
+ public int read(char[] cbuf, int off, int len) throws IOException
+ {
+ if (remaining <= 0)
+ {
+ return -1;
+ }
+
+ if (len > remaining)
+ {
+ len = (int)remaining;
+ }
+
+ len = in.read(cbuf, off, len);
+ if (len > 0)
+ {
+ remaining -= len;
+ }
+ else
+ {
+ remaining -= remaining;
+ }
+
+ return len;
+ }
+
+ @Override
+ public long skip(long n) throws IOException
+ {
+ if (n > remaining)
+ {
+ n = remaining;
+ }
+
+ remaining -= n = in.skip(n);
+ return n;
+ }
+
+ @Override
+ public boolean markSupported()
+ {
+ return in.markSupported();
+ }
+
+ @Override
+ public void mark(int readlimit) throws IOException
+ {
+ if (markSupported())
+ {
+ in.mark(readlimit);
+ remainingAtMark = remaining;
+ }
+ }
+
+ @Override
+ public void reset() throws IOException
+ {
+ in.reset();
+ remaining = remainingAtMark;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ remaining = 0;
+ in.close();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java index f950112a8d..cff41b6bd9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java @@ -1,219 +1,219 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.ImplementationError; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.channels.FileChannel; - -/** - * @author Eike Stepper - */ -public final class NIOUtil -{ - private NIOUtil() - { - } - - /** - * TODO Look at {@link #copy(File, File, boolean)} - */ - public static void copyFile(File source, File target) - { - // http://www.javalobby.org/java/forums/t17036.html - // http://java.sun.com/developer/JDCTechTips/2002/tt0507.html#tip1 - FileChannel sourceChannel = null; - FileChannel targetChannel = null; - - try - { - if (!target.getParentFile().exists()) - { - target.getParentFile().mkdirs(); - } - - if (!target.exists()) - { - target.createNewFile(); - } - - sourceChannel = new FileInputStream(source).getChannel(); - targetChannel = new FileOutputStream(target).getChannel(); - - long size = sourceChannel.size(); - long transfered = sourceChannel.transferTo(0, size, targetChannel); - if (transfered != size) - { - throw new ImplementationError("Seems as if a loop must be implemented here"); //$NON-NLS-1$ - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - IOUtil.closeSilent(sourceChannel); - IOUtil.closeSilent(targetChannel); - } - } - - /** - * Copy source file to destination. If destination is a path then source file name is appended. If destination file - * exists then: overwrite=true - destination file is replaced; overwite=false - exception is thrown. - * - * @param src - * source file - * @param dst - * destination file or path - * @param overwrite - * overwrite destination file - * @exception IOException - * I/O problem - */ - @SuppressWarnings("unused") - private static void copy(final File src, File dst, final boolean overwrite) throws IOException - { - if (!src.isFile() || !src.exists()) - { - throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); //$NON-NLS-1$ //$NON-NLS-2$ - } - - if (dst.exists()) - { - if (dst.isDirectory()) - { - // name - dst = new File(dst, src.getName()); - } - else if (dst.isFile()) - { - if (!overwrite) - { - throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else - { - throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - - File dstParent = dst.getParentFile(); - if (!dstParent.exists()) - { - if (!dstParent.mkdirs()) - { - throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); //$NON-NLS-1$ - } - } - - long fileSize = src.length(); - if (fileSize > 20971520l) - { // for larger files (20Mb) use streams - FileInputStream in = new FileInputStream(src); - FileOutputStream out = new FileOutputStream(dst); - try - { - int doneCnt = -1, bufSize = 32768; - byte buf[] = new byte[bufSize]; - while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) - { - if (doneCnt == 0) - { - Thread.yield(); - } - else - { - out.write(buf, 0, doneCnt); - } - } - - out.flush(); - } - finally - { - try - { - in.close(); - } - catch (IOException e) - { - } - - try - { - out.close(); - } - catch (IOException e) - { - } - } - } - else - { // smaller files, use channels - FileInputStream fis = new FileInputStream(src); - FileOutputStream fos = new FileOutputStream(dst); - FileChannel in = fis.getChannel(), out = fos.getChannel(); - - try - { - long offs = 0, doneCnt = 0, copyCnt = Math.min(65536, fileSize); - do - { - doneCnt = in.transferTo(offs, copyCnt, out); - offs += doneCnt; - fileSize -= doneCnt; - } - - while (fileSize > 0); - } - finally - { // cleanup - try - { - in.close(); - } - catch (IOException e) - { - } - - try - { - out.close(); - } - catch (IOException e) - { - } - - try - { - fis.close(); - } - catch (IOException e) - { - } - - try - { - fos.close(); - } - catch (IOException ex) - { - } - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.ImplementationError;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+
+/**
+ * @author Eike Stepper
+ */
+public final class NIOUtil
+{
+ private NIOUtil()
+ {
+ }
+
+ /**
+ * TODO Look at {@link #copy(File, File, boolean)}
+ */
+ public static void copyFile(File source, File target)
+ {
+ // http://www.javalobby.org/java/forums/t17036.html
+ // http://java.sun.com/developer/JDCTechTips/2002/tt0507.html#tip1
+ FileChannel sourceChannel = null;
+ FileChannel targetChannel = null;
+
+ try
+ {
+ if (!target.getParentFile().exists())
+ {
+ target.getParentFile().mkdirs();
+ }
+
+ if (!target.exists())
+ {
+ target.createNewFile();
+ }
+
+ sourceChannel = new FileInputStream(source).getChannel();
+ targetChannel = new FileOutputStream(target).getChannel();
+
+ long size = sourceChannel.size();
+ long transfered = sourceChannel.transferTo(0, size, targetChannel);
+ if (transfered != size)
+ {
+ throw new ImplementationError("Seems as if a loop must be implemented here"); //$NON-NLS-1$
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ IOUtil.closeSilent(sourceChannel);
+ IOUtil.closeSilent(targetChannel);
+ }
+ }
+
+ /**
+ * Copy source file to destination. If destination is a path then source file name is appended. If destination file
+ * exists then: overwrite=true - destination file is replaced; overwite=false - exception is thrown.
+ *
+ * @param src
+ * source file
+ * @param dst
+ * destination file or path
+ * @param overwrite
+ * overwrite destination file
+ * @exception IOException
+ * I/O problem
+ */
+ @SuppressWarnings("unused")
+ private static void copy(final File src, File dst, final boolean overwrite) throws IOException
+ {
+ if (!src.isFile() || !src.exists())
+ {
+ throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ if (dst.exists())
+ {
+ if (dst.isDirectory())
+ {
+ // name
+ dst = new File(dst, src.getName());
+ }
+ else if (dst.isFile())
+ {
+ if (!overwrite)
+ {
+ throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ else
+ {
+ throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+
+ File dstParent = dst.getParentFile();
+ if (!dstParent.exists())
+ {
+ if (!dstParent.mkdirs())
+ {
+ throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); //$NON-NLS-1$
+ }
+ }
+
+ long fileSize = src.length();
+ if (fileSize > 20971520l)
+ { // for larger files (20Mb) use streams
+ FileInputStream in = new FileInputStream(src);
+ FileOutputStream out = new FileOutputStream(dst);
+ try
+ {
+ int doneCnt = -1, bufSize = 32768;
+ byte buf[] = new byte[bufSize];
+ while ((doneCnt = in.read(buf, 0, bufSize)) >= 0)
+ {
+ if (doneCnt == 0)
+ {
+ Thread.yield();
+ }
+ else
+ {
+ out.write(buf, 0, doneCnt);
+ }
+ }
+
+ out.flush();
+ }
+ finally
+ {
+ try
+ {
+ in.close();
+ }
+ catch (IOException e)
+ {
+ }
+
+ try
+ {
+ out.close();
+ }
+ catch (IOException e)
+ {
+ }
+ }
+ }
+ else
+ { // smaller files, use channels
+ FileInputStream fis = new FileInputStream(src);
+ FileOutputStream fos = new FileOutputStream(dst);
+ FileChannel in = fis.getChannel(), out = fos.getChannel();
+
+ try
+ {
+ long offs = 0, doneCnt = 0, copyCnt = Math.min(65536, fileSize);
+ do
+ {
+ doneCnt = in.transferTo(offs, copyCnt, out);
+ offs += doneCnt;
+ fileSize -= doneCnt;
+ }
+
+ while (fileSize > 0);
+ }
+ finally
+ { // cleanup
+ try
+ {
+ in.close();
+ }
+ catch (IOException e)
+ {
+ }
+
+ try
+ {
+ out.close();
+ }
+ catch (IOException e)
+ {
+ }
+
+ try
+ {
+ fis.close();
+ }
+ catch (IOException e)
+ {
+ }
+
+ try
+ {
+ fos.close();
+ }
+ catch (IOException ex)
+ {
+ }
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java index d25d8ed658..661d147503 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java @@ -1,231 +1,231 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; - -/** - * @author Eike Stepper - */ -public abstract class SortedFileMap<K extends Comparable<K>, V> implements Closeable -{ - private File file; - - private RandomAccessFile randomAccessFile; - - private ExtendedDataInput input; - - private ExtendedDataOutput output; - - private long entrySize; - - private long entryCount; - - /** - * @see RandomAccessFile#RandomAccessFile(File, String) - */ - public SortedFileMap(File file, String mode) - { - try - { - this.file = file; - randomAccessFile = new RandomAccessFile(file, mode); - input = new DataInputExtender(randomAccessFile); - output = new DataOutputExtender(randomAccessFile); - entrySize = getKeySize() + getValueSize(); - entryCount = randomAccessFile.length() / entrySize; - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public void close() throws IOException - { - IOUtil.close(randomAccessFile); - } - - public File getFile() - { - return file; - } - - public RandomAccessFile getRandomAccessFile() - { - return randomAccessFile; - } - - public long getEntryCount() - { - return entryCount; - } - - public int getEntrySize() - { - return (int)entrySize; - } - - public long getPosition(long index) - { - return index * entrySize; - } - - public long getValuePosition(long index) - { - return getPosition(index) + getKeySize(); - } - - public K getMaxKey() - { - if (entryCount == 0) - { - return null; - } - - return getKey(entryCount - 1); - } - - public K getKey(long index) - { - try - { - long pos = getPosition(index); - randomAccessFile.seek(pos); - return readKey(input); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public V getValue(long index) - { - try - { - long pos = getValuePosition(index); - randomAccessFile.seek(pos); - return readValue(input); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public V get(K key) - { - try - { - long index = search(key); - if (index < 0) - { - return null; - } - - return readValue(input); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - public V put(K key, V value) - { - try - { - long index = search(key); - if (index >= 0) - { - long pos = getValuePosition(index); - randomAccessFile.seek(pos); - V oldValue = readValue(input); - randomAccessFile.seek(pos); - writeValue(output, value); - return oldValue; - } - - index = -index - 1; - for (long i = entryCount; i > index; --i) - { - randomAccessFile.seek(getPosition(i - 1)); - K k = readKey(input); - randomAccessFile.seek(getValuePosition(i - 1)); - V v = readValue(input); - - randomAccessFile.seek(getPosition(i)); - writeKey(output, k); - randomAccessFile.seek(getValuePosition(i)); - writeValue(output, v); - } - - ++entryCount; - randomAccessFile.seek(getPosition(index)); - writeKey(output, key); - randomAccessFile.seek(getValuePosition(index)); - writeValue(output, value); - return null; - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - /** - * @return The index of the entry with the given key if the key exists, <code>-(insertionIndex + 1)</code> otherwise. - */ - protected long search(K key) throws IOException - { - long low = 0; - long high = entryCount - 1; - - while (low <= high) - { - long mid = low + high >> 1; - randomAccessFile.seek(getPosition(mid)); - Comparable<K> midVal = readKey(input); - int cmp = midVal.compareTo(key); - - if (cmp < 0) - { - low = mid + 1; - } - else if (cmp > 0) - { - high = mid - 1; - } - else - { - return mid; // key found - } - } - - return -(low + 1); // key not found. - } - - public abstract int getKeySize(); - - protected abstract K readKey(ExtendedDataInput in) throws IOException; - - protected abstract void writeKey(ExtendedDataOutput out, K key) throws IOException; - - public abstract int getValueSize(); - - protected abstract V readValue(ExtendedDataInput in) throws IOException; - - protected abstract void writeValue(ExtendedDataOutput out, V value) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class SortedFileMap<K extends Comparable<K>, V> implements Closeable
+{
+ private File file;
+
+ private RandomAccessFile randomAccessFile;
+
+ private ExtendedDataInput input;
+
+ private ExtendedDataOutput output;
+
+ private long entrySize;
+
+ private long entryCount;
+
+ /**
+ * @see RandomAccessFile#RandomAccessFile(File, String)
+ */
+ public SortedFileMap(File file, String mode)
+ {
+ try
+ {
+ this.file = file;
+ randomAccessFile = new RandomAccessFile(file, mode);
+ input = new DataInputExtender(randomAccessFile);
+ output = new DataOutputExtender(randomAccessFile);
+ entrySize = getKeySize() + getValueSize();
+ entryCount = randomAccessFile.length() / entrySize;
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public void close() throws IOException
+ {
+ IOUtil.close(randomAccessFile);
+ }
+
+ public File getFile()
+ {
+ return file;
+ }
+
+ public RandomAccessFile getRandomAccessFile()
+ {
+ return randomAccessFile;
+ }
+
+ public long getEntryCount()
+ {
+ return entryCount;
+ }
+
+ public int getEntrySize()
+ {
+ return (int)entrySize;
+ }
+
+ public long getPosition(long index)
+ {
+ return index * entrySize;
+ }
+
+ public long getValuePosition(long index)
+ {
+ return getPosition(index) + getKeySize();
+ }
+
+ public K getMaxKey()
+ {
+ if (entryCount == 0)
+ {
+ return null;
+ }
+
+ return getKey(entryCount - 1);
+ }
+
+ public K getKey(long index)
+ {
+ try
+ {
+ long pos = getPosition(index);
+ randomAccessFile.seek(pos);
+ return readKey(input);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public V getValue(long index)
+ {
+ try
+ {
+ long pos = getValuePosition(index);
+ randomAccessFile.seek(pos);
+ return readValue(input);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public V get(K key)
+ {
+ try
+ {
+ long index = search(key);
+ if (index < 0)
+ {
+ return null;
+ }
+
+ return readValue(input);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ public V put(K key, V value)
+ {
+ try
+ {
+ long index = search(key);
+ if (index >= 0)
+ {
+ long pos = getValuePosition(index);
+ randomAccessFile.seek(pos);
+ V oldValue = readValue(input);
+ randomAccessFile.seek(pos);
+ writeValue(output, value);
+ return oldValue;
+ }
+
+ index = -index - 1;
+ for (long i = entryCount; i > index; --i)
+ {
+ randomAccessFile.seek(getPosition(i - 1));
+ K k = readKey(input);
+ randomAccessFile.seek(getValuePosition(i - 1));
+ V v = readValue(input);
+
+ randomAccessFile.seek(getPosition(i));
+ writeKey(output, k);
+ randomAccessFile.seek(getValuePosition(i));
+ writeValue(output, v);
+ }
+
+ ++entryCount;
+ randomAccessFile.seek(getPosition(index));
+ writeKey(output, key);
+ randomAccessFile.seek(getValuePosition(index));
+ writeValue(output, value);
+ return null;
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ /**
+ * @return The index of the entry with the given key if the key exists, <code>-(insertionIndex + 1)</code> otherwise.
+ */
+ protected long search(K key) throws IOException
+ {
+ long low = 0;
+ long high = entryCount - 1;
+
+ while (low <= high)
+ {
+ long mid = low + high >> 1;
+ randomAccessFile.seek(getPosition(mid));
+ Comparable<K> midVal = readKey(input);
+ int cmp = midVal.compareTo(key);
+
+ if (cmp < 0)
+ {
+ low = mid + 1;
+ }
+ else if (cmp > 0)
+ {
+ high = mid - 1;
+ }
+ else
+ {
+ return mid; // key found
+ }
+ }
+
+ return -(low + 1); // key not found.
+ }
+
+ public abstract int getKeySize();
+
+ protected abstract K readKey(ExtendedDataInput in) throws IOException;
+
+ protected abstract void writeKey(ExtendedDataOutput out, K key) throws IOException;
+
+ public abstract int getValueSize();
+
+ protected abstract V readValue(ExtendedDataInput in) throws IOException;
+
+ protected abstract void writeValue(ExtendedDataOutput out, V value) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java index 730af6582c..857b1aabbf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java @@ -1,58 +1,58 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public class StreamWrapperChain extends DelegatingStreamWrapper -{ - private IStreamWrapper head; - - public StreamWrapperChain(IStreamWrapper head, IStreamWrapper delegate) - { - super(delegate); - this.head = head; - } - - public IStreamWrapper getHead() - { - return head; - } - - @Override - protected InputStream doWrapInputStream(InputStream in) throws IOException - { - return head.wrapInputStream(in); - } - - @Override - protected OutputStream doWrapOutputStream(OutputStream out) throws IOException - { - return head.wrapOutputStream(out); - } - - @Override - protected void doFinishInputStream(InputStream in) throws IOException - { - head.finishInputStream(in); - } - - @Override - protected void doFinishOutputStream(OutputStream out) throws IOException - { - head.finishOutputStream(out); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class StreamWrapperChain extends DelegatingStreamWrapper
+{
+ private IStreamWrapper head;
+
+ public StreamWrapperChain(IStreamWrapper head, IStreamWrapper delegate)
+ {
+ super(delegate);
+ this.head = head;
+ }
+
+ public IStreamWrapper getHead()
+ {
+ return head;
+ }
+
+ @Override
+ protected InputStream doWrapInputStream(InputStream in) throws IOException
+ {
+ return head.wrapInputStream(in);
+ }
+
+ @Override
+ protected OutputStream doWrapOutputStream(OutputStream out) throws IOException
+ {
+ return head.wrapOutputStream(out);
+ }
+
+ @Override
+ protected void doFinishInputStream(InputStream in) throws IOException
+ {
+ head.finishInputStream(in);
+ }
+
+ @Override
+ protected void doFinishOutputStream(OutputStream out) throws IOException
+ {
+ head.finishOutputStream(out);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java index da29d1e742..f6ede4f264 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java @@ -1,456 +1,456 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.CheckUtil; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class StringCompressor implements StringIO -{ - /** - * @since 3.0 - */ - public static boolean BYPASS = false; - - private static final int NULL_ID = 0; - - private static final int INFO_FOLLOWS = Integer.MIN_VALUE; - - private static final byte NOTHING_FOLLOWS = 1; - - private static final byte STRING_FOLLOWS = 2; - - private static final byte ACK_FOLLOWS = 3; - - private static final boolean DEBUG = false; - - private static final byte DEBUG_STRING = -1; - - private static final byte DEBUG_INT = -2; - - private static final byte DEBUG_BYTE = -3; - - private boolean client; - - private int lastID; - - private Map<String, ID> stringToID = new HashMap<String, ID>(); - - private Map<Integer, String> idToString = new HashMap<Integer, String>(); - - private List<Integer> pendingAcknowledgements = new ArrayList<Integer>(); - - /** - * Creates a StringCompressor instance. - * - * @param client - * Must be different on both sides of the stream. - */ - public StringCompressor(boolean client) - { - this.client = client; - } - - public boolean isClient() - { - return client; - } - - public void write(ExtendedDataOutput out, String string) throws IOException - { - if (DEBUG) - { - trace("BEGIN", string); - } - - if (string == null) - { - writeInt(out, NULL_ID); - return; - } - - ID id; - List<Integer> acknowledgements = null; - boolean stringFollows = false; - synchronized (this) - { - id = stringToID.get(string); - if (id == null) - { - lastID += client ? 1 : -1; - id = new ID(lastID); - - stringToID.put(string, id); - idToString.put(id.getValue(), string); - stringFollows = true; - } - else if (!id.isAcknowledged()) - { - stringFollows = true; - } - - if (!pendingAcknowledgements.isEmpty()) - { - acknowledgements = pendingAcknowledgements; - pendingAcknowledgements = new ArrayList<Integer>(); - } - } - - if (stringFollows || acknowledgements != null) - { - writeInt(out, INFO_FOLLOWS); - writeInt(out, id.getValue()); - - if (stringFollows) - { - writeByte(out, STRING_FOLLOWS); - writeString(out, string); - } - - if (acknowledgements != null) - { - for (int ack : acknowledgements) - { - writeByte(out, ACK_FOLLOWS); - writeInt(out, ack); - } - } - - writeByte(out, NOTHING_FOLLOWS); - } - else - { - writeInt(out, id.getValue()); - } - } - - public String read(ExtendedDataInput in) throws IOException - { - if (DEBUG) - { - trace("BEGIN", "?"); - } - - int id = readInt(in); - if (id == NULL_ID) - { - return null; - } - - String string = null; - List<Integer> acks = null; - if (id == INFO_FOLLOWS) - { - id = readInt(in); - - boolean moreInfos = true; - while (moreInfos) - { - byte info = readByte(in); - switch (info) - { - case NOTHING_FOLLOWS: - moreInfos = false; - break; - - case STRING_FOLLOWS: - string = readString(in); - break; - - case ACK_FOLLOWS: - if (acks == null) - { - acks = new ArrayList<Integer>(); - } - - acks.add(readInt(in)); - break; - - default: - throw new IOException("Invalid info: " + info); //$NON-NLS-1$ - } - } - } - - synchronized (this) - { - acknowledge(acks); - if (string != null) - { - stringToID.put(string, new ID(id)); - idToString.put(id, string); - pendingAcknowledgements.add(id); - } - else - { - string = idToString.get(id); - if (string == null) - { - throw new IOException("String ID unknown: " + id); //$NON-NLS-1$ - } - } - } - - return string; - } - - @Override - public String toString() - { - return MessageFormat.format("StringCompressor[client={0}]", client); //$NON-NLS-1$ - } - - private void acknowledge(List<Integer> acks) - { - if (acks != null) - { - for (int value : acks) - { - String string = idToString.get(value); - if (string != null) - { - ID id = stringToID.get(string); - if (id != null) - { - id.setAcknowledged(); - } - } - } - } - } - - private void writeByte(ExtendedDataOutput out, byte value) throws IOException - { - if (DEBUG) - { - trace("writeByte", value); - out.writeByte(DEBUG_BYTE); - } - - out.writeByte(value); - } - - private void writeInt(ExtendedDataOutput out, int value) throws IOException - { - if (DEBUG) - { - trace("writeInt", value); - out.writeByte(DEBUG_INT); - } - - out.writeInt(value); - } - - /** - * @since 3.0 - */ - protected void writeString(ExtendedDataOutput out, String value) throws IOException - { - if (DEBUG) - { - trace("writeString", value); - out.writeByte(DEBUG_STRING); - } - - out.writeString(value); - } - - private byte readByte(ExtendedDataInput in) throws IOException - { - if (DEBUG) - { - byte type = in.readByte(); - if (DEBUG_BYTE != type) - { - throw new IOException("Not a byte value (type=" + type + ")"); //$NON-NLS-1$ - } - } - - byte value = in.readByte(); - if (DEBUG) - { - trace("readByte", value); - } - - return value; - } - - private int readInt(ExtendedDataInput in) throws IOException - { - if (DEBUG) - { - byte type = in.readByte(); - if (DEBUG_INT != type) - { - throw new IOException("Not an integer value (type=" + type + ")"); //$NON-NLS-1$ - } - } - - int value = in.readInt(); - if (DEBUG) - { - trace("readInt", value); - } - - return value; - } - - /** - * @since 3.0 - */ - protected String readString(ExtendedDataInput in) throws IOException - { - if (DEBUG) - { - byte type = in.readByte(); - if (DEBUG_STRING != type) - { - throw new IOException("Not a string value (type=" + type + ")"); //$NON-NLS-1$ - } - } - - String value = in.readString(); - if (DEBUG) - { - trace("readString", value); - } - - return value; - } - - private void trace(String prefix, Object value) - { - if (value instanceof Byte) - { - byte opcode = (Byte)value; - switch (opcode) - { - case NOTHING_FOLLOWS: - value = "NOTHING_FOLLOWS"; - break; - - case STRING_FOLLOWS: - value = "STRING_FOLLOWS"; - break; - - case ACK_FOLLOWS: - value = "STRING_FOLLOWS"; - break; - } - } - - if (value instanceof Integer) - { - int opcode = (Integer)value; - if (opcode == INFO_FOLLOWS) - { - value = "INFO_FOLLOWS"; - } - } - - String msg = "[" + Thread.currentThread().getName() + "] " + prefix + ": " + value; - if (!client) - { - msg = " " + msg; - } - - IOUtil.OUT().println(msg); - } - - /** - * @author Eike Stepper - */ - private static final class ID - { - private int value; - - private boolean acknowledged; - - public ID(int value) - { - CheckUtil.checkArg(value != INFO_FOLLOWS, "value"); - this.value = value; - } - - public int getValue() - { - return value; - } - - public boolean isAcknowledged() - { - return acknowledged; - } - - public void setAcknowledged() - { - acknowledged = true; - } - } - - /** - * @author Eike Stepper - * @since 3.0 - */ - public static class Counting extends StringCompressor - { - private long stringsRead; - - private long stringsWritten; - - public Counting(boolean client) - { - super(client); - } - - public long getStringsRead() - { - return stringsRead; - } - - public long getStringsWritten() - { - return stringsWritten; - } - - @Override - protected String readString(ExtendedDataInput in) throws IOException - { - synchronized (this) - { - ++stringsRead; - } - - return super.readString(in); - } - - @Override - protected void writeString(ExtendedDataOutput out, String value) throws IOException - { - synchronized (this) - { - ++stringsWritten; - } - - super.writeString(out, value); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.CheckUtil;
+
+import java.io.IOException;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class StringCompressor implements StringIO
+{
+ /**
+ * @since 3.0
+ */
+ public static boolean BYPASS = false;
+
+ private static final int NULL_ID = 0;
+
+ private static final int INFO_FOLLOWS = Integer.MIN_VALUE;
+
+ private static final byte NOTHING_FOLLOWS = 1;
+
+ private static final byte STRING_FOLLOWS = 2;
+
+ private static final byte ACK_FOLLOWS = 3;
+
+ private static final boolean DEBUG = false;
+
+ private static final byte DEBUG_STRING = -1;
+
+ private static final byte DEBUG_INT = -2;
+
+ private static final byte DEBUG_BYTE = -3;
+
+ private boolean client;
+
+ private int lastID;
+
+ private Map<String, ID> stringToID = new HashMap<String, ID>();
+
+ private Map<Integer, String> idToString = new HashMap<Integer, String>();
+
+ private List<Integer> pendingAcknowledgements = new ArrayList<Integer>();
+
+ /**
+ * Creates a StringCompressor instance.
+ *
+ * @param client
+ * Must be different on both sides of the stream.
+ */
+ public StringCompressor(boolean client)
+ {
+ this.client = client;
+ }
+
+ public boolean isClient()
+ {
+ return client;
+ }
+
+ public void write(ExtendedDataOutput out, String string) throws IOException
+ {
+ if (DEBUG)
+ {
+ trace("BEGIN", string);
+ }
+
+ if (string == null)
+ {
+ writeInt(out, NULL_ID);
+ return;
+ }
+
+ ID id;
+ List<Integer> acknowledgements = null;
+ boolean stringFollows = false;
+ synchronized (this)
+ {
+ id = stringToID.get(string);
+ if (id == null)
+ {
+ lastID += client ? 1 : -1;
+ id = new ID(lastID);
+
+ stringToID.put(string, id);
+ idToString.put(id.getValue(), string);
+ stringFollows = true;
+ }
+ else if (!id.isAcknowledged())
+ {
+ stringFollows = true;
+ }
+
+ if (!pendingAcknowledgements.isEmpty())
+ {
+ acknowledgements = pendingAcknowledgements;
+ pendingAcknowledgements = new ArrayList<Integer>();
+ }
+ }
+
+ if (stringFollows || acknowledgements != null)
+ {
+ writeInt(out, INFO_FOLLOWS);
+ writeInt(out, id.getValue());
+
+ if (stringFollows)
+ {
+ writeByte(out, STRING_FOLLOWS);
+ writeString(out, string);
+ }
+
+ if (acknowledgements != null)
+ {
+ for (int ack : acknowledgements)
+ {
+ writeByte(out, ACK_FOLLOWS);
+ writeInt(out, ack);
+ }
+ }
+
+ writeByte(out, NOTHING_FOLLOWS);
+ }
+ else
+ {
+ writeInt(out, id.getValue());
+ }
+ }
+
+ public String read(ExtendedDataInput in) throws IOException
+ {
+ if (DEBUG)
+ {
+ trace("BEGIN", "?");
+ }
+
+ int id = readInt(in);
+ if (id == NULL_ID)
+ {
+ return null;
+ }
+
+ String string = null;
+ List<Integer> acks = null;
+ if (id == INFO_FOLLOWS)
+ {
+ id = readInt(in);
+
+ boolean moreInfos = true;
+ while (moreInfos)
+ {
+ byte info = readByte(in);
+ switch (info)
+ {
+ case NOTHING_FOLLOWS:
+ moreInfos = false;
+ break;
+
+ case STRING_FOLLOWS:
+ string = readString(in);
+ break;
+
+ case ACK_FOLLOWS:
+ if (acks == null)
+ {
+ acks = new ArrayList<Integer>();
+ }
+
+ acks.add(readInt(in));
+ break;
+
+ default:
+ throw new IOException("Invalid info: " + info); //$NON-NLS-1$
+ }
+ }
+ }
+
+ synchronized (this)
+ {
+ acknowledge(acks);
+ if (string != null)
+ {
+ stringToID.put(string, new ID(id));
+ idToString.put(id, string);
+ pendingAcknowledgements.add(id);
+ }
+ else
+ {
+ string = idToString.get(id);
+ if (string == null)
+ {
+ throw new IOException("String ID unknown: " + id); //$NON-NLS-1$
+ }
+ }
+ }
+
+ return string;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("StringCompressor[client={0}]", client); //$NON-NLS-1$
+ }
+
+ private void acknowledge(List<Integer> acks)
+ {
+ if (acks != null)
+ {
+ for (int value : acks)
+ {
+ String string = idToString.get(value);
+ if (string != null)
+ {
+ ID id = stringToID.get(string);
+ if (id != null)
+ {
+ id.setAcknowledged();
+ }
+ }
+ }
+ }
+ }
+
+ private void writeByte(ExtendedDataOutput out, byte value) throws IOException
+ {
+ if (DEBUG)
+ {
+ trace("writeByte", value);
+ out.writeByte(DEBUG_BYTE);
+ }
+
+ out.writeByte(value);
+ }
+
+ private void writeInt(ExtendedDataOutput out, int value) throws IOException
+ {
+ if (DEBUG)
+ {
+ trace("writeInt", value);
+ out.writeByte(DEBUG_INT);
+ }
+
+ out.writeInt(value);
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected void writeString(ExtendedDataOutput out, String value) throws IOException
+ {
+ if (DEBUG)
+ {
+ trace("writeString", value);
+ out.writeByte(DEBUG_STRING);
+ }
+
+ out.writeString(value);
+ }
+
+ private byte readByte(ExtendedDataInput in) throws IOException
+ {
+ if (DEBUG)
+ {
+ byte type = in.readByte();
+ if (DEBUG_BYTE != type)
+ {
+ throw new IOException("Not a byte value (type=" + type + ")"); //$NON-NLS-1$
+ }
+ }
+
+ byte value = in.readByte();
+ if (DEBUG)
+ {
+ trace("readByte", value);
+ }
+
+ return value;
+ }
+
+ private int readInt(ExtendedDataInput in) throws IOException
+ {
+ if (DEBUG)
+ {
+ byte type = in.readByte();
+ if (DEBUG_INT != type)
+ {
+ throw new IOException("Not an integer value (type=" + type + ")"); //$NON-NLS-1$
+ }
+ }
+
+ int value = in.readInt();
+ if (DEBUG)
+ {
+ trace("readInt", value);
+ }
+
+ return value;
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected String readString(ExtendedDataInput in) throws IOException
+ {
+ if (DEBUG)
+ {
+ byte type = in.readByte();
+ if (DEBUG_STRING != type)
+ {
+ throw new IOException("Not a string value (type=" + type + ")"); //$NON-NLS-1$
+ }
+ }
+
+ String value = in.readString();
+ if (DEBUG)
+ {
+ trace("readString", value);
+ }
+
+ return value;
+ }
+
+ private void trace(String prefix, Object value)
+ {
+ if (value instanceof Byte)
+ {
+ byte opcode = (Byte)value;
+ switch (opcode)
+ {
+ case NOTHING_FOLLOWS:
+ value = "NOTHING_FOLLOWS";
+ break;
+
+ case STRING_FOLLOWS:
+ value = "STRING_FOLLOWS";
+ break;
+
+ case ACK_FOLLOWS:
+ value = "STRING_FOLLOWS";
+ break;
+ }
+ }
+
+ if (value instanceof Integer)
+ {
+ int opcode = (Integer)value;
+ if (opcode == INFO_FOLLOWS)
+ {
+ value = "INFO_FOLLOWS";
+ }
+ }
+
+ String msg = "[" + Thread.currentThread().getName() + "] " + prefix + ": " + value;
+ if (!client)
+ {
+ msg = " " + msg;
+ }
+
+ IOUtil.OUT().println(msg);
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class ID
+ {
+ private int value;
+
+ private boolean acknowledged;
+
+ public ID(int value)
+ {
+ CheckUtil.checkArg(value != INFO_FOLLOWS, "value");
+ this.value = value;
+ }
+
+ public int getValue()
+ {
+ return value;
+ }
+
+ public boolean isAcknowledged()
+ {
+ return acknowledged;
+ }
+
+ public void setAcknowledged()
+ {
+ acknowledged = true;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ * @since 3.0
+ */
+ public static class Counting extends StringCompressor
+ {
+ private long stringsRead;
+
+ private long stringsWritten;
+
+ public Counting(boolean client)
+ {
+ super(client);
+ }
+
+ public long getStringsRead()
+ {
+ return stringsRead;
+ }
+
+ public long getStringsWritten()
+ {
+ return stringsWritten;
+ }
+
+ @Override
+ protected String readString(ExtendedDataInput in) throws IOException
+ {
+ synchronized (this)
+ {
+ ++stringsRead;
+ }
+
+ return super.readString(in);
+ }
+
+ @Override
+ protected void writeString(ExtendedDataOutput out, String value) throws IOException
+ {
+ synchronized (this)
+ {
+ ++stringsWritten;
+ }
+
+ super.writeString(out, value);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java index ed2c261fa6..e522b2532b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java @@ -1,43 +1,43 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface StringIO -{ - public static final StringIO DIRECT = new StringIO() - { - public void write(ExtendedDataOutput out, String string) throws IOException - { - out.writeString(string); - } - - public String read(ExtendedDataInput in) throws IOException - { - return in.readString(); - } - - @Override - public String toString() - { - return "DIRECT"; //$NON-NLS-1$ - } - }; - - public void write(ExtendedDataOutput out, String string) throws IOException; - - public String read(ExtendedDataInput in) throws IOException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface StringIO
+{
+ public static final StringIO DIRECT = new StringIO()
+ {
+ public void write(ExtendedDataOutput out, String string) throws IOException
+ {
+ out.writeString(string);
+ }
+
+ public String read(ExtendedDataInput in) throws IOException
+ {
+ return in.readString();
+ }
+
+ @Override
+ public String toString()
+ {
+ return "DIRECT"; //$NON-NLS-1$
+ }
+ };
+
+ public void write(ExtendedDataOutput out, String string) throws IOException;
+
+ public String read(ExtendedDataInput in) throws IOException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java index c2e178ef58..0d1934e69b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java @@ -1,177 +1,177 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.om.OMPlatform; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * @author Eike Stepper - */ -public final class TMPUtil -{ - /** - * @since 3.0 - */ - public static final String TEMP_FOLDER_PROPERTY = "org.eclipse.net4j.util.io.tmpdir"; - - /** - * @since 2.0 - */ - public static final String SYSTEM_TEMP_FOLDER = OMPlatform.INSTANCE.getProperty("java.io.tmpdir"); //$NON-NLS-1$ - - private static File tempFolder; - - private TMPUtil() - { - } - - /** - * @since 3.0 - */ - public synchronized static File getTempFolder() - { - if (tempFolder == null) - { - String path = OMPlatform.INSTANCE.getProperty(TEMP_FOLDER_PROPERTY); - if (path == null) - { - path = getPathFromUserHome(); - if (path == null) - { - path = SYSTEM_TEMP_FOLDER; - } - } - - tempFolder = new File(path); - - if (!tempFolder.exists()) - { - tempFolder.mkdirs(); - } - } - - return tempFolder; - } - - private static String getPathFromUserHome() - { - File home = new File(OMPlatform.INSTANCE.getProperty("user.home")); - File file = new File(home, TEMP_FOLDER_PROPERTY); - if (file.exists() && file.isFile()) - { - InputStream in = null; - - try - { - in = new FileInputStream(file); - - Properties properties = new Properties(); - properties.load(in); - - return properties.getProperty("path"); - } - catch (Exception ignore) - { - } - finally - { - IOUtil.closeSilent(in); - } - } - - return null; - } - - /** - * @since 3.0 - */ - public static void setTempFolder(String tempFolder) - { - TMPUtil.tempFolder = new File(tempFolder); - } - - public static File createTempFolder() throws IORuntimeException - { - return createTempFolder("tmp"); //$NON-NLS-1$ - } - - public static File createTempFolder(String prefix) throws IORuntimeException - { - return createTempFolder(prefix, ""); //$NON-NLS-1$ - } - - public static File createTempFolder(String prefix, String suffix) throws IORuntimeException - { - return createTempFolder(prefix, suffix, getTempFolder()); - } - - public static File createTempFolder(String prefix, String suffix, File directory) throws IORuntimeException - { - try - { - File tmp = File.createTempFile(prefix, suffix, directory); - String tmpPath = tmp.getAbsolutePath(); - tmp.delete(); - tmp = new File(tmpPath); - tmp.mkdirs(); - return tmp; - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } - - /** - * @since 3.1 - */ - public static File createTempFile() throws IORuntimeException - { - return createTempFile("tmp"); //$NON-NLS-1$ - } - - /** - * @since 3.1 - */ - public static File createTempFile(String prefix) throws IORuntimeException - { - return createTempFile(prefix, ""); //$NON-NLS-1$ - } - - /** - * @since 3.1 - */ - public static File createTempFile(String prefix, String suffix) throws IORuntimeException - { - return createTempFile(prefix, suffix, getTempFolder()); - } - - /** - * @since 3.1 - */ - public static File createTempFile(String prefix, String suffix, File directory) throws IORuntimeException - { - try - { - return File.createTempFile(prefix, suffix, directory); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.om.OMPlatform;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * @author Eike Stepper
+ */
+public final class TMPUtil
+{
+ /**
+ * @since 3.0
+ */
+ public static final String TEMP_FOLDER_PROPERTY = "org.eclipse.net4j.util.io.tmpdir";
+
+ /**
+ * @since 2.0
+ */
+ public static final String SYSTEM_TEMP_FOLDER = OMPlatform.INSTANCE.getProperty("java.io.tmpdir"); //$NON-NLS-1$
+
+ private static File tempFolder;
+
+ private TMPUtil()
+ {
+ }
+
+ /**
+ * @since 3.0
+ */
+ public synchronized static File getTempFolder()
+ {
+ if (tempFolder == null)
+ {
+ String path = OMPlatform.INSTANCE.getProperty(TEMP_FOLDER_PROPERTY);
+ if (path == null)
+ {
+ path = getPathFromUserHome();
+ if (path == null)
+ {
+ path = SYSTEM_TEMP_FOLDER;
+ }
+ }
+
+ tempFolder = new File(path);
+
+ if (!tempFolder.exists())
+ {
+ tempFolder.mkdirs();
+ }
+ }
+
+ return tempFolder;
+ }
+
+ private static String getPathFromUserHome()
+ {
+ File home = new File(OMPlatform.INSTANCE.getProperty("user.home"));
+ File file = new File(home, TEMP_FOLDER_PROPERTY);
+ if (file.exists() && file.isFile())
+ {
+ InputStream in = null;
+
+ try
+ {
+ in = new FileInputStream(file);
+
+ Properties properties = new Properties();
+ properties.load(in);
+
+ return properties.getProperty("path");
+ }
+ catch (Exception ignore)
+ {
+ }
+ finally
+ {
+ IOUtil.closeSilent(in);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static void setTempFolder(String tempFolder)
+ {
+ TMPUtil.tempFolder = new File(tempFolder);
+ }
+
+ public static File createTempFolder() throws IORuntimeException
+ {
+ return createTempFolder("tmp"); //$NON-NLS-1$
+ }
+
+ public static File createTempFolder(String prefix) throws IORuntimeException
+ {
+ return createTempFolder(prefix, ""); //$NON-NLS-1$
+ }
+
+ public static File createTempFolder(String prefix, String suffix) throws IORuntimeException
+ {
+ return createTempFolder(prefix, suffix, getTempFolder());
+ }
+
+ public static File createTempFolder(String prefix, String suffix, File directory) throws IORuntimeException
+ {
+ try
+ {
+ File tmp = File.createTempFile(prefix, suffix, directory);
+ String tmpPath = tmp.getAbsolutePath();
+ tmp.delete();
+ tmp = new File(tmpPath);
+ tmp.mkdirs();
+ return tmp;
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static File createTempFile() throws IORuntimeException
+ {
+ return createTempFile("tmp"); //$NON-NLS-1$
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static File createTempFile(String prefix) throws IORuntimeException
+ {
+ return createTempFile(prefix, ""); //$NON-NLS-1$
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static File createTempFile(String prefix, String suffix) throws IORuntimeException
+ {
+ return createTempFile(prefix, suffix, getTempFolder());
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static File createTempFile(String prefix, String suffix, File directory) throws IORuntimeException
+ {
+ try
+ {
+ return File.createTempFile(prefix, suffix, directory);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java index b264975d4f..4a8d9a48b2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java @@ -1,317 +1,317 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import org.eclipse.net4j.util.HexUtil; -import org.eclipse.net4j.util.WrappedException; - -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; - -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamResult; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.util.LinkedList; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class XMLOutput -{ - private static final AttributesImpl NO_ATTRIBUTES = new AttributesImpl(); - - private TransformerHandler xmlHandler; - - private char[] newLine; - - private char[] indentation; - - private LinkedList<Element> stack = new LinkedList<Element>(); - - private Element element; - - public XMLOutput(OutputStream out) throws TransformerConfigurationException, SAXException - { - setNewLine("\n"); - setIndentation(" "); - SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); - - xmlHandler = factory.newTransformerHandler(); - - Transformer transformer = xmlHandler.getTransformer(); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - - xmlHandler.setResult(new StreamResult(out)); - xmlHandler.startDocument(); - } - - public void setNewLine(String newLine) - { - this.newLine = newLine.toCharArray(); - } - - public void setIndentation(String indentation) - { - this.indentation = indentation.toCharArray(); - } - - public XMLOutput element(String name) throws SAXException - { - flush(); - element = new Element(name); - return this; - } - - public XMLOutput attribute(String name, Object value) throws SAXException - { - if (value != null) - { - return attributeOrNull(name, value); - } - - return this; - } - - public XMLOutput attributeOrNull(String name, Object value) throws SAXException - { - checkElement(); - element.addAttribute(name, value); - return this; - } - - public Writer characters() throws SAXException - { - checkElement(); - newLine(); - element.start(); - xmlHandler.startCDATA(); - - return new Writer() - { - @Override - public void write(char[] cbuf, int off, int len) throws IOException - { - try - { - xmlHandler.characters(cbuf, off, len); - } - catch (SAXException ex) - { - throw WrappedException.wrap(ex); - } - } - - @Override - public void flush() throws IOException - { - // Do nothing - } - - @Override - public void close() throws IOException - { - try - { - xmlHandler.endCDATA(); - element.end(); - } - catch (SAXException ex) - { - throw WrappedException.wrap(ex); - } - finally - { - element = null; - } - } - }; - } - - public OutputStream bytes() throws SAXException - { - checkElement(); - newLine(); - element.start(); - xmlHandler.startCDATA(); - - return new OutputStream() - { - @Override - public void write(byte[] b, int off, int len) throws IOException - { - try - { - char[] cbuf = HexUtil.bytesToHex(b, off, len).toCharArray(); - xmlHandler.characters(cbuf, 0, cbuf.length); - } - catch (SAXException ex) - { - throw WrappedException.wrap(ex); - } - } - - @Override - public void write(int i) throws IOException - { - byte b = (byte)((i & 0xff) + Byte.MIN_VALUE); - byte[] bs = { b }; - write(bs, 0, 1); - } - - @Override - public void close() throws IOException - { - try - { - xmlHandler.endCDATA(); - element.end(); - } - catch (SAXException ex) - { - throw WrappedException.wrap(ex); - } - finally - { - element = null; - } - } - }; - } - - public XMLOutput push() throws SAXException - { - newLine(); - element.start(); - - stack.add(element); - element = null; - return this; - } - - public XMLOutput pop() throws SAXException - { - flush(); - Element element = stack.removeLast(); - - if (element.hasChildren()) - { - newLine(); - } - - element.end(); - return this; - } - - public void done() throws SAXException - { - while (!stack.isEmpty()) - { - pop(); - } - - xmlHandler.endDocument(); - } - - private void flush() throws SAXException - { - if (element != null) - { - newLine(); - element.start(); - element.end(); - element = null; - } - } - - private void newLine() throws SAXException - { - xmlHandler.ignorableWhitespace(newLine, 0, newLine.length); - for (int i = 0; i < stack.size(); i++) - { - xmlHandler.ignorableWhitespace(indentation, 0, indentation.length); - } - } - - private void checkElement() - { - if (element == null) - { - throw new IllegalStateException("No element"); - } - } - - /** - * @author Eike Stepper - */ - private final class Element - { - private String name; - - private AttributesImpl attributes; - - private boolean children; - - public Element(String name) - { - this.name = name; - } - - public boolean hasChildren() - { - return children; - } - - public void addChild() - { - children = true; - } - - public void addAttribute(String name, Object value) - { - if (attributes == null) - { - attributes = new AttributesImpl(); - } - - if (value == null) - { - value = ""; - } - - attributes.addAttribute("", "", name, "", value.toString()); - } - - public void start() throws SAXException - { - if (!stack.isEmpty()) - { - stack.getLast().addChild(); - } - - xmlHandler.startElement("", "", name, attributes == null ? NO_ATTRIBUTES : attributes); - } - - public void end() throws SAXException - { - xmlHandler.endElement("", "", name); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import org.eclipse.net4j.util.HexUtil;
+import org.eclipse.net4j.util.WrappedException;
+
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
+
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.sax.SAXTransformerFactory;
+import javax.xml.transform.sax.TransformerHandler;
+import javax.xml.transform.stream.StreamResult;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.Writer;
+import java.util.LinkedList;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class XMLOutput
+{
+ private static final AttributesImpl NO_ATTRIBUTES = new AttributesImpl();
+
+ private TransformerHandler xmlHandler;
+
+ private char[] newLine;
+
+ private char[] indentation;
+
+ private LinkedList<Element> stack = new LinkedList<Element>();
+
+ private Element element;
+
+ public XMLOutput(OutputStream out) throws TransformerConfigurationException, SAXException
+ {
+ setNewLine("\n");
+ setIndentation(" ");
+ SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
+
+ xmlHandler = factory.newTransformerHandler();
+
+ Transformer transformer = xmlHandler.getTransformer();
+ transformer.setOutputProperty(OutputKeys.METHOD, "xml");
+ transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
+ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+
+ xmlHandler.setResult(new StreamResult(out));
+ xmlHandler.startDocument();
+ }
+
+ public void setNewLine(String newLine)
+ {
+ this.newLine = newLine.toCharArray();
+ }
+
+ public void setIndentation(String indentation)
+ {
+ this.indentation = indentation.toCharArray();
+ }
+
+ public XMLOutput element(String name) throws SAXException
+ {
+ flush();
+ element = new Element(name);
+ return this;
+ }
+
+ public XMLOutput attribute(String name, Object value) throws SAXException
+ {
+ if (value != null)
+ {
+ return attributeOrNull(name, value);
+ }
+
+ return this;
+ }
+
+ public XMLOutput attributeOrNull(String name, Object value) throws SAXException
+ {
+ checkElement();
+ element.addAttribute(name, value);
+ return this;
+ }
+
+ public Writer characters() throws SAXException
+ {
+ checkElement();
+ newLine();
+ element.start();
+ xmlHandler.startCDATA();
+
+ return new Writer()
+ {
+ @Override
+ public void write(char[] cbuf, int off, int len) throws IOException
+ {
+ try
+ {
+ xmlHandler.characters(cbuf, off, len);
+ }
+ catch (SAXException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ @Override
+ public void flush() throws IOException
+ {
+ // Do nothing
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ try
+ {
+ xmlHandler.endCDATA();
+ element.end();
+ }
+ catch (SAXException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ element = null;
+ }
+ }
+ };
+ }
+
+ public OutputStream bytes() throws SAXException
+ {
+ checkElement();
+ newLine();
+ element.start();
+ xmlHandler.startCDATA();
+
+ return new OutputStream()
+ {
+ @Override
+ public void write(byte[] b, int off, int len) throws IOException
+ {
+ try
+ {
+ char[] cbuf = HexUtil.bytesToHex(b, off, len).toCharArray();
+ xmlHandler.characters(cbuf, 0, cbuf.length);
+ }
+ catch (SAXException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ @Override
+ public void write(int i) throws IOException
+ {
+ byte b = (byte)((i & 0xff) + Byte.MIN_VALUE);
+ byte[] bs = { b };
+ write(bs, 0, 1);
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ try
+ {
+ xmlHandler.endCDATA();
+ element.end();
+ }
+ catch (SAXException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ element = null;
+ }
+ }
+ };
+ }
+
+ public XMLOutput push() throws SAXException
+ {
+ newLine();
+ element.start();
+
+ stack.add(element);
+ element = null;
+ return this;
+ }
+
+ public XMLOutput pop() throws SAXException
+ {
+ flush();
+ Element element = stack.removeLast();
+
+ if (element.hasChildren())
+ {
+ newLine();
+ }
+
+ element.end();
+ return this;
+ }
+
+ public void done() throws SAXException
+ {
+ while (!stack.isEmpty())
+ {
+ pop();
+ }
+
+ xmlHandler.endDocument();
+ }
+
+ private void flush() throws SAXException
+ {
+ if (element != null)
+ {
+ newLine();
+ element.start();
+ element.end();
+ element = null;
+ }
+ }
+
+ private void newLine() throws SAXException
+ {
+ xmlHandler.ignorableWhitespace(newLine, 0, newLine.length);
+ for (int i = 0; i < stack.size(); i++)
+ {
+ xmlHandler.ignorableWhitespace(indentation, 0, indentation.length);
+ }
+ }
+
+ private void checkElement()
+ {
+ if (element == null)
+ {
+ throw new IllegalStateException("No element");
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class Element
+ {
+ private String name;
+
+ private AttributesImpl attributes;
+
+ private boolean children;
+
+ public Element(String name)
+ {
+ this.name = name;
+ }
+
+ public boolean hasChildren()
+ {
+ return children;
+ }
+
+ public void addChild()
+ {
+ children = true;
+ }
+
+ public void addAttribute(String name, Object value)
+ {
+ if (attributes == null)
+ {
+ attributes = new AttributesImpl();
+ }
+
+ if (value == null)
+ {
+ value = "";
+ }
+
+ attributes.addAttribute("", "", name, "", value.toString());
+ }
+
+ public void start() throws SAXException
+ {
+ if (!stack.isEmpty())
+ {
+ stack.getLast().addChild();
+ }
+
+ xmlHandler.startElement("", "", name, attributes == null ? NO_ATTRIBUTES : attributes);
+ }
+
+ public void end() throws SAXException
+ {
+ xmlHandler.endElement("", "", name);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java index e48d2a3e31..cecd5cb3aa 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java @@ -1,55 +1,55 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * @author Eike Stepper - */ -public class XORInputStream extends DelegatingInputStream -{ - private int[] key; - - private int index; - - public XORInputStream(InputStream in, int... key) - { - super(in); - this.key = key; - } - - public int[] getKey() - { - return key; - } - - @Override - public int read() throws IOException - { - int b = super.read(); - if (b != -1) - { - if (key != null && key.length != 0) - { - if (index == key.length) - { - index = 0; - } - - b = b & 0xFF ^ key[index++] & 0xFF; - } - } - - return b; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class XORInputStream extends DelegatingInputStream
+{
+ private int[] key;
+
+ private int index;
+
+ public XORInputStream(InputStream in, int... key)
+ {
+ super(in);
+ this.key = key;
+ }
+
+ public int[] getKey()
+ {
+ return key;
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ int b = super.read();
+ if (b != -1)
+ {
+ if (key != null && key.length != 0)
+ {
+ if (index == key.length)
+ {
+ index = 0;
+ }
+
+ b = b & 0xFF ^ key[index++] & 0xFF;
+ }
+ }
+
+ return b;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java index 2f94c37257..e95d166e95 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public class XOROutputStream extends DelegatingOutputStream -{ - private int[] key; - - private int index; - - public XOROutputStream(OutputStream out, int... key) - { - super(out); - this.key = key; - } - - public int[] getKey() - { - return key; - } - - @Override - public void write(int b) throws IOException - { - if (key != null && key.length != 0) - { - if (index == key.length) - { - index = 0; - } - - b = b & 0xFF ^ key[index++] & 0xFF; - } - - super.write(b); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class XOROutputStream extends DelegatingOutputStream
+{
+ private int[] key;
+
+ private int index;
+
+ public XOROutputStream(OutputStream out, int... key)
+ {
+ super(out);
+ this.key = key;
+ }
+
+ public int[] getKey()
+ {
+ return key;
+ }
+
+ @Override
+ public void write(int b) throws IOException
+ {
+ if (key != null && key.length != 0)
+ {
+ if (index == key.length)
+ {
+ index = 0;
+ }
+
+ b = b & 0xFF ^ key[index++] & 0xFF;
+ }
+
+ super.write(b);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java index d62dbc7a1c..293b4d6ca4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java @@ -1,61 +1,61 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * @author Eike Stepper - */ -public class XORStreamWrapper implements IStreamWrapper -{ - private int[] key; - - public XORStreamWrapper(int[] key) - { - this.key = key; - } - - public int[] getKey() - { - return key; - } - - public XORInputStream wrapInputStream(InputStream in) throws IOException - { - if (in instanceof XORInputStream) - { - return (XORInputStream)in; - } - - return new XORInputStream(in, key); - } - - public XOROutputStream wrapOutputStream(OutputStream out) throws IOException - { - if (out instanceof XOROutputStream) - { - return (XOROutputStream)out; - } - - return new XOROutputStream(out, key); - } - - public void finishInputStream(InputStream in) throws IOException - { - } - - public void finishOutputStream(OutputStream out) throws IOException - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class XORStreamWrapper implements IStreamWrapper
+{
+ private int[] key;
+
+ public XORStreamWrapper(int[] key)
+ {
+ this.key = key;
+ }
+
+ public int[] getKey()
+ {
+ return key;
+ }
+
+ public XORInputStream wrapInputStream(InputStream in) throws IOException
+ {
+ if (in instanceof XORInputStream)
+ {
+ return (XORInputStream)in;
+ }
+
+ return new XORInputStream(in, key);
+ }
+
+ public XOROutputStream wrapOutputStream(OutputStream out) throws IOException
+ {
+ if (out instanceof XOROutputStream)
+ {
+ return (XOROutputStream)out;
+ }
+
+ return new XOROutputStream(out, key);
+ }
+
+ public void finishInputStream(InputStream in) throws IOException
+ {
+ }
+
+ public void finishOutputStream(OutputStream out) throws IOException
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java index e15c1ef819..89f22103d2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java @@ -1,408 +1,408 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.io; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; -import java.util.zip.ZipOutputStream; - -/** - * @author Eike Stepper - */ -public final class ZIPUtil -{ - public static final int DEFALULT_BUFFER_SIZE = 4096; - - private static final int ORDER_KEEP = -1; - - private static final int ORDER_SWAP = 1; - - private ZIPUtil() - { - } - - public static void zip(ZipEntryHandler handler, File zipFile) throws IORuntimeException - { - final byte[] buffer = new byte[DEFALULT_BUFFER_SIZE]; - final EntryContext context = new EntryContext(); - - FileOutputStream fos = IOUtil.openOutputStream(zipFile); - ZipOutputStream zos = null; - InputStream input = null; - ZipEntry entry = null; - - try - { - zos = new ZipOutputStream(new BufferedOutputStream(fos, DEFALULT_BUFFER_SIZE)); - for (;;) - { - handler.handleEntry(context); - if (context.isEmpty()) - { - break; - } - - try - { - String name = context.getName().replace(File.separatorChar, '/'); - entry = new ZipEntry(name); - zos.putNextEntry(entry); - - if (!context.isDirectory()) - { - input = context.getInputStream(); - if (input == null) - { - throw new IllegalStateException("Input is null for zip entry " + name); //$NON-NLS-1$ - } - - IOUtil.copy(input, zos, buffer); - } - } - finally - { - IOUtil.closeSilent(input); - if (entry != null) - { - zos.closeEntry(); - } - - context.reset(); - } - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - IOUtil.closeSilent(zos); - IOUtil.closeSilent(fos); - } - } - - public static void zip(File sourceFolder, boolean excludeRoot, File zipFile) - { - zip(new FileSystemZipHandler(sourceFolder, excludeRoot), zipFile); - } - - public static void unzip(File zipFile, UnzipHandler handler) throws IORuntimeException - { - FileInputStream fis = IOUtil.openInputStream(zipFile); - ZipInputStream zis = null; - - try - { - zis = new ZipInputStream(new BufferedInputStream(fis, DEFALULT_BUFFER_SIZE)); - - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) - { - if (entry.isDirectory()) - { - handler.unzipDirectory(entry.getName()); - } - else - { - // TODO Provide delegating InputStream that ignores close() - handler.unzipFile(entry.getName(), zis); - } - } - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - IOUtil.closeSilent(zis); - IOUtil.closeSilent(fis); - } - } - - public static void unzip(File zipFile, File targetFolder) throws IORuntimeException - { - unzip(zipFile, new FileSystemUnzipHandler(targetFolder, DEFALULT_BUFFER_SIZE)); - } - - /** - * @author Eike Stepper - */ - public interface ZipEntryHandler - { - public void handleEntry(EntryContext context) throws IOException; - } - - /** - * @author Eike Stepper - */ - public interface UnzipHandler - { - public void unzipDirectory(String name) throws IOException; - - public void unzipFile(String name, InputStream zipStream) throws IOException; - } - - /** - * @author Eike Stepper - */ - public static final class EntryContext - { - private static final String EMPTY = new String(); - - private String name = EMPTY; - - private InputStream inputStream; - - private boolean directory; - - EntryContext() - { - } - - void reset() - { - name = null; - inputStream = null; - } - - boolean isEmpty() - { - return name == null; - } - - boolean isDirectory() - { - return directory; - } - - String getName() - { - return name; - } - - InputStream getInputStream() - { - return inputStream; - } - - public void setName(String name, boolean directory) - { - this.name = name + (directory ? "/" : ""); //$NON-NLS-1$ //$NON-NLS-2$ - this.directory = directory; - } - - public void setInputStream(InputStream inputStream) - { - this.inputStream = inputStream; - } - } - - /** - * @author Eike Stepper - */ - public static final class FileSystemZipHandler implements ZipEntryHandler - { - private int sourceFolderLength; - - private transient Iterator<File> files; - - public FileSystemZipHandler(File sourceFolder, boolean excludeRoot) - { - File root = excludeRoot ? sourceFolder : sourceFolder.getParentFile(); - sourceFolderLength = root.getAbsolutePath().length(); - if (excludeRoot) - { - ++sourceFolderLength; - } - - final int baseLength = sourceFolder.getAbsolutePath().length(); - List<File> list = IOUtil.listBreadthFirst(sourceFolder); - Collections.sort(list, new Comparator<File>() - { - public int compare(File f1, File f2) - { - String path1 = getPath(f1, baseLength); - String path2 = getPath(f2, baseLength); - if (path1.length() == 0) - { - return ORDER_KEEP; - } - - if (path2.length() == 0) - { - return ORDER_SWAP; - } - - if (f1.isDirectory()) - { - if (f2.isDirectory()) - { - // f1=dir, f2=dir - if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ - { - return ORDER_KEEP; - } - - if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ - { - return ORDER_SWAP; - } - - return path1.compareTo(path2); - } - - // f1=dir, f2=file - if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ - { - return ORDER_KEEP; - } - - if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ - { - return ORDER_SWAP; - } - - return ORDER_KEEP; - } - - if (f2.isDirectory()) - { - // f1=file, f2=dir - if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ - { - return ORDER_SWAP; - } - - if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ - { - return ORDER_KEEP; - } - - return ORDER_SWAP; - } - - // f1=file, f2=file - if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ - { - return ORDER_KEEP; - } - - if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ - { - return ORDER_SWAP; - } - - return path1.compareTo(path2); - } - - private String getPath(File file, int baseLength) - { - String absolutePath = file.getAbsolutePath(); - String substring = absolutePath.substring(baseLength); - String replace = substring.replace(File.separatorChar, '/'); - return replace; - } - }); - - files = list.iterator(); - if (excludeRoot) - { - files.next(); - } - } - - public void handleEntry(EntryContext context) throws IOException - { - if (files.hasNext()) - { - File file = files.next(); - String name = getName(file); - if (name.length() != 0) - { - context.setName(name, file.isDirectory()); - - if (file.isFile()) - { - context.setInputStream(IOUtil.openInputStream(file)); - } - } - } - } - - protected String getName(File file) - { - return file.getAbsolutePath().substring(sourceFolderLength); - } - } - - /** - * @author Eike Stepper - */ - public static final class FileSystemUnzipHandler implements UnzipHandler - { - private File targetFolder; - - private transient byte[] buffer; - - public FileSystemUnzipHandler(File targetFolder, int bufferSize) - { - this.targetFolder = targetFolder; - buffer = new byte[bufferSize]; - } - - public File getTargetFolder() - { - return targetFolder; - } - - public void unzipDirectory(String name) - { - File directory = new File(targetFolder, name); - if (!directory.exists()) - { - directory.mkdirs(); - } - } - - public void unzipFile(String name, InputStream zipStream) - { - File targetFile = new File(targetFolder, name); - if (!targetFile.getParentFile().exists()) - { - targetFile.getParentFile().mkdirs(); - } - - FileOutputStream out = IOUtil.openOutputStream(targetFile); - - try - { - IOUtil.copy(zipStream, out, buffer); - } - finally - { - IOUtil.closeSilent(out); - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.io;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * @author Eike Stepper
+ */
+public final class ZIPUtil
+{
+ public static final int DEFALULT_BUFFER_SIZE = 4096;
+
+ private static final int ORDER_KEEP = -1;
+
+ private static final int ORDER_SWAP = 1;
+
+ private ZIPUtil()
+ {
+ }
+
+ public static void zip(ZipEntryHandler handler, File zipFile) throws IORuntimeException
+ {
+ final byte[] buffer = new byte[DEFALULT_BUFFER_SIZE];
+ final EntryContext context = new EntryContext();
+
+ FileOutputStream fos = IOUtil.openOutputStream(zipFile);
+ ZipOutputStream zos = null;
+ InputStream input = null;
+ ZipEntry entry = null;
+
+ try
+ {
+ zos = new ZipOutputStream(new BufferedOutputStream(fos, DEFALULT_BUFFER_SIZE));
+ for (;;)
+ {
+ handler.handleEntry(context);
+ if (context.isEmpty())
+ {
+ break;
+ }
+
+ try
+ {
+ String name = context.getName().replace(File.separatorChar, '/');
+ entry = new ZipEntry(name);
+ zos.putNextEntry(entry);
+
+ if (!context.isDirectory())
+ {
+ input = context.getInputStream();
+ if (input == null)
+ {
+ throw new IllegalStateException("Input is null for zip entry " + name); //$NON-NLS-1$
+ }
+
+ IOUtil.copy(input, zos, buffer);
+ }
+ }
+ finally
+ {
+ IOUtil.closeSilent(input);
+ if (entry != null)
+ {
+ zos.closeEntry();
+ }
+
+ context.reset();
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ IOUtil.closeSilent(zos);
+ IOUtil.closeSilent(fos);
+ }
+ }
+
+ public static void zip(File sourceFolder, boolean excludeRoot, File zipFile)
+ {
+ zip(new FileSystemZipHandler(sourceFolder, excludeRoot), zipFile);
+ }
+
+ public static void unzip(File zipFile, UnzipHandler handler) throws IORuntimeException
+ {
+ FileInputStream fis = IOUtil.openInputStream(zipFile);
+ ZipInputStream zis = null;
+
+ try
+ {
+ zis = new ZipInputStream(new BufferedInputStream(fis, DEFALULT_BUFFER_SIZE));
+
+ ZipEntry entry;
+ while ((entry = zis.getNextEntry()) != null)
+ {
+ if (entry.isDirectory())
+ {
+ handler.unzipDirectory(entry.getName());
+ }
+ else
+ {
+ // TODO Provide delegating InputStream that ignores close()
+ handler.unzipFile(entry.getName(), zis);
+ }
+ }
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ IOUtil.closeSilent(zis);
+ IOUtil.closeSilent(fis);
+ }
+ }
+
+ public static void unzip(File zipFile, File targetFolder) throws IORuntimeException
+ {
+ unzip(zipFile, new FileSystemUnzipHandler(targetFolder, DEFALULT_BUFFER_SIZE));
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public interface ZipEntryHandler
+ {
+ public void handleEntry(EntryContext context) throws IOException;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public interface UnzipHandler
+ {
+ public void unzipDirectory(String name) throws IOException;
+
+ public void unzipFile(String name, InputStream zipStream) throws IOException;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static final class EntryContext
+ {
+ private static final String EMPTY = new String();
+
+ private String name = EMPTY;
+
+ private InputStream inputStream;
+
+ private boolean directory;
+
+ EntryContext()
+ {
+ }
+
+ void reset()
+ {
+ name = null;
+ inputStream = null;
+ }
+
+ boolean isEmpty()
+ {
+ return name == null;
+ }
+
+ boolean isDirectory()
+ {
+ return directory;
+ }
+
+ String getName()
+ {
+ return name;
+ }
+
+ InputStream getInputStream()
+ {
+ return inputStream;
+ }
+
+ public void setName(String name, boolean directory)
+ {
+ this.name = name + (directory ? "/" : ""); //$NON-NLS-1$ //$NON-NLS-2$
+ this.directory = directory;
+ }
+
+ public void setInputStream(InputStream inputStream)
+ {
+ this.inputStream = inputStream;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static final class FileSystemZipHandler implements ZipEntryHandler
+ {
+ private int sourceFolderLength;
+
+ private transient Iterator<File> files;
+
+ public FileSystemZipHandler(File sourceFolder, boolean excludeRoot)
+ {
+ File root = excludeRoot ? sourceFolder : sourceFolder.getParentFile();
+ sourceFolderLength = root.getAbsolutePath().length();
+ if (excludeRoot)
+ {
+ ++sourceFolderLength;
+ }
+
+ final int baseLength = sourceFolder.getAbsolutePath().length();
+ List<File> list = IOUtil.listBreadthFirst(sourceFolder);
+ Collections.sort(list, new Comparator<File>()
+ {
+ public int compare(File f1, File f2)
+ {
+ String path1 = getPath(f1, baseLength);
+ String path2 = getPath(f2, baseLength);
+ if (path1.length() == 0)
+ {
+ return ORDER_KEEP;
+ }
+
+ if (path2.length() == 0)
+ {
+ return ORDER_SWAP;
+ }
+
+ if (f1.isDirectory())
+ {
+ if (f2.isDirectory())
+ {
+ // f1=dir, f2=dir
+ if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
+ {
+ return ORDER_KEEP;
+ }
+
+ if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
+ {
+ return ORDER_SWAP;
+ }
+
+ return path1.compareTo(path2);
+ }
+
+ // f1=dir, f2=file
+ if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
+ {
+ return ORDER_KEEP;
+ }
+
+ if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
+ {
+ return ORDER_SWAP;
+ }
+
+ return ORDER_KEEP;
+ }
+
+ if (f2.isDirectory())
+ {
+ // f1=file, f2=dir
+ if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
+ {
+ return ORDER_SWAP;
+ }
+
+ if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
+ {
+ return ORDER_KEEP;
+ }
+
+ return ORDER_SWAP;
+ }
+
+ // f1=file, f2=file
+ if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
+ {
+ return ORDER_KEEP;
+ }
+
+ if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
+ {
+ return ORDER_SWAP;
+ }
+
+ return path1.compareTo(path2);
+ }
+
+ private String getPath(File file, int baseLength)
+ {
+ String absolutePath = file.getAbsolutePath();
+ String substring = absolutePath.substring(baseLength);
+ String replace = substring.replace(File.separatorChar, '/');
+ return replace;
+ }
+ });
+
+ files = list.iterator();
+ if (excludeRoot)
+ {
+ files.next();
+ }
+ }
+
+ public void handleEntry(EntryContext context) throws IOException
+ {
+ if (files.hasNext())
+ {
+ File file = files.next();
+ String name = getName(file);
+ if (name.length() != 0)
+ {
+ context.setName(name, file.isDirectory());
+
+ if (file.isFile())
+ {
+ context.setInputStream(IOUtil.openInputStream(file));
+ }
+ }
+ }
+ }
+
+ protected String getName(File file)
+ {
+ return file.getAbsolutePath().substring(sourceFolderLength);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static final class FileSystemUnzipHandler implements UnzipHandler
+ {
+ private File targetFolder;
+
+ private transient byte[] buffer;
+
+ public FileSystemUnzipHandler(File targetFolder, int bufferSize)
+ {
+ this.targetFolder = targetFolder;
+ buffer = new byte[bufferSize];
+ }
+
+ public File getTargetFolder()
+ {
+ return targetFolder;
+ }
+
+ public void unzipDirectory(String name)
+ {
+ File directory = new File(targetFolder, name);
+ if (!directory.exists())
+ {
+ directory.mkdirs();
+ }
+ }
+
+ public void unzipFile(String name, InputStream zipStream)
+ {
+ File targetFile = new File(targetFolder, name);
+ if (!targetFile.getParentFile().exists())
+ {
+ targetFile.getParentFile().mkdirs();
+ }
+
+ FileOutputStream out = IOUtil.openOutputStream(targetFile);
+
+ try
+ {
+ IOUtil.copy(zipStream, out, buffer);
+ }
+ finally
+ {
+ IOUtil.closeSilent(out);
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java index e68d58cb66..44fa3a1ed5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycle.java index 8d9f5cbb26..e65a4fa80c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycle.java @@ -1,45 +1,45 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -import org.eclipse.net4j.util.event.INotifier; - -/** - * An entity that has a well-defined {@link #getLifecycleState() lifecycle} and can be {@link #activate() activated} or - * {@link #deactivate() deactivated}. - * <p> - * A lifecycle can fire the following events: - * <ul> - * <li> {@link ILifecycleEvent} before and after the {@link #getLifecycleState() state} of this lifecycle changes. - * </ul> - * - * @author Eike Stepper - * @apiviz.landmark - * @apiviz.has {@link LifecycleState} - * @apiviz.uses {@link ILifecycleEvent} - - fires - * @apiviz.excludeSubtypes - */ -public interface ILifecycle extends INotifier -{ - public void activate() throws LifecycleException; - - public Exception deactivate(); - - /** - * @since 3.0 - */ - public LifecycleState getLifecycleState(); - - /** - * @since 3.0 - */ - public boolean isActive(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+import org.eclipse.net4j.util.event.INotifier;
+
+/**
+ * An entity that has a well-defined {@link #getLifecycleState() lifecycle} and can be {@link #activate() activated} or
+ * {@link #deactivate() deactivated}.
+ * <p>
+ * A lifecycle can fire the following events:
+ * <ul>
+ * <li> {@link ILifecycleEvent} before and after the {@link #getLifecycleState() state} of this lifecycle changes.
+ * </ul>
+ *
+ * @author Eike Stepper
+ * @apiviz.landmark
+ * @apiviz.has {@link LifecycleState}
+ * @apiviz.uses {@link ILifecycleEvent} - - fires
+ * @apiviz.excludeSubtypes
+ */
+public interface ILifecycle extends INotifier
+{
+ public void activate() throws LifecycleException;
+
+ public Exception deactivate();
+
+ /**
+ * @since 3.0
+ */
+ public LifecycleState getLifecycleState();
+
+ /**
+ * @since 3.0
+ */
+ public boolean isActive();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java index 6513cdb6a5..f43ca8ca27 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java @@ -1,43 +1,43 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -import org.eclipse.net4j.util.event.IEvent; - -/** - * An {@link IEvent event} fired from an entity with a {@link ILifecycle lifecycle} when its lifecycle {@link Kind - * state} has changed. - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement Thi import org.eclipse.net4j.util.event.IEvent; import org.eclipse.net4j.util.event.IEvent; import - * org.eclipse.net4j.util.event.IEvent; s interface is not intended to be implemented by clients. - * @apiviz.has {@link org.eclipse.net4j.util.lifecycle.ILifecycleEvent.Kind} - */ -public interface ILifecycleEvent extends IEvent -{ - /** - * @since 3.0 - */ - public ILifecycle getSource(); - - public Kind getKind(); - - /** - * Enumerates the possible {@link ILifecycle#getLifecycleState() lifecycle state} changes of an entity. - * - * @author Eike Stepper - */ - public enum Kind - { - ABOUT_TO_ACTIVATE, ACTIVATED, ABOUT_TO_DEACTIVATE, DEACTIVATED - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+import org.eclipse.net4j.util.event.IEvent;
+
+/**
+ * An {@link IEvent event} fired from an entity with a {@link ILifecycle lifecycle} when its lifecycle {@link Kind
+ * state} has changed.
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement Thi import org.eclipse.net4j.util.event.IEvent; import org.eclipse.net4j.util.event.IEvent; import
+ * org.eclipse.net4j.util.event.IEvent; s interface is not intended to be implemented by clients.
+ * @apiviz.has {@link org.eclipse.net4j.util.lifecycle.ILifecycleEvent.Kind}
+ */
+public interface ILifecycleEvent extends IEvent
+{
+ /**
+ * @since 3.0
+ */
+ public ILifecycle getSource();
+
+ public Kind getKind();
+
+ /**
+ * Enumerates the possible {@link ILifecycle#getLifecycleState() lifecycle state} changes of an entity.
+ *
+ * @author Eike Stepper
+ */
+ public enum Kind
+ {
+ ABOUT_TO_ACTIVATE, ACTIVATED, ABOUT_TO_DEACTIVATE, DEACTIVATED
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/Lifecycle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/Lifecycle.java index a00c175c51..c0cdd7c4d8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/Lifecycle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/Lifecycle.java @@ -1,303 +1,303 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.CheckUtil; -import org.eclipse.net4j.util.ReflectUtil; -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.Notifier; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.util.concurrent.Semaphore; - -/** - * A default implementation of an entity with a {@link ILifecycle lifecycle}. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class Lifecycle extends Notifier implements ILifecycle -{ - public static boolean USE_LABEL = true; - - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_LIFECYCLE, Lifecycle.class); - - private static final ContextTracer DUMPER = new ContextTracer(OM.DEBUG_LIFECYCLE_DUMP, Lifecycle.class); - - private static final boolean TRACE_IGNORING = false; - - private static final boolean LOCKING = true; - - private LifecycleState lifecycleState = LifecycleState.INACTIVE; - - @ExcludeFromDump - private Semaphore lifecycleSemaphore = new Semaphore(1); - - /** - * @since 2.0 - */ - public Lifecycle() - { - } - - public final void activate() throws LifecycleException - { - try - { - if (lifecycleState == LifecycleState.INACTIVE) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Activating " + this); //$NON-NLS-1$ - } - - lock(); - - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.ABOUT_TO_ACTIVATE), listeners); - } - - doBeforeActivate(); - - lifecycleState = LifecycleState.ACTIVATING; - doActivate(); - - if (!isDeferredActivation()) - { - deferredActivate(true); - } - - dump(); - } - else - { - if (TRACE_IGNORING) - { - if (TRACER.isEnabled()) - { - TRACER.format("Ignoring activation in state {0} for {1}", lifecycleState, this); //$NON-NLS-1$ - } - } - } - } - catch (RuntimeException ex) - { - deferredActivate(false); - throw ex; - } - catch (Exception ex) - { - deferredActivate(false); - throw new LifecycleException(ex); - } - } - - public final Exception deactivate() - { - try - { - if (lifecycleState == LifecycleState.ACTIVE) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Deactivating " + this); //$NON-NLS-1$ - } - - lock(); - - doBeforeDeactivate(); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.ABOUT_TO_DEACTIVATE), listeners); - } - - lifecycleState = LifecycleState.DEACTIVATING; - doDeactivate(); - - lifecycleState = LifecycleState.INACTIVE; - unlock(); - - if (listeners != null) - { - fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.DEACTIVATED), listeners); - } - - return null; - } - - if (TRACE_IGNORING) - { - if (TRACER.isEnabled()) - { - TRACER.format("Ignoring deactivation in state {0} for {1}", lifecycleState, this); //$NON-NLS-1$ - } - } - - return null; - } - catch (Exception ex) - { - lifecycleState = LifecycleState.INACTIVE; - unlock(); - return ex; - } - } - - /** - * @since 3.0 - */ - public final LifecycleState getLifecycleState() - { - return lifecycleState; - } - - public final boolean isActive() - { - return lifecycleState == LifecycleState.ACTIVE; - } - - @Override - public String toString() - { - if (USE_LABEL) - { - return ReflectUtil.getLabel(this); - } - - return super.toString(); - } - - protected final void dump() - { - if (DUMPER.isEnabled()) - { - DUMPER.trace("DUMP" + ReflectUtil.toString(this)); //$NON-NLS-1$ - } - } - - protected final void checkActive() - { - LifecycleUtil.checkActive(this); - } - - protected final void checkInactive() - { - LifecycleUtil.checkInactive(this); - } - - protected final void checkNull(Object handle, String msg) throws NullPointerException - { - CheckUtil.checkNull(handle, msg); - } - - protected final void checkArg(boolean expr, String msg) throws IllegalArgumentException - { - CheckUtil.checkArg(expr, msg); - } - - protected final void checkArg(Object handle, String handleName) throws IllegalArgumentException - { - CheckUtil.checkState(handle, handleName); - } - - protected final void checkState(boolean expr, String msg) throws IllegalStateException - { - CheckUtil.checkState(expr, msg); - } - - protected final void checkState(Object handle, String handleName) throws IllegalStateException - { - CheckUtil.checkState(handle, handleName); - } - - /** - * @since 2.0 - */ - protected final void deferredActivate(boolean successful) - { - if (successful) - { - lifecycleState = LifecycleState.ACTIVE; - - try - { - doAfterActivate(); - } - catch (Exception ex) - { - OM.LOG.error(ex); - deactivate(); - return; - } - - unlock(); - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.ACTIVATED), listeners); - } - } - else - { - lifecycleState = LifecycleState.INACTIVE; - unlock(); - } - } - - protected boolean isDeferredActivation() - { - return false; - } - - protected void doBeforeActivate() throws Exception - { - } - - protected void doActivate() throws Exception - { - } - - /** - * @since 3.0 - */ - protected void doAfterActivate() throws Exception - { - } - - protected void doBeforeDeactivate() throws Exception - { - } - - protected void doDeactivate() throws Exception - { - } - - private void lock() throws InterruptedException - { - if (LOCKING) - { - lifecycleSemaphore.acquire(); - } - } - - private void unlock() - { - if (LOCKING) - { - lifecycleSemaphore.release(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.CheckUtil;
+import org.eclipse.net4j.util.ReflectUtil;
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.Notifier;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.util.concurrent.Semaphore;
+
+/**
+ * A default implementation of an entity with a {@link ILifecycle lifecycle}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class Lifecycle extends Notifier implements ILifecycle
+{
+ public static boolean USE_LABEL = true;
+
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_LIFECYCLE, Lifecycle.class);
+
+ private static final ContextTracer DUMPER = new ContextTracer(OM.DEBUG_LIFECYCLE_DUMP, Lifecycle.class);
+
+ private static final boolean TRACE_IGNORING = false;
+
+ private static final boolean LOCKING = true;
+
+ private LifecycleState lifecycleState = LifecycleState.INACTIVE;
+
+ @ExcludeFromDump
+ private Semaphore lifecycleSemaphore = new Semaphore(1);
+
+ /**
+ * @since 2.0
+ */
+ public Lifecycle()
+ {
+ }
+
+ public final void activate() throws LifecycleException
+ {
+ try
+ {
+ if (lifecycleState == LifecycleState.INACTIVE)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Activating " + this); //$NON-NLS-1$
+ }
+
+ lock();
+
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.ABOUT_TO_ACTIVATE), listeners);
+ }
+
+ doBeforeActivate();
+
+ lifecycleState = LifecycleState.ACTIVATING;
+ doActivate();
+
+ if (!isDeferredActivation())
+ {
+ deferredActivate(true);
+ }
+
+ dump();
+ }
+ else
+ {
+ if (TRACE_IGNORING)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Ignoring activation in state {0} for {1}", lifecycleState, this); //$NON-NLS-1$
+ }
+ }
+ }
+ }
+ catch (RuntimeException ex)
+ {
+ deferredActivate(false);
+ throw ex;
+ }
+ catch (Exception ex)
+ {
+ deferredActivate(false);
+ throw new LifecycleException(ex);
+ }
+ }
+
+ public final Exception deactivate()
+ {
+ try
+ {
+ if (lifecycleState == LifecycleState.ACTIVE)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Deactivating " + this); //$NON-NLS-1$
+ }
+
+ lock();
+
+ doBeforeDeactivate();
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.ABOUT_TO_DEACTIVATE), listeners);
+ }
+
+ lifecycleState = LifecycleState.DEACTIVATING;
+ doDeactivate();
+
+ lifecycleState = LifecycleState.INACTIVE;
+ unlock();
+
+ if (listeners != null)
+ {
+ fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.DEACTIVATED), listeners);
+ }
+
+ return null;
+ }
+
+ if (TRACE_IGNORING)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Ignoring deactivation in state {0} for {1}", lifecycleState, this); //$NON-NLS-1$
+ }
+ }
+
+ return null;
+ }
+ catch (Exception ex)
+ {
+ lifecycleState = LifecycleState.INACTIVE;
+ unlock();
+ return ex;
+ }
+ }
+
+ /**
+ * @since 3.0
+ */
+ public final LifecycleState getLifecycleState()
+ {
+ return lifecycleState;
+ }
+
+ public final boolean isActive()
+ {
+ return lifecycleState == LifecycleState.ACTIVE;
+ }
+
+ @Override
+ public String toString()
+ {
+ if (USE_LABEL)
+ {
+ return ReflectUtil.getLabel(this);
+ }
+
+ return super.toString();
+ }
+
+ protected final void dump()
+ {
+ if (DUMPER.isEnabled())
+ {
+ DUMPER.trace("DUMP" + ReflectUtil.toString(this)); //$NON-NLS-1$
+ }
+ }
+
+ protected final void checkActive()
+ {
+ LifecycleUtil.checkActive(this);
+ }
+
+ protected final void checkInactive()
+ {
+ LifecycleUtil.checkInactive(this);
+ }
+
+ protected final void checkNull(Object handle, String msg) throws NullPointerException
+ {
+ CheckUtil.checkNull(handle, msg);
+ }
+
+ protected final void checkArg(boolean expr, String msg) throws IllegalArgumentException
+ {
+ CheckUtil.checkArg(expr, msg);
+ }
+
+ protected final void checkArg(Object handle, String handleName) throws IllegalArgumentException
+ {
+ CheckUtil.checkState(handle, handleName);
+ }
+
+ protected final void checkState(boolean expr, String msg) throws IllegalStateException
+ {
+ CheckUtil.checkState(expr, msg);
+ }
+
+ protected final void checkState(Object handle, String handleName) throws IllegalStateException
+ {
+ CheckUtil.checkState(handle, handleName);
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected final void deferredActivate(boolean successful)
+ {
+ if (successful)
+ {
+ lifecycleState = LifecycleState.ACTIVE;
+
+ try
+ {
+ doAfterActivate();
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ deactivate();
+ return;
+ }
+
+ unlock();
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ fireEvent(new LifecycleEvent(this, ILifecycleEvent.Kind.ACTIVATED), listeners);
+ }
+ }
+ else
+ {
+ lifecycleState = LifecycleState.INACTIVE;
+ unlock();
+ }
+ }
+
+ protected boolean isDeferredActivation()
+ {
+ return false;
+ }
+
+ protected void doBeforeActivate() throws Exception
+ {
+ }
+
+ protected void doActivate() throws Exception
+ {
+ }
+
+ /**
+ * @since 3.0
+ */
+ protected void doAfterActivate() throws Exception
+ {
+ }
+
+ protected void doBeforeDeactivate() throws Exception
+ {
+ }
+
+ protected void doDeactivate() throws Exception
+ {
+ }
+
+ private void lock() throws InterruptedException
+ {
+ if (LOCKING)
+ {
+ lifecycleSemaphore.acquire();
+ }
+ }
+
+ private void unlock()
+ {
+ if (LOCKING)
+ {
+ lifecycleSemaphore.release();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java index 7c72ce6561..ab46f83e61 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java @@ -1,47 +1,47 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -import org.eclipse.net4j.util.event.Event; - -/** - * A default implementation of a lifecycle {@link ILifecycleEvent event}. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class LifecycleEvent extends Event implements ILifecycleEvent -{ - private static final long serialVersionUID = 1L; - - private Kind kind; - - public LifecycleEvent(Lifecycle lifecycle, Kind kind) - { - super(lifecycle); - this.kind = kind; - } - - /** - * @since 3.0 - */ - @Override - public ILifecycle getSource() - { - return (ILifecycle)super.getSource(); - } - - public Kind getKind() - { - return kind; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+import org.eclipse.net4j.util.event.Event;
+
+/**
+ * A default implementation of a lifecycle {@link ILifecycleEvent event}.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class LifecycleEvent extends Event implements ILifecycleEvent
+{
+ private static final long serialVersionUID = 1L;
+
+ private Kind kind;
+
+ public LifecycleEvent(Lifecycle lifecycle, Kind kind)
+ {
+ super(lifecycle);
+ this.kind = kind;
+ }
+
+ /**
+ * @since 3.0
+ */
+ @Override
+ public ILifecycle getSource()
+ {
+ return (ILifecycle)super.getSource();
+ }
+
+ public Kind getKind()
+ {
+ return kind;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java index 19a952a045..ff7765879d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java @@ -1,80 +1,80 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.event.IListener; - -/** - * A {@link IListener listener} that dispatches lifecycle {@link ILifecycleEvent events} to methods that can be - * overridden by extenders. - * - * @author Eike Stepper - * @apiviz.exclude - */ -public class LifecycleEventAdapter implements IListener -{ - public LifecycleEventAdapter() - { - } - - public final void notifyEvent(IEvent event) - { - if (event instanceof ILifecycleEvent) - { - ILifecycleEvent e = (ILifecycleEvent)event; - notifyLifecycleEvent(e); - } - else - { - notifyOtherEvent(event); - } - } - - protected void notifyLifecycleEvent(ILifecycleEvent event) - { - switch (event.getKind()) - { - case ABOUT_TO_ACTIVATE: - onAboutToActivate(event.getSource()); - break; - case ACTIVATED: - onActivated(event.getSource()); - break; - case ABOUT_TO_DEACTIVATE: - onAboutToDeactivate(event.getSource()); - break; - case DEACTIVATED: - onDeactivated(event.getSource()); - break; - } - } - - protected void notifyOtherEvent(IEvent event) - { - } - - protected void onAboutToActivate(ILifecycle lifecycle) - { - } - - protected void onActivated(ILifecycle lifecycle) - { - } - - protected void onAboutToDeactivate(ILifecycle lifecycle) - { - } - - protected void onDeactivated(ILifecycle lifecycle) - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.event.IListener;
+
+/**
+ * A {@link IListener listener} that dispatches lifecycle {@link ILifecycleEvent events} to methods that can be
+ * overridden by extenders.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+public class LifecycleEventAdapter implements IListener
+{
+ public LifecycleEventAdapter()
+ {
+ }
+
+ public final void notifyEvent(IEvent event)
+ {
+ if (event instanceof ILifecycleEvent)
+ {
+ ILifecycleEvent e = (ILifecycleEvent)event;
+ notifyLifecycleEvent(e);
+ }
+ else
+ {
+ notifyOtherEvent(event);
+ }
+ }
+
+ protected void notifyLifecycleEvent(ILifecycleEvent event)
+ {
+ switch (event.getKind())
+ {
+ case ABOUT_TO_ACTIVATE:
+ onAboutToActivate(event.getSource());
+ break;
+ case ACTIVATED:
+ onActivated(event.getSource());
+ break;
+ case ABOUT_TO_DEACTIVATE:
+ onAboutToDeactivate(event.getSource());
+ break;
+ case DEACTIVATED:
+ onDeactivated(event.getSource());
+ break;
+ }
+ }
+
+ protected void notifyOtherEvent(IEvent event)
+ {
+ }
+
+ protected void onAboutToActivate(ILifecycle lifecycle)
+ {
+ }
+
+ protected void onActivated(ILifecycle lifecycle)
+ {
+ }
+
+ protected void onAboutToDeactivate(ILifecycle lifecycle)
+ {
+ }
+
+ protected void onDeactivated(ILifecycle lifecycle)
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java index ca3e61248c..bc2a715c3f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java @@ -1,42 +1,42 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -/** - * An unchecked wrapper exception for checked exceptions being thrown from {@link Lifecycle#doActivate()}. - * - * @author Eike Stepper - * @noextend This class is not intended to be subclassed by clients. - * @apiviz.exclude - */ -public class LifecycleException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public LifecycleException() - { - } - - public LifecycleException(String message) - { - super(message); - } - - public LifecycleException(Throwable cause) - { - super(cause); - } - - public LifecycleException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+/**
+ * An unchecked wrapper exception for checked exceptions being thrown from {@link Lifecycle#doActivate()}.
+ *
+ * @author Eike Stepper
+ * @noextend This class is not intended to be subclassed by clients.
+ * @apiviz.exclude
+ */
+public class LifecycleException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public LifecycleException()
+ {
+ }
+
+ public LifecycleException(String message)
+ {
+ super(message);
+ }
+
+ public LifecycleException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public LifecycleException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java index 976fa1c1ba..af0cbaa958 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -/** - * Enumerates the possible lifecycle states of an entity with a {@link ILifecycle lifecycle}. - * - * @author Eike Stepper - * @since 3.0 - */ -public enum LifecycleState -{ - ACTIVATING, ACTIVE, DEACTIVATING, INACTIVE -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+/**
+ * Enumerates the possible lifecycle states of an entity with a {@link ILifecycle lifecycle}.
+ *
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public enum LifecycleState
+{
+ ACTIVATING, ACTIVE, DEACTIVATING, INACTIVE
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleUtil.java index c21eabf1d2..d5c544497d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleUtil.java @@ -1,446 +1,446 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.lifecycle; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.event.IEvent; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.om.log.OMLogger.Level; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.lang.annotation.Annotation; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Various static helper methods for dealing with {@link ILifecycle lifecycles}. - * - * @author Eike Stepper - */ -public final class LifecycleUtil -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_LIFECYCLE, LifecycleUtil.class); - - private LifecycleUtil() - { - } - - /** - * @since 3.0 - */ - public static LifecycleState getLifecycleState(Object object) - { - if (object instanceof ILifecycle) - { - return ((ILifecycle)object).getLifecycleState(); - } - - return LifecycleState.ACTIVE; - } - - public static boolean isActive(Object object) - { - if (object instanceof ILifecycle) - { - return ((ILifecycle)object).isActive(); - } - - return object != null; - } - - /** - * @since 2.0 - */ - public static void checkActive(Object object) throws IllegalStateException - { - if (!isActive(object)) - { - throw new IllegalStateException("Not active: " + object); //$NON-NLS-1$ - } - } - - /** - * @since 2.0 - */ - public static void checkInactive(Object object) throws IllegalStateException - { - if (isActive(object)) - { - throw new IllegalStateException("Not inactive: " + object); //$NON-NLS-1$ - } - } - - public static void activate(Object object) throws LifecycleException - { - activate(object, false); - } - - /** - * @see Activator - */ - public static void activate(Object object, boolean useAnnotation) throws LifecycleException - { - if (object instanceof ILifecycle) - { - ((ILifecycle)object).activate(); - } - else if (object != null && useAnnotation) - { - invokeAnnotation(object, Activator.class); - } - } - - public static Exception activateSilent(Object object) - { - return activateSilent(object, false); - } - - /** - * @see Activator - */ - public static Exception activateSilent(Object object, boolean useAnnotation) - { - try - { - activate(object, useAnnotation); - return null; - } - catch (Exception ex) - { - OM.LOG.error(ex); - return ex; - } - } - - public static boolean waitForActive(Object object, long millis) - { - return waitFor(object, millis, LifecycleState.ACTIVE); - } - - /** - * @since 3.1 - */ - public static boolean waitForInactive(Object object, long millis) - { - return waitFor(object, millis, LifecycleState.INACTIVE); - } - - /** - * @since 3.1 - */ - public static boolean waitFor(Object object, long millis, final LifecycleState state) - { - try - { - if (object instanceof ILifecycle) - { - Lifecycle lifecycle = (Lifecycle)object; - if (lifecycle.getLifecycleState() == state) - { - return true; - } - - final CountDownLatch latch = new CountDownLatch(1); - IListener adapter = new IListener() - { - public void notifyEvent(IEvent event) - { - if (event instanceof ILifecycleEvent) - { - ILifecycleEvent e = (ILifecycleEvent)event; - if (e.getSource().getLifecycleState() == state) - { - latch.countDown(); - } - } - } - }; - - try - { - lifecycle.addListener(adapter); - latch.await(millis, TimeUnit.MILLISECONDS); - } - finally - { - lifecycle.removeListener(adapter); - } - - return lifecycle.getLifecycleState() == state; - } - - return true; - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static Exception deactivate(Object object) - { - return deactivate(object, false); - } - - /** - * @see Deactivator - */ - public static Exception deactivate(Object object, boolean useAnnotation) - { - if (object instanceof ILifecycle) - { - return ((ILifecycle)object).deactivate(); - } - else if (object != null && useAnnotation) - { - // TODO Handle evtl. return value (exception) - invokeAnnotation(object, Deactivator.class); - } - - return null; - } - - /** - * @since 2.0 - */ - public static void deactivate(Object object, Level logLevel) - { - Exception exception = deactivate(object); - if (exception != null) - { - OM.LOG.log(logLevel, "Problem while deactivating " + object, exception); //$NON-NLS-1$ - } - } - - public static void deactivateNoisy(Object object) throws LifecycleException - { - deactivateNoisy(object, false); - } - - public static void deactivateNoisy(Object object, boolean useAnnotation) throws LifecycleException - { - Exception ex = deactivate(object, useAnnotation); - if (ex instanceof RuntimeException) - { - throw (RuntimeException)ex; - } - else if (ex != null) - { - throw new LifecycleException(ex); - } - } - - /** - * @since 2.0 - */ - public static <T> T delegateLifecycle(ClassLoader loader, T pojo, Class<?> pojoInterface, ILifecycle delegate) - { - return Delegator.newProxy(loader, pojo, pojoInterface, delegate); - } - - /** - * @since 2.0 - */ - public static <T> T delegateLifecycle(ClassLoader loader, T pojo, ILifecycle delegate) - { - return Delegator.newProxy(loader, pojo, pojo.getClass(), delegate); - } - - private static <T extends Annotation> void invokeAnnotation(Object object, Class<T> annotationClass) - { - Class<?> c = object.getClass(); - while (c != Object.class) - { - final Method[] methods = c.getDeclaredMethods(); - for (Method method : methods) - { - if (method.getParameterTypes().length == 0) - { - Annotation annotation = method.getAnnotation(annotationClass); - if (annotation != null) - { - invokeMethod(object, method); - boolean propagate = annotationClass == Activator.class ? ((Activator)annotation).propagate() - : ((Deactivator)annotation).propagate(); - if (!propagate) - { - break; - } - } - } - } - - c = c.getSuperclass(); - } - } - - private static Object invokeMethod(Object object, Method method) - { - try - { - return method.invoke(object, (Object[])null); - } - catch (IllegalAccessException iae) - { - try - { - method.setAccessible(true); - return method.invoke(object, (Object[])null); - } - catch (Exception ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace(ex); - } - } - } - catch (Exception ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace(ex); - } - } - - return null; - } - - /** - * Annotates a method of a POJO class that's supposed to be called to <em>activate</em> a POJO object during - * {@link LifecycleUtil#activate(Object)}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public @interface Activator - { - boolean propagate() default true; - } - - /** - * Annotates a method of a POJO class that's supposed to be called to <em>deactivate</em> a POJO object during - * {@link LifecycleUtil#deactivate(Object)}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.METHOD) - public @interface Deactivator - { - boolean propagate() default true; - } - - /** - * The {@link InvocationHandler invocation handler} of the {@link Proxy dynamic proxy} created in - * {@link LifecycleUtil#delegateLifecycle(ClassLoader, Object, ILifecycle) LifecycleUtil.delegateLifecycle()}. - * - * @author Eike Stepper - * @since 2.0 - * @apiviz.exclude - */ - public static final class Delegator<T> implements InvocationHandler - { - private static final Class<ILifecycle> INTERFACE = ILifecycle.class; - - private T pojo; - - private ILifecycle delegate; - - public Delegator(T pojo, ILifecycle delegate) - { - this.pojo = pojo; - this.delegate = delegate; - } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable - { - String name = method.getName(); - if (name.equals("activate")) //$NON-NLS-1$ - { - delegate.activate(); - return null; - } - - if (name.equals("deactivate")) //$NON-NLS-1$ - { - return delegate.deactivate(); - } - - if (name.equals("isActive")) //$NON-NLS-1$ - { - return delegate.isActive(); - } - - if (name.equals("getLifecycleState")) //$NON-NLS-1$ - { - return delegate.getLifecycleState(); - } - - if (name.equals("getListeners")) //$NON-NLS-1$ - { - return delegate.getListeners(); - } - - if (name.equals("hasListeners")) //$NON-NLS-1$ - { - return delegate.hasListeners(); - } - - if (name.equals("addListener")) //$NON-NLS-1$ - { - delegate.addListener((IListener)args[0]); - return null; - } - - if (name.equals("removeListener")) //$NON-NLS-1$ - { - delegate.removeListener((IListener)args[0]); - return null; - } - - try - { - return method.invoke(pojo, args); - } - catch (Exception ex) - { - throw ex; - } - } - - public static <T> T newProxy(ClassLoader loader, T pojo, Class<?> pojoInterface, ILifecycle delegate) - { - if (pojo == null) - { - return pojo; - } - - Delegator<T> h = new Delegator<T>(pojo, delegate); - final Class<?>[] interfaces = { pojoInterface, INTERFACE }; - - @SuppressWarnings("unchecked") - T proxy = (T)Proxy.newProxyInstance(loader, interfaces, h); - return proxy; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.lifecycle;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.event.IEvent;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Various static helper methods for dealing with {@link ILifecycle lifecycles}.
+ *
+ * @author Eike Stepper
+ */
+public final class LifecycleUtil
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_LIFECYCLE, LifecycleUtil.class);
+
+ private LifecycleUtil()
+ {
+ }
+
+ /**
+ * @since 3.0
+ */
+ public static LifecycleState getLifecycleState(Object object)
+ {
+ if (object instanceof ILifecycle)
+ {
+ return ((ILifecycle)object).getLifecycleState();
+ }
+
+ return LifecycleState.ACTIVE;
+ }
+
+ public static boolean isActive(Object object)
+ {
+ if (object instanceof ILifecycle)
+ {
+ return ((ILifecycle)object).isActive();
+ }
+
+ return object != null;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static void checkActive(Object object) throws IllegalStateException
+ {
+ if (!isActive(object))
+ {
+ throw new IllegalStateException("Not active: " + object); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static void checkInactive(Object object) throws IllegalStateException
+ {
+ if (isActive(object))
+ {
+ throw new IllegalStateException("Not inactive: " + object); //$NON-NLS-1$
+ }
+ }
+
+ public static void activate(Object object) throws LifecycleException
+ {
+ activate(object, false);
+ }
+
+ /**
+ * @see Activator
+ */
+ public static void activate(Object object, boolean useAnnotation) throws LifecycleException
+ {
+ if (object instanceof ILifecycle)
+ {
+ ((ILifecycle)object).activate();
+ }
+ else if (object != null && useAnnotation)
+ {
+ invokeAnnotation(object, Activator.class);
+ }
+ }
+
+ public static Exception activateSilent(Object object)
+ {
+ return activateSilent(object, false);
+ }
+
+ /**
+ * @see Activator
+ */
+ public static Exception activateSilent(Object object, boolean useAnnotation)
+ {
+ try
+ {
+ activate(object, useAnnotation);
+ return null;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ return ex;
+ }
+ }
+
+ public static boolean waitForActive(Object object, long millis)
+ {
+ return waitFor(object, millis, LifecycleState.ACTIVE);
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static boolean waitForInactive(Object object, long millis)
+ {
+ return waitFor(object, millis, LifecycleState.INACTIVE);
+ }
+
+ /**
+ * @since 3.1
+ */
+ public static boolean waitFor(Object object, long millis, final LifecycleState state)
+ {
+ try
+ {
+ if (object instanceof ILifecycle)
+ {
+ Lifecycle lifecycle = (Lifecycle)object;
+ if (lifecycle.getLifecycleState() == state)
+ {
+ return true;
+ }
+
+ final CountDownLatch latch = new CountDownLatch(1);
+ IListener adapter = new IListener()
+ {
+ public void notifyEvent(IEvent event)
+ {
+ if (event instanceof ILifecycleEvent)
+ {
+ ILifecycleEvent e = (ILifecycleEvent)event;
+ if (e.getSource().getLifecycleState() == state)
+ {
+ latch.countDown();
+ }
+ }
+ }
+ };
+
+ try
+ {
+ lifecycle.addListener(adapter);
+ latch.await(millis, TimeUnit.MILLISECONDS);
+ }
+ finally
+ {
+ lifecycle.removeListener(adapter);
+ }
+
+ return lifecycle.getLifecycleState() == state;
+ }
+
+ return true;
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ public static Exception deactivate(Object object)
+ {
+ return deactivate(object, false);
+ }
+
+ /**
+ * @see Deactivator
+ */
+ public static Exception deactivate(Object object, boolean useAnnotation)
+ {
+ if (object instanceof ILifecycle)
+ {
+ return ((ILifecycle)object).deactivate();
+ }
+ else if (object != null && useAnnotation)
+ {
+ // TODO Handle evtl. return value (exception)
+ invokeAnnotation(object, Deactivator.class);
+ }
+
+ return null;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static void deactivate(Object object, Level logLevel)
+ {
+ Exception exception = deactivate(object);
+ if (exception != null)
+ {
+ OM.LOG.log(logLevel, "Problem while deactivating " + object, exception); //$NON-NLS-1$
+ }
+ }
+
+ public static void deactivateNoisy(Object object) throws LifecycleException
+ {
+ deactivateNoisy(object, false);
+ }
+
+ public static void deactivateNoisy(Object object, boolean useAnnotation) throws LifecycleException
+ {
+ Exception ex = deactivate(object, useAnnotation);
+ if (ex instanceof RuntimeException)
+ {
+ throw (RuntimeException)ex;
+ }
+ else if (ex != null)
+ {
+ throw new LifecycleException(ex);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static <T> T delegateLifecycle(ClassLoader loader, T pojo, Class<?> pojoInterface, ILifecycle delegate)
+ {
+ return Delegator.newProxy(loader, pojo, pojoInterface, delegate);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static <T> T delegateLifecycle(ClassLoader loader, T pojo, ILifecycle delegate)
+ {
+ return Delegator.newProxy(loader, pojo, pojo.getClass(), delegate);
+ }
+
+ private static <T extends Annotation> void invokeAnnotation(Object object, Class<T> annotationClass)
+ {
+ Class<?> c = object.getClass();
+ while (c != Object.class)
+ {
+ final Method[] methods = c.getDeclaredMethods();
+ for (Method method : methods)
+ {
+ if (method.getParameterTypes().length == 0)
+ {
+ Annotation annotation = method.getAnnotation(annotationClass);
+ if (annotation != null)
+ {
+ invokeMethod(object, method);
+ boolean propagate = annotationClass == Activator.class ? ((Activator)annotation).propagate()
+ : ((Deactivator)annotation).propagate();
+ if (!propagate)
+ {
+ break;
+ }
+ }
+ }
+ }
+
+ c = c.getSuperclass();
+ }
+ }
+
+ private static Object invokeMethod(Object object, Method method)
+ {
+ try
+ {
+ return method.invoke(object, (Object[])null);
+ }
+ catch (IllegalAccessException iae)
+ {
+ try
+ {
+ method.setAccessible(true);
+ return method.invoke(object, (Object[])null);
+ }
+ catch (Exception ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace(ex);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace(ex);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Annotates a method of a POJO class that's supposed to be called to <em>activate</em> a POJO object during
+ * {@link LifecycleUtil#activate(Object)}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.METHOD)
+ public @interface Activator
+ {
+ boolean propagate() default true;
+ }
+
+ /**
+ * Annotates a method of a POJO class that's supposed to be called to <em>deactivate</em> a POJO object during
+ * {@link LifecycleUtil#deactivate(Object)}.
+ *
+ * @author Eike Stepper
+ * @apiviz.exclude
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.METHOD)
+ public @interface Deactivator
+ {
+ boolean propagate() default true;
+ }
+
+ /**
+ * The {@link InvocationHandler invocation handler} of the {@link Proxy dynamic proxy} created in
+ * {@link LifecycleUtil#delegateLifecycle(ClassLoader, Object, ILifecycle) LifecycleUtil.delegateLifecycle()}.
+ *
+ * @author Eike Stepper
+ * @since 2.0
+ * @apiviz.exclude
+ */
+ public static final class Delegator<T> implements InvocationHandler
+ {
+ private static final Class<ILifecycle> INTERFACE = ILifecycle.class;
+
+ private T pojo;
+
+ private ILifecycle delegate;
+
+ public Delegator(T pojo, ILifecycle delegate)
+ {
+ this.pojo = pojo;
+ this.delegate = delegate;
+ }
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
+ {
+ String name = method.getName();
+ if (name.equals("activate")) //$NON-NLS-1$
+ {
+ delegate.activate();
+ return null;
+ }
+
+ if (name.equals("deactivate")) //$NON-NLS-1$
+ {
+ return delegate.deactivate();
+ }
+
+ if (name.equals("isActive")) //$NON-NLS-1$
+ {
+ return delegate.isActive();
+ }
+
+ if (name.equals("getLifecycleState")) //$NON-NLS-1$
+ {
+ return delegate.getLifecycleState();
+ }
+
+ if (name.equals("getListeners")) //$NON-NLS-1$
+ {
+ return delegate.getListeners();
+ }
+
+ if (name.equals("hasListeners")) //$NON-NLS-1$
+ {
+ return delegate.hasListeners();
+ }
+
+ if (name.equals("addListener")) //$NON-NLS-1$
+ {
+ delegate.addListener((IListener)args[0]);
+ return null;
+ }
+
+ if (name.equals("removeListener")) //$NON-NLS-1$
+ {
+ delegate.removeListener((IListener)args[0]);
+ return null;
+ }
+
+ try
+ {
+ return method.invoke(pojo, args);
+ }
+ catch (Exception ex)
+ {
+ throw ex;
+ }
+ }
+
+ public static <T> T newProxy(ClassLoader loader, T pojo, Class<?> pojoInterface, ILifecycle delegate)
+ {
+ if (pojo == null)
+ {
+ return pojo;
+ }
+
+ Delegator<T> h = new Delegator<T>(pojo, delegate);
+ final Class<?>[] interfaces = { pojoInterface, INTERFACE };
+
+ @SuppressWarnings("unchecked")
+ T proxy = (T)Proxy.newProxyInstance(loader, interfaces, h);
+ return proxy;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java index 6ecf268ca9..069a8d2401 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java index f99ca881fc..be35816666 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java @@ -1,67 +1,67 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om; - -import org.eclipse.net4j.internal.util.om.LegacyBundle; - -/** - * Various static helper methods for dealing with {@link OMBundle bundles} if OSGi {@link OMPlatform#isOSGiRunning() is - * not running}. - * - * @author Eike Stepper - */ -public final class LegacyUtil -{ - private static final String[] UNINITIALIZED = {}; - - private static String[] commandLineArgs = UNINITIALIZED; - - private LegacyUtil() - { - } - - /** - * @since 3.2 - */ - public static String[] getCommandLineArgs() throws IllegalStateException - { - if (commandLineArgs == UNINITIALIZED) - { - throw new IllegalStateException("Command line argumentshave not been set"); - } - - return commandLineArgs; - } - - /** - * @since 3.2 - */ - public static void setCommandLineArgs(String[] commandLineArgs) - { - LegacyUtil.commandLineArgs = commandLineArgs; - } - - public static void startBundles(OMBundle[] bundles) throws Exception - { - for (int i = 0; i < bundles.length; i++) - { - ((LegacyBundle)bundles[i]).start(); - } - } - - public static void stopBundles(OMBundle[] bundles) throws Exception - { - for (int i = bundles.length - 1; i >= 0; i--) - { - ((LegacyBundle)bundles[i]).stop(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om;
+
+import org.eclipse.net4j.internal.util.om.LegacyBundle;
+
+/**
+ * Various static helper methods for dealing with {@link OMBundle bundles} if OSGi {@link OMPlatform#isOSGiRunning() is
+ * not running}.
+ *
+ * @author Eike Stepper
+ */
+public final class LegacyUtil
+{
+ private static final String[] UNINITIALIZED = {};
+
+ private static String[] commandLineArgs = UNINITIALIZED;
+
+ private LegacyUtil()
+ {
+ }
+
+ /**
+ * @since 3.2
+ */
+ public static String[] getCommandLineArgs() throws IllegalStateException
+ {
+ if (commandLineArgs == UNINITIALIZED)
+ {
+ throw new IllegalStateException("Command line argumentshave not been set");
+ }
+
+ return commandLineArgs;
+ }
+
+ /**
+ * @since 3.2
+ */
+ public static void setCommandLineArgs(String[] commandLineArgs)
+ {
+ LegacyUtil.commandLineArgs = commandLineArgs;
+ }
+
+ public static void startBundles(OMBundle[] bundles) throws Exception
+ {
+ for (int i = 0; i < bundles.length; i++)
+ {
+ ((LegacyBundle)bundles[i]).start();
+ }
+ }
+
+ public static void stopBundles(OMBundle[] bundles) throws Exception
+ {
+ for (int i = bundles.length - 1; i >= 0; i--)
+ {
+ ((LegacyBundle)bundles[i]).stop();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java index 252912edff..ac42062f21 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java @@ -1,177 +1,177 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om; - -import org.eclipse.net4j.util.om.log.OMLogger; -import org.eclipse.net4j.util.om.pref.OMPreferences; -import org.eclipse.net4j.util.om.trace.OMTracer; - -import org.eclipse.osgi.service.debug.DebugOptions; - -import org.osgi.framework.Bundle; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Iterator; -import java.util.Properties; -import java.util.ResourceBundle; - -/** - * Represents a {@link Bundle bundle}, whether OSGi {@link OMPlatform#isOSGiRunning() is running} or not. - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - * @apiviz.landmark - * @apiviz.has {@link org.eclipse.net4j.util.om.pref.OMPreferences} oneway - - preferences - * @apiviz.has {@link org.eclipse.net4j.util.om.log.OMLogger} oneway - - logger - * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTracer} - - tracers - * @apiviz.has {@link OMBundle.DebugSupport} - * @apiviz.has {@link OMBundle.TranslationSupport} - * @apiviz.has {@link java.util.Properties} oneway - - config - */ -public interface OMBundle -{ - public OMPlatform getPlatform(); - - public String getBundleID(); - - public URL getBaseURL(); - - /** - * @since 3.2 - */ - public Iterator<Class<?>> getClasses(); - - public OMTracer tracer(String name); - - public OMLogger logger(); - - public OMPreferences preferences(); - - public File getConfigFile(); - - public Properties getConfigProperties(); - - public String getStateLocation(); - - public InputStream getInputStream(String path) throws IOException; - - public DebugSupport getDebugSupport(); - - public TranslationSupport getTranslationSupport(); - - /** - * @deprecated For internal use only. - */ - @Deprecated - public void setBundleContext(Object bundleContext); - - /** - * A facility for accessing OSGi {@link DebugOptions debug options}, whether OSGi {@link OMPlatform#isOSGiRunning() is - * running} or not. - * - * @author Eike Stepper - */ - public interface DebugSupport - { - public boolean isDebugging(); - - public void setDebugging(boolean debugging); - - public String getDebugOption(String option); - - public void setDebugOption(String option, String value); - - public String getDebugOption(String option, String defaultValue); - - public boolean getDebugOption(String option, boolean defaultValue); - - public void setDebugOption(String option, boolean value); - - public int getDebugOption(String option, int defaultValue); - - public void setDebugOption(String option, int value); - } - - /** - * A facility for accessing {@link ResourceBundle resource bundles}. - * - * @author Eike Stepper - */ - public interface TranslationSupport - { - /** - * Indicates whether strings should be translated by default. - * - * @return <code>true</code> if strings should be translated by default; <code>false</code> otherwise. - */ - public boolean shouldTranslate(); - - /** - * Sets whether strings should be translated by default. - * - * @param shouldTranslate - * whether strings should be translated by default. - */ - public void setShouldTranslate(boolean shouldTranslate); - - /** - * Returns the string resource associated with the key. - * - * @param key - * the key of the string resource. - * @return the string resource associated with the key. - */ - String getString(String key); - - /** - * Returns the string resource associated with the key. - * - * @param key - * the key of the string resource. - * @param translate - * whether the result is to be translated to the current locale. - * @return the string resource associated with the key. - */ - String getString(String key, boolean translate); - - /** - * Returns a string resource associated with the key, and performs substitutions. - * - * @param key - * the key of the string. - * @param args - * the message substitutions. - * @return a string resource associated with the key. - * @see #getString(String) - * @see java.text.MessageFormat#format(String, Object...) - */ - String getString(String key, Object... args); - - /** - * Returns a string resource associated with the key, and performs substitutions. - * - * @param key - * the key of the string. - * @param translate - * whether the result is to be translated to the current locale. - * @param args - * the message substitutions. - * @return a string resource associated with the key. - * @see #getString(String) - * @see java.text.MessageFormat#format(String, Object[]) - */ - String getString(String key, boolean translate, Object... args); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om;
+
+import org.eclipse.net4j.util.om.log.OMLogger;
+import org.eclipse.net4j.util.om.pref.OMPreferences;
+import org.eclipse.net4j.util.om.trace.OMTracer;
+
+import org.eclipse.osgi.service.debug.DebugOptions;
+
+import org.osgi.framework.Bundle;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Iterator;
+import java.util.Properties;
+import java.util.ResourceBundle;
+
+/**
+ * Represents a {@link Bundle bundle}, whether OSGi {@link OMPlatform#isOSGiRunning() is running} or not.
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @apiviz.landmark
+ * @apiviz.has {@link org.eclipse.net4j.util.om.pref.OMPreferences} oneway - - preferences
+ * @apiviz.has {@link org.eclipse.net4j.util.om.log.OMLogger} oneway - - logger
+ * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTracer} - - tracers
+ * @apiviz.has {@link OMBundle.DebugSupport}
+ * @apiviz.has {@link OMBundle.TranslationSupport}
+ * @apiviz.has {@link java.util.Properties} oneway - - config
+ */
+public interface OMBundle
+{
+ public OMPlatform getPlatform();
+
+ public String getBundleID();
+
+ public URL getBaseURL();
+
+ /**
+ * @since 3.2
+ */
+ public Iterator<Class<?>> getClasses();
+
+ public OMTracer tracer(String name);
+
+ public OMLogger logger();
+
+ public OMPreferences preferences();
+
+ public File getConfigFile();
+
+ public Properties getConfigProperties();
+
+ public String getStateLocation();
+
+ public InputStream getInputStream(String path) throws IOException;
+
+ public DebugSupport getDebugSupport();
+
+ public TranslationSupport getTranslationSupport();
+
+ /**
+ * @deprecated For internal use only.
+ */
+ @Deprecated
+ public void setBundleContext(Object bundleContext);
+
+ /**
+ * A facility for accessing OSGi {@link DebugOptions debug options}, whether OSGi {@link OMPlatform#isOSGiRunning() is
+ * running} or not.
+ *
+ * @author Eike Stepper
+ */
+ public interface DebugSupport
+ {
+ public boolean isDebugging();
+
+ public void setDebugging(boolean debugging);
+
+ public String getDebugOption(String option);
+
+ public void setDebugOption(String option, String value);
+
+ public String getDebugOption(String option, String defaultValue);
+
+ public boolean getDebugOption(String option, boolean defaultValue);
+
+ public void setDebugOption(String option, boolean value);
+
+ public int getDebugOption(String option, int defaultValue);
+
+ public void setDebugOption(String option, int value);
+ }
+
+ /**
+ * A facility for accessing {@link ResourceBundle resource bundles}.
+ *
+ * @author Eike Stepper
+ */
+ public interface TranslationSupport
+ {
+ /**
+ * Indicates whether strings should be translated by default.
+ *
+ * @return <code>true</code> if strings should be translated by default; <code>false</code> otherwise.
+ */
+ public boolean shouldTranslate();
+
+ /**
+ * Sets whether strings should be translated by default.
+ *
+ * @param shouldTranslate
+ * whether strings should be translated by default.
+ */
+ public void setShouldTranslate(boolean shouldTranslate);
+
+ /**
+ * Returns the string resource associated with the key.
+ *
+ * @param key
+ * the key of the string resource.
+ * @return the string resource associated with the key.
+ */
+ String getString(String key);
+
+ /**
+ * Returns the string resource associated with the key.
+ *
+ * @param key
+ * the key of the string resource.
+ * @param translate
+ * whether the result is to be translated to the current locale.
+ * @return the string resource associated with the key.
+ */
+ String getString(String key, boolean translate);
+
+ /**
+ * Returns a string resource associated with the key, and performs substitutions.
+ *
+ * @param key
+ * the key of the string.
+ * @param args
+ * the message substitutions.
+ * @return a string resource associated with the key.
+ * @see #getString(String)
+ * @see java.text.MessageFormat#format(String, Object...)
+ */
+ String getString(String key, Object... args);
+
+ /**
+ * Returns a string resource associated with the key, and performs substitutions.
+ *
+ * @param key
+ * the key of the string.
+ * @param translate
+ * whether the result is to be translated to the current locale.
+ * @param args
+ * the message substitutions.
+ * @return a string resource associated with the key.
+ * @see #getString(String)
+ * @see java.text.MessageFormat#format(String, Object[])
+ */
+ String getString(String key, boolean translate, Object... args);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java index 6f3efc5fef..c353b4ea37 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java @@ -1,92 +1,92 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om; - -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.om.log.OMLogFilter; -import org.eclipse.net4j.util.om.log.OMLogHandler; -import org.eclipse.net4j.util.om.trace.OMTraceHandler; - -import java.io.File; -import java.util.Properties; - -/** - * Represents the platform that {@link OMBundle bundles} are deployed into, whether OSGi {@link #isOSGiRunning() is - * running} or not. - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - * @apiviz.landmark - * @apiviz.has {@link OMBundle} bundles platform - * @apiviz.owns {@link org.eclipse.net4j.util.om.log.OMLogHandler} - - logHandlers - * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTraceHandler} - - traceHandlers - * @apiviz.has {@link java.io.File} oneway - - stateFolder - */ -public interface OMPlatform -{ - // @Singleton - public static final OMPlatform INSTANCE = AbstractPlatform.createPlatform(); - - public OMBundle bundle(String bundleID, Class<?> accessor); - - public boolean isOSGiRunning(); - - /** - * @since 2.0 - */ - public boolean isExtensionRegistryAvailable(); - - public boolean isDebugging(); - - public void setDebugging(boolean debugging); - - /** - * @since 3.2 - */ - public void addLogFilter(OMLogFilter logFilter); - - /** - * @since 3.2 - */ - public void removeLogFilter(OMLogFilter logFilter); - - public void addLogHandler(OMLogHandler logHandler); - - public void removeLogHandler(OMLogHandler logHandler); - - public void addTraceHandler(OMTraceHandler traceHandler); - - public void removeTraceHandler(OMTraceHandler traceHandler); - - public File getStateFolder(); - - public File getConfigFolder(); - - public File getConfigFile(String name); - - public Properties getConfigProperties(String name); - - /** - * @since 3.0 - */ - public String getProperty(String key); - - /** - * @since 3.0 - */ - public String getProperty(String key, String defaultValue); - - /** - * @since 3.2 - */ - public String[] getCommandLineArgs() throws IllegalStateException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.om.log.OMLogFilter;
+import org.eclipse.net4j.util.om.log.OMLogHandler;
+import org.eclipse.net4j.util.om.trace.OMTraceHandler;
+
+import java.io.File;
+import java.util.Properties;
+
+/**
+ * Represents the platform that {@link OMBundle bundles} are deployed into, whether OSGi {@link #isOSGiRunning() is
+ * running} or not.
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @apiviz.landmark
+ * @apiviz.has {@link OMBundle} bundles platform
+ * @apiviz.owns {@link org.eclipse.net4j.util.om.log.OMLogHandler} - - logHandlers
+ * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTraceHandler} - - traceHandlers
+ * @apiviz.has {@link java.io.File} oneway - - stateFolder
+ */
+public interface OMPlatform
+{
+ // @Singleton
+ public static final OMPlatform INSTANCE = AbstractPlatform.createPlatform();
+
+ public OMBundle bundle(String bundleID, Class<?> accessor);
+
+ public boolean isOSGiRunning();
+
+ /**
+ * @since 2.0
+ */
+ public boolean isExtensionRegistryAvailable();
+
+ public boolean isDebugging();
+
+ public void setDebugging(boolean debugging);
+
+ /**
+ * @since 3.2
+ */
+ public void addLogFilter(OMLogFilter logFilter);
+
+ /**
+ * @since 3.2
+ */
+ public void removeLogFilter(OMLogFilter logFilter);
+
+ public void addLogHandler(OMLogHandler logHandler);
+
+ public void removeLogHandler(OMLogHandler logHandler);
+
+ public void addTraceHandler(OMTraceHandler traceHandler);
+
+ public void removeTraceHandler(OMTraceHandler traceHandler);
+
+ public File getStateFolder();
+
+ public File getConfigFolder();
+
+ public File getConfigFile(String name);
+
+ public Properties getConfigProperties(String name);
+
+ /**
+ * @since 3.0
+ */
+ public String getProperty(String key);
+
+ /**
+ * @since 3.0
+ */
+ public String getProperty(String key, String defaultValue);
+
+ /**
+ * @since 3.2
+ */
+ public String[] getCommandLineArgs() throws IllegalStateException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java index 2d41ba444b..93f0031cba 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java @@ -1,320 +1,320 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om; - -import org.eclipse.net4j.internal.util.bundle.AbstractBundle; -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.internal.util.om.OSGiBundle; -import org.eclipse.net4j.util.io.IOUtil; - -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.ObjectStreamClass; - -/** - * A default implementation of an OSGi {@link BundleActivator bundle activator} for OM {@link OMBundle bundles}. - * - * @author Eike Stepper - */ -public abstract class OSGiActivator implements BundleActivator -{ - private OMBundle omBundle; - - /** - * @since 2.0 - */ - protected BundleContext bundleContext; - - public OSGiActivator(OMBundle omBundle) - { - this.omBundle = omBundle; - } - - public final OMBundle getOMBundle() - { - return omBundle; - } - - public final void start(BundleContext context) throws Exception - { - bundleContext = context; - OSGiActivator.traceStart(context); - if (omBundle == null) - { - throw new IllegalStateException("bundle == null"); //$NON-NLS-1$ - } - - try - { - setBundleContext(context); - ((AbstractBundle)omBundle).start(); - doStart(); - } - catch (Error error) - { - omBundle.logger().error(error); - throw error; - } - catch (Exception ex) - { - omBundle.logger().error(ex); - throw ex; - } - } - - public final void stop(BundleContext context) throws Exception - { - OSGiActivator.traceStop(context); - if (omBundle == null) - { - throw new IllegalStateException("bundle == null"); //$NON-NLS-1$ - } - - try - { - doStop(); - ((AbstractBundle)omBundle).stop(); - setBundleContext(null); - } - catch (Error error) - { - omBundle.logger().error(error); - throw error; - } - catch (Exception ex) - { - omBundle.logger().error(ex); - throw ex; - } - } - - @Override - public final boolean equals(Object obj) - { - return super.equals(obj); - } - - @Override - public final int hashCode() - { - return super.hashCode(); - } - - @Override - public final String toString() - { - return super.toString(); - } - - @Override - protected final Object clone() throws CloneNotSupportedException - { - return super.clone(); - } - - @Override - protected final void finalize() throws Throwable - { - super.finalize(); - } - - /** - * @since 2.0 - */ - protected void doStart() throws Exception - { - } - - /** - * @since 2.0 - */ - protected void doStop() throws Exception - { - } - - @SuppressWarnings("deprecation") - private void setBundleContext(BundleContext context) - { - omBundle.setBundleContext(context); - } - - /** - * @since 2.0 - */ - public static void traceStart(BundleContext context) - { - try - { - if (OM.TRACER.isEnabled()) - { - OM.TRACER.format("Starting bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$ - } - } - catch (RuntimeException ignore) - { - } - } - - /** - * @since 2.0 - */ - public static void traceStop(BundleContext context) - { - try - { - if (OM.TRACER.isEnabled()) - { - OM.TRACER.format("Stopping bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$ - } - } - catch (RuntimeException ignore) - { - } - } - - /** - * Saves and loads {@link OMBundle bundle} state. - * - * @author Eike Stepper - * @since 3.1 - */ - public static abstract class StateHandler - { - private OSGiBundle bundle; - - public StateHandler(OMBundle bundle) - { - this.bundle = (OSGiBundle)bundle; - } - - public final void start() throws Exception - { - Object state = null; - File stateFile = getStateFile(); - if (stateFile.exists()) - { - FileInputStream fis = null; - - try - { - fis = new FileInputStream(stateFile); - ObjectInputStream ois = new ObjectInputStream(fis) - { - @Override - protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException - { - String className = desc.getName(); - return bundle.getAccessor().getClassLoader().loadClass(className); - } - }; - - state = ois.readObject(); - IOUtil.close(ois); - } - catch (Exception ex) - { - OM.LOG.error(ex); - IOUtil.close(fis); - fis = null; - stateFile.delete(); - } - finally - { - IOUtil.close(fis); - } - } - - startWithState(state); - } - - public final void stop() throws Exception - { - FileOutputStream fos = null; - - try - { - Object state = stopWithState(); - - File stateFile = getStateFile(); - fos = new FileOutputStream(stateFile); - ObjectOutputStream oos = new ObjectOutputStream(fos); - oos.writeObject(state); - IOUtil.close(oos); - } - finally - { - IOUtil.close(fos); - } - } - - private File getStateFile() - { - return new File(bundle.getStateLocation(), "state.bin"); - } - - protected abstract void startWithState(Object state) throws Exception; - - protected abstract Object stopWithState() throws Exception; - } - - /** - * An OSGi {@link OSGiActivator activator} that stores {@link StateHandler bundle state} between sessions. - * - * @author Eike Stepper - * @since 3.1 - * @apiviz.has {@link OSGiActivator.StateHandler} oneway - - stateHandler - */ - public static abstract class WithState extends OSGiActivator - { - private StateHandler handler = new StateHandler(getOMBundle()) - { - @Override - protected void startWithState(Object state) throws Exception - { - doStartWithState(state); - } - - @Override - protected Object stopWithState() throws Exception - { - return doStopWithState(); - } - }; - - public WithState(OMBundle bundle) - { - super(bundle); - } - - @Override - protected final void doStart() throws Exception - { - handler.start(); - } - - @Override - protected final void doStop() throws Exception - { - handler.stop(); - } - - protected abstract void doStartWithState(Object state) throws Exception; - - protected abstract Object doStopWithState() throws Exception; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.internal.util.om.OSGiBundle;
+import org.eclipse.net4j.util.io.IOUtil;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+
+/**
+ * A default implementation of an OSGi {@link BundleActivator bundle activator} for OM {@link OMBundle bundles}.
+ *
+ * @author Eike Stepper
+ */
+public abstract class OSGiActivator implements BundleActivator
+{
+ private OMBundle omBundle;
+
+ /**
+ * @since 2.0
+ */
+ protected BundleContext bundleContext;
+
+ public OSGiActivator(OMBundle omBundle)
+ {
+ this.omBundle = omBundle;
+ }
+
+ public final OMBundle getOMBundle()
+ {
+ return omBundle;
+ }
+
+ public final void start(BundleContext context) throws Exception
+ {
+ bundleContext = context;
+ OSGiActivator.traceStart(context);
+ if (omBundle == null)
+ {
+ throw new IllegalStateException("bundle == null"); //$NON-NLS-1$
+ }
+
+ try
+ {
+ setBundleContext(context);
+ ((AbstractBundle)omBundle).start();
+ doStart();
+ }
+ catch (Error error)
+ {
+ omBundle.logger().error(error);
+ throw error;
+ }
+ catch (Exception ex)
+ {
+ omBundle.logger().error(ex);
+ throw ex;
+ }
+ }
+
+ public final void stop(BundleContext context) throws Exception
+ {
+ OSGiActivator.traceStop(context);
+ if (omBundle == null)
+ {
+ throw new IllegalStateException("bundle == null"); //$NON-NLS-1$
+ }
+
+ try
+ {
+ doStop();
+ ((AbstractBundle)omBundle).stop();
+ setBundleContext(null);
+ }
+ catch (Error error)
+ {
+ omBundle.logger().error(error);
+ throw error;
+ }
+ catch (Exception ex)
+ {
+ omBundle.logger().error(ex);
+ throw ex;
+ }
+ }
+
+ @Override
+ public final boolean equals(Object obj)
+ {
+ return super.equals(obj);
+ }
+
+ @Override
+ public final int hashCode()
+ {
+ return super.hashCode();
+ }
+
+ @Override
+ public final String toString()
+ {
+ return super.toString();
+ }
+
+ @Override
+ protected final Object clone() throws CloneNotSupportedException
+ {
+ return super.clone();
+ }
+
+ @Override
+ protected final void finalize() throws Throwable
+ {
+ super.finalize();
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected void doStart() throws Exception
+ {
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected void doStop() throws Exception
+ {
+ }
+
+ @SuppressWarnings("deprecation")
+ private void setBundleContext(BundleContext context)
+ {
+ omBundle.setBundleContext(context);
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static void traceStart(BundleContext context)
+ {
+ try
+ {
+ if (OM.TRACER.isEnabled())
+ {
+ OM.TRACER.format("Starting bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$
+ }
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static void traceStop(BundleContext context)
+ {
+ try
+ {
+ if (OM.TRACER.isEnabled())
+ {
+ OM.TRACER.format("Stopping bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$
+ }
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+
+ /**
+ * Saves and loads {@link OMBundle bundle} state.
+ *
+ * @author Eike Stepper
+ * @since 3.1
+ */
+ public static abstract class StateHandler
+ {
+ private OSGiBundle bundle;
+
+ public StateHandler(OMBundle bundle)
+ {
+ this.bundle = (OSGiBundle)bundle;
+ }
+
+ public final void start() throws Exception
+ {
+ Object state = null;
+ File stateFile = getStateFile();
+ if (stateFile.exists())
+ {
+ FileInputStream fis = null;
+
+ try
+ {
+ fis = new FileInputStream(stateFile);
+ ObjectInputStream ois = new ObjectInputStream(fis)
+ {
+ @Override
+ protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException
+ {
+ String className = desc.getName();
+ return bundle.getAccessor().getClassLoader().loadClass(className);
+ }
+ };
+
+ state = ois.readObject();
+ IOUtil.close(ois);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ IOUtil.close(fis);
+ fis = null;
+ stateFile.delete();
+ }
+ finally
+ {
+ IOUtil.close(fis);
+ }
+ }
+
+ startWithState(state);
+ }
+
+ public final void stop() throws Exception
+ {
+ FileOutputStream fos = null;
+
+ try
+ {
+ Object state = stopWithState();
+
+ File stateFile = getStateFile();
+ fos = new FileOutputStream(stateFile);
+ ObjectOutputStream oos = new ObjectOutputStream(fos);
+ oos.writeObject(state);
+ IOUtil.close(oos);
+ }
+ finally
+ {
+ IOUtil.close(fos);
+ }
+ }
+
+ private File getStateFile()
+ {
+ return new File(bundle.getStateLocation(), "state.bin");
+ }
+
+ protected abstract void startWithState(Object state) throws Exception;
+
+ protected abstract Object stopWithState() throws Exception;
+ }
+
+ /**
+ * An OSGi {@link OSGiActivator activator} that stores {@link StateHandler bundle state} between sessions.
+ *
+ * @author Eike Stepper
+ * @since 3.1
+ * @apiviz.has {@link OSGiActivator.StateHandler} oneway - - stateHandler
+ */
+ public static abstract class WithState extends OSGiActivator
+ {
+ private StateHandler handler = new StateHandler(getOMBundle())
+ {
+ @Override
+ protected void startWithState(Object state) throws Exception
+ {
+ doStartWithState(state);
+ }
+
+ @Override
+ protected Object stopWithState() throws Exception
+ {
+ return doStopWithState();
+ }
+ };
+
+ public WithState(OMBundle bundle)
+ {
+ super(bundle);
+ }
+
+ @Override
+ protected final void doStart() throws Exception
+ {
+ handler.start();
+ }
+
+ @Override
+ protected final void doStop() throws Exception
+ {
+ handler.stop();
+ }
+
+ protected abstract void doStartWithState(Object state) throws Exception;
+
+ protected abstract Object doStopWithState() throws Exception;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java index 824249ec1c..87f2808ac3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java @@ -1,147 +1,147 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import org.eclipse.equinox.app.IApplication; -import org.eclipse.equinox.app.IApplicationContext; - -import java.util.concurrent.CountDownLatch; - -/** - * A default implementation of an OSGi {@link IApplication application}. - * - * @author Eike Stepper - */ -public class OSGiApplication implements IApplication -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OSGiApplication.class); - - private String applicationID; - - private IApplicationContext context; - - private CountDownLatch stopLatch; - - public OSGiApplication(String applicationID) - { - this.applicationID = applicationID; - } - - public String getApplicationID() - { - return applicationID; - } - - public IApplicationContext getApplicationContext() - { - return context; - } - - public boolean isRunning() - { - return stopLatch != null; - } - - public final Object start(IApplicationContext context) throws Exception - { - this.context = context; - traceStart(applicationID); - - try - { - doStart(); - } - catch (Error error) - { - OM.LOG.error(error); - throw error; - } - catch (Exception ex) - { - OM.LOG.error(ex); - throw ex; - } - - if (context != null) - { - context.applicationRunning(); - } - - stopLatch = new CountDownLatch(1); - stopLatch.await(); - stopLatch = null; - return EXIT_OK; - } - - public final void stop() - { - traceStop(applicationID); - - try - { - doStop(); - } - catch (Error error) - { - OM.LOG.error(error); - throw error; - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - - context = null; - if (stopLatch != null) - { - stopLatch.countDown(); - } - } - - protected void doStart() throws Exception - { - } - - protected void doStop() throws Exception - { - } - - public static void traceStart(String applicationID) - { - try - { - if (TRACER.isEnabled()) - { - TRACER.format("Starting application {0}", applicationID); //$NON-NLS-1$ - } - } - catch (RuntimeException ignore) - { - } - } - - public static void traceStop(String applicationID) - { - try - { - if (TRACER.isEnabled()) - { - TRACER.format("Stopping application {0}", applicationID); //$NON-NLS-1$ - } - } - catch (RuntimeException ignore) - { - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import org.eclipse.equinox.app.IApplication;
+import org.eclipse.equinox.app.IApplicationContext;
+
+import java.util.concurrent.CountDownLatch;
+
+/**
+ * A default implementation of an OSGi {@link IApplication application}.
+ *
+ * @author Eike Stepper
+ */
+public class OSGiApplication implements IApplication
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OSGiApplication.class);
+
+ private String applicationID;
+
+ private IApplicationContext context;
+
+ private CountDownLatch stopLatch;
+
+ public OSGiApplication(String applicationID)
+ {
+ this.applicationID = applicationID;
+ }
+
+ public String getApplicationID()
+ {
+ return applicationID;
+ }
+
+ public IApplicationContext getApplicationContext()
+ {
+ return context;
+ }
+
+ public boolean isRunning()
+ {
+ return stopLatch != null;
+ }
+
+ public final Object start(IApplicationContext context) throws Exception
+ {
+ this.context = context;
+ traceStart(applicationID);
+
+ try
+ {
+ doStart();
+ }
+ catch (Error error)
+ {
+ OM.LOG.error(error);
+ throw error;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ throw ex;
+ }
+
+ if (context != null)
+ {
+ context.applicationRunning();
+ }
+
+ stopLatch = new CountDownLatch(1);
+ stopLatch.await();
+ stopLatch = null;
+ return EXIT_OK;
+ }
+
+ public final void stop()
+ {
+ traceStop(applicationID);
+
+ try
+ {
+ doStop();
+ }
+ catch (Error error)
+ {
+ OM.LOG.error(error);
+ throw error;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+
+ context = null;
+ if (stopLatch != null)
+ {
+ stopLatch.countDown();
+ }
+ }
+
+ protected void doStart() throws Exception
+ {
+ }
+
+ protected void doStop() throws Exception
+ {
+ }
+
+ public static void traceStart(String applicationID)
+ {
+ try
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Starting application {0}", applicationID); //$NON-NLS-1$
+ }
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+
+ public static void traceStop(String applicationID)
+ {
+ try
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Stopping application {0}", applicationID); //$NON-NLS-1$
+ }
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/AbstractLogHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/AbstractLogHandler.java index 833c2b1e01..b7e6935157 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/AbstractLogHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/AbstractLogHandler.java @@ -1,76 +1,76 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class AbstractLogHandler implements OMLogHandler -{ - private Level logLevel; - - public AbstractLogHandler(Level logLevel) - { - this.logLevel = logLevel; - } - - public AbstractLogHandler() - { - this(Level.DEBUG); - } - - public Level getLogLevel() - { - return logLevel; - } - - public void setLogLevel(Level logLevel) - { - this.logLevel = logLevel; - } - - public void logged(OMLogger logger, Level level, String msg, Throwable t) - { - try - { - if (level.ordinal() <= logLevel.ordinal()) - { - writeLog(logger, level, msg, t); - } - } - catch (Throwable ignore) - { - // Ignore - } - } - - protected abstract void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable; - - public static String toString(Level level) - { - switch (level) - { - case ERROR: - return "[ERROR]"; //$NON-NLS-1$ - case WARN: - return "[WARN]"; //$NON-NLS-1$ - case INFO: - return "[INFO]"; //$NON-NLS-1$ - case DEBUG: - return "[DEBUG]"; //$NON-NLS-1$ - default: - throw new IllegalArgumentException("Illegal log level: " + level); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class AbstractLogHandler implements OMLogHandler
+{
+ private Level logLevel;
+
+ public AbstractLogHandler(Level logLevel)
+ {
+ this.logLevel = logLevel;
+ }
+
+ public AbstractLogHandler()
+ {
+ this(Level.DEBUG);
+ }
+
+ public Level getLogLevel()
+ {
+ return logLevel;
+ }
+
+ public void setLogLevel(Level logLevel)
+ {
+ this.logLevel = logLevel;
+ }
+
+ public void logged(OMLogger logger, Level level, String msg, Throwable t)
+ {
+ try
+ {
+ if (level.ordinal() <= logLevel.ordinal())
+ {
+ writeLog(logger, level, msg, t);
+ }
+ }
+ catch (Throwable ignore)
+ {
+ // Ignore
+ }
+ }
+
+ protected abstract void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable;
+
+ public static String toString(Level level)
+ {
+ switch (level)
+ {
+ case ERROR:
+ return "[ERROR]"; //$NON-NLS-1$
+ case WARN:
+ return "[WARN]"; //$NON-NLS-1$
+ case INFO:
+ return "[INFO]"; //$NON-NLS-1$
+ case DEBUG:
+ return "[DEBUG]"; //$NON-NLS-1$
+ default:
+ throw new IllegalArgumentException("Illegal log level: " + level); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/EclipseLoggingBridge.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/EclipseLoggingBridge.java index b372647b4e..c314132e16 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/EclipseLoggingBridge.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/EclipseLoggingBridge.java @@ -1,64 +1,64 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.internal.util.om.OSGiBundle; -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -import org.eclipse.core.runtime.ILog; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; -import org.eclipse.core.runtime.Status; - -/** - * @author Eike Stepper - */ -public class EclipseLoggingBridge implements OMLogHandler -{ - /** - * @Singleton - */ - public static final EclipseLoggingBridge INSTANCE = new EclipseLoggingBridge(); - - protected EclipseLoggingBridge() - { - } - - public void logged(OMLogger logger, Level level, String msg, Throwable t) - { - try - { - OSGiBundle bundle = (OSGiBundle)logger.getBundle(); - ILog log = Platform.getLog(bundle.getBundleContext().getBundle()); - log.log(new Status(toEclipse(level), bundle.getBundleID(), IStatus.OK, msg, t)); - } - catch (RuntimeException ignore) - { - } - } - - public static int toEclipse(Level level) - { - switch (level) - { - case ERROR: - return IStatus.ERROR; - case WARN: - return IStatus.WARNING; - case INFO: - return IStatus.INFO; - case DEBUG: - return IStatus.OK; - default: - throw new IllegalArgumentException("Illegal log level: " + level); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.internal.util.om.OSGiBundle;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+import org.eclipse.core.runtime.ILog;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.Platform;
+import org.eclipse.core.runtime.Status;
+
+/**
+ * @author Eike Stepper
+ */
+public class EclipseLoggingBridge implements OMLogHandler
+{
+ /**
+ * @Singleton
+ */
+ public static final EclipseLoggingBridge INSTANCE = new EclipseLoggingBridge();
+
+ protected EclipseLoggingBridge()
+ {
+ }
+
+ public void logged(OMLogger logger, Level level, String msg, Throwable t)
+ {
+ try
+ {
+ OSGiBundle bundle = (OSGiBundle)logger.getBundle();
+ ILog log = Platform.getLog(bundle.getBundleContext().getBundle());
+ log.log(new Status(toEclipse(level), bundle.getBundleID(), IStatus.OK, msg, t));
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+
+ public static int toEclipse(Level level)
+ {
+ switch (level)
+ {
+ case ERROR:
+ return IStatus.ERROR;
+ case WARN:
+ return IStatus.WARNING;
+ case INFO:
+ return IStatus.INFO;
+ case DEBUG:
+ return IStatus.OK;
+ default:
+ throw new IllegalArgumentException("Illegal log level: " + level); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/FileLogHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/FileLogHandler.java index aa6e9272a4..3072471680 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/FileLogHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/FileLogHandler.java @@ -1,64 +1,64 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class FileLogHandler extends AbstractLogHandler -{ - private File logFile; - - public FileLogHandler(File logFile, Level logLevel) - { - super(logLevel); - this.logFile = logFile; - } - - public FileLogHandler(File logFile) - { - this.logFile = logFile; - } - - public File getLogFile() - { - return logFile; - } - - @Override - protected void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable - { - FileOutputStream fos = null; - - try - { - fos = new FileOutputStream(logFile, true); - PrintStream stream = new PrintStream(fos); - stream.println(toString(level) + " " + msg); //$NON-NLS-1$ - if (t != null) - { - IOUtil.print(t, stream); - } - } - finally - { - IOUtil.close(fos); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.PrintStream;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class FileLogHandler extends AbstractLogHandler
+{
+ private File logFile;
+
+ public FileLogHandler(File logFile, Level logLevel)
+ {
+ super(logLevel);
+ this.logFile = logFile;
+ }
+
+ public FileLogHandler(File logFile)
+ {
+ this.logFile = logFile;
+ }
+
+ public File getLogFile()
+ {
+ return logFile;
+ }
+
+ @Override
+ protected void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable
+ {
+ FileOutputStream fos = null;
+
+ try
+ {
+ fos = new FileOutputStream(logFile, true);
+ PrintStream stream = new PrintStream(fos);
+ stream.println(toString(level) + " " + msg); //$NON-NLS-1$
+ if (t != null)
+ {
+ IOUtil.print(t, stream);
+ }
+ }
+ finally
+ {
+ IOUtil.close(fos);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/Logger.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/Logger.java index 526438a8e1..0aedecc08d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/Logger.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/Logger.java @@ -1,113 +1,113 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.om.OMBundle; - -/** - * @author Eike Stepper - */ -public class Logger implements OMLogger -{ - private OMBundle bundle; - - public Logger(OMBundle bundle) - { - this.bundle = bundle; - } - - public OMBundle getBundle() - { - return bundle; - } - - public void log(Level level, String msg, Throwable t) - { - ((AbstractPlatform)bundle.getPlatform()).log(this, level, msg, t); - } - - public void error(String msg, Throwable t) - { - log(Level.ERROR, msg, t); - } - - public void warn(String msg, Throwable t) - { - log(Level.WARN, msg, t); - } - - public void info(String msg, Throwable t) - { - log(Level.INFO, msg, t); - } - - public void debug(String msg, Throwable t) - { - log(Level.DEBUG, msg, t); - } - - public void log(Level level, String msg) - { - log(level, msg, null); - } - - public void error(String msg) - { - log(Level.ERROR, msg); - } - - public void warn(String msg) - { - log(Level.WARN, msg); - } - - public void info(String msg) - { - log(Level.INFO, msg); - } - - public void debug(String msg) - { - log(Level.DEBUG, msg); - } - - public void log(Level level, Throwable t) - { - String msg = t.getMessage(); - if (msg == null) - { - msg = t.getClass().getSimpleName(); - } - - log(level, msg, t); - } - - public void error(Throwable t) - { - log(Level.ERROR, t); - } - - public void warn(Throwable t) - { - log(Level.WARN, t); - } - - public void info(Throwable t) - { - log(Level.INFO, t); - } - - public void debug(Throwable t) - { - log(Level.DEBUG, t); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.om.OMBundle;
+
+/**
+ * @author Eike Stepper
+ */
+public class Logger implements OMLogger
+{
+ private OMBundle bundle;
+
+ public Logger(OMBundle bundle)
+ {
+ this.bundle = bundle;
+ }
+
+ public OMBundle getBundle()
+ {
+ return bundle;
+ }
+
+ public void log(Level level, String msg, Throwable t)
+ {
+ ((AbstractPlatform)bundle.getPlatform()).log(this, level, msg, t);
+ }
+
+ public void error(String msg, Throwable t)
+ {
+ log(Level.ERROR, msg, t);
+ }
+
+ public void warn(String msg, Throwable t)
+ {
+ log(Level.WARN, msg, t);
+ }
+
+ public void info(String msg, Throwable t)
+ {
+ log(Level.INFO, msg, t);
+ }
+
+ public void debug(String msg, Throwable t)
+ {
+ log(Level.DEBUG, msg, t);
+ }
+
+ public void log(Level level, String msg)
+ {
+ log(level, msg, null);
+ }
+
+ public void error(String msg)
+ {
+ log(Level.ERROR, msg);
+ }
+
+ public void warn(String msg)
+ {
+ log(Level.WARN, msg);
+ }
+
+ public void info(String msg)
+ {
+ log(Level.INFO, msg);
+ }
+
+ public void debug(String msg)
+ {
+ log(Level.DEBUG, msg);
+ }
+
+ public void log(Level level, Throwable t)
+ {
+ String msg = t.getMessage();
+ if (msg == null)
+ {
+ msg = t.getClass().getSimpleName();
+ }
+
+ log(level, msg, t);
+ }
+
+ public void error(Throwable t)
+ {
+ log(Level.ERROR, t);
+ }
+
+ public void warn(Throwable t)
+ {
+ log(Level.WARN, t);
+ }
+
+ public void info(Throwable t)
+ {
+ log(Level.INFO, t);
+ }
+
+ public void debug(Throwable t)
+ {
+ log(Level.DEBUG, t);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogFilter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogFilter.java index d9d902fa20..34545e9f06 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogFilter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogFilter.java @@ -1,31 +1,31 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.util.om.OMPlatform; -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -/** - * Filters log events before they are being passed to {@link OMPlatform#addLogFilter(OMLogFilter) registered} - * {@link OMLogHandler log handlers}. - * - * @author Eike Stepper - * @since 3.2 - */ -public interface OMLogFilter -{ - /** - * Prevents the log event represented by the arguments from being passed to - * {@link OMPlatform#addLogFilter(OMLogFilter) registered} {@link OMLogHandler log handlers}, if and only if - * <code>true</code> is returned. - */ - public boolean filter(OMLogger logger, Level level, String msg, Throwable t); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.util.om.OMPlatform;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+/**
+ * Filters log events before they are being passed to {@link OMPlatform#addLogFilter(OMLogFilter) registered}
+ * {@link OMLogHandler log handlers}.
+ *
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public interface OMLogFilter
+{
+ /**
+ * Prevents the log event represented by the arguments from being passed to
+ * {@link OMPlatform#addLogFilter(OMLogFilter) registered} {@link OMLogHandler log handlers}, if and only if
+ * <code>true</code> is returned.
+ */
+ public boolean filter(OMLogger logger, Level level, String msg, Throwable t);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogHandler.java index e275ad2500..3c4c7a2f12 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogHandler.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -/** - * @author Eike Stepper - */ -public interface OMLogHandler -{ - public void logged(OMLogger logger, Level level, String msg, Throwable t); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+/**
+ * @author Eike Stepper
+ */
+public interface OMLogHandler
+{
+ public void logged(OMLogger logger, Level level, String msg, Throwable t);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogger.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogger.java index 5048257148..fda15b3d73 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogger.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OMLogger.java @@ -1,61 +1,61 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.util.om.OMBundle; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMLogger -{ - public OMBundle getBundle(); - - public void log(Level level, String msg, Throwable t); - - public void error(String msg, Throwable t); - - public void warn(String msg, Throwable t); - - public void info(String msg, Throwable t); - - public void debug(String msg, Throwable t); - - public void log(Level level, String msg); - - public void error(String msg); - - public void warn(String msg); - - public void info(String msg); - - public void debug(String msg); - - public void log(Level level, Throwable t); - - public void error(Throwable t); - - public void warn(Throwable t); - - public void info(Throwable t); - - public void debug(Throwable t); - - /** - * @author Eike Stepper - */ - public enum Level - { - ERROR, WARN, INFO, DEBUG - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.util.om.OMBundle;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMLogger
+{
+ public OMBundle getBundle();
+
+ public void log(Level level, String msg, Throwable t);
+
+ public void error(String msg, Throwable t);
+
+ public void warn(String msg, Throwable t);
+
+ public void info(String msg, Throwable t);
+
+ public void debug(String msg, Throwable t);
+
+ public void log(Level level, String msg);
+
+ public void error(String msg);
+
+ public void warn(String msg);
+
+ public void info(String msg);
+
+ public void debug(String msg);
+
+ public void log(Level level, Throwable t);
+
+ public void error(Throwable t);
+
+ public void warn(Throwable t);
+
+ public void info(Throwable t);
+
+ public void debug(Throwable t);
+
+ /**
+ * @author Eike Stepper
+ */
+ public enum Level
+ {
+ ERROR, WARN, INFO, DEBUG
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OSGiLoggingBridge.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OSGiLoggingBridge.java index 8b15f88f06..9e887612b6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OSGiLoggingBridge.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/OSGiLoggingBridge.java @@ -1,81 +1,81 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.internal.util.om.OSGiBundle; -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogService; - -/** - * @author Eike Stepper - */ -public class OSGiLoggingBridge implements OMLogHandler -{ - // @Singleton - public static final OSGiLoggingBridge INSTANCE = new OSGiLoggingBridge(); - - protected OSGiLoggingBridge() - { - } - - public void logged(OMLogger logger, Level level, String msg, Throwable t) - { - try - { - BundleContext bundleContext = ((OSGiBundle)logger.getBundle()).getBundleContext(); - logged(bundleContext, level, msg, t); - } - catch (RuntimeException ignore) - { - } - } - - public void logged(BundleContext bundleContext, Level level, String msg, Throwable t) - { - LogService logService = getLogService(bundleContext); - logService.log(toOSGi(level), msg, t); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected LogService getLogService(BundleContext bundleContext) - { - try - { - ServiceReference ref = bundleContext.getServiceReference(LogService.class.getName()); - LogService logService = (LogService)bundleContext.getService(ref); - return logService; - } - catch (RuntimeException ex) - { - throw new IllegalStateException("Log service not found", ex); //$NON-NLS-1$ - } - } - - public static int toOSGi(Level level) - { - switch (level) - { - case ERROR: - return LogService.LOG_ERROR; - case WARN: - return LogService.LOG_WARNING; - case INFO: - return LogService.LOG_INFO; - case DEBUG: - return LogService.LOG_DEBUG; - default: - throw new IllegalArgumentException("Illegal log level: " + level); //$NON-NLS-1$ - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.internal.util.om.OSGiBundle;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.log.LogService;
+
+/**
+ * @author Eike Stepper
+ */
+public class OSGiLoggingBridge implements OMLogHandler
+{
+ // @Singleton
+ public static final OSGiLoggingBridge INSTANCE = new OSGiLoggingBridge();
+
+ protected OSGiLoggingBridge()
+ {
+ }
+
+ public void logged(OMLogger logger, Level level, String msg, Throwable t)
+ {
+ try
+ {
+ BundleContext bundleContext = ((OSGiBundle)logger.getBundle()).getBundleContext();
+ logged(bundleContext, level, msg, t);
+ }
+ catch (RuntimeException ignore)
+ {
+ }
+ }
+
+ public void logged(BundleContext bundleContext, Level level, String msg, Throwable t)
+ {
+ LogService logService = getLogService(bundleContext);
+ logService.log(toOSGi(level), msg, t);
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected LogService getLogService(BundleContext bundleContext)
+ {
+ try
+ {
+ ServiceReference ref = bundleContext.getServiceReference(LogService.class.getName());
+ LogService logService = (LogService)bundleContext.getService(ref);
+ return logService;
+ }
+ catch (RuntimeException ex)
+ {
+ throw new IllegalStateException("Log service not found", ex); //$NON-NLS-1$
+ }
+ }
+
+ public static int toOSGi(Level level)
+ {
+ switch (level)
+ {
+ case ERROR:
+ return LogService.LOG_ERROR;
+ case WARN:
+ return LogService.LOG_WARNING;
+ case INFO:
+ return LogService.LOG_INFO;
+ case DEBUG:
+ return LogService.LOG_DEBUG;
+ default:
+ throw new IllegalArgumentException("Illegal log level: " + level); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/PrintLogHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/PrintLogHandler.java index f4959a18cc..2feb28ae50 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/PrintLogHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/PrintLogHandler.java @@ -1,50 +1,50 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.log; - -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.log.OMLogger.Level; - -import java.io.PrintStream; - -/** - * @author Eike Stepper - */ -public class PrintLogHandler extends AbstractLogHandler -{ - public static final PrintLogHandler CONSOLE = new PrintLogHandler(); - - private PrintStream out; - - private PrintStream err; - - public PrintLogHandler(PrintStream out, PrintStream err) - { - this.out = out; - this.err = err; - } - - protected PrintLogHandler() - { - this(IOUtil.OUT(), IOUtil.ERR()); - } - - @Override - protected void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable - { - PrintStream stream = level == Level.ERROR ? err : out; - stream.println(toString(level) + " " + msg); //$NON-NLS-1$ - if (t != null) - { - IOUtil.print(t, stream); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.log;
+
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.log.OMLogger.Level;
+
+import java.io.PrintStream;
+
+/**
+ * @author Eike Stepper
+ */
+public class PrintLogHandler extends AbstractLogHandler
+{
+ public static final PrintLogHandler CONSOLE = new PrintLogHandler();
+
+ private PrintStream out;
+
+ private PrintStream err;
+
+ public PrintLogHandler(PrintStream out, PrintStream err)
+ {
+ this.out = out;
+ this.err = err;
+ }
+
+ protected PrintLogHandler()
+ {
+ this(IOUtil.OUT(), IOUtil.ERR());
+ }
+
+ @Override
+ protected void writeLog(OMLogger logger, Level level, String msg, Throwable t) throws Throwable
+ {
+ PrintStream stream = level == Level.ERROR ? err : out;
+ stream.println(toString(level) + " " + msg); //$NON-NLS-1$
+ if (t != null)
+ {
+ IOUtil.print(t, stream);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java index 83f37850c6..e13650fc23 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java index 315fae7d79..3bef60ad82 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java @@ -1,207 +1,207 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import org.eclipse.net4j.internal.util.bundle.OM; - -import java.util.Timer; -import java.util.TimerTask; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class AbstractMonitor implements OMMonitor -{ - private static final long NOT_BEGUN = -1; - - private double totalWork = NOT_BEGUN; - - private double work; - - public AbstractMonitor() - { - } - - public boolean hasBegun() throws MonitorCanceledException - { - checkCanceled(); - return totalWork != NOT_BEGUN; - } - - public OMMonitor begin(double totalWork) throws MonitorCanceledException - { - checkCanceled(); - this.totalWork = totalWork; - return this; - } - - public OMMonitor begin() throws MonitorCanceledException - { - return begin(ONE); - } - - public void worked(double work) throws MonitorCanceledException - { - checkBegun(); - this.work += work; - } - - public void worked() throws MonitorCanceledException - { - worked(ONE); - } - - public OMMonitor fork(double work) - { - checkBegun(); - return createNestedMonitor(work); - } - - public OMMonitor fork() - { - return fork(ONE); - } - - public Async forkAsync(double work) - { - checkBegun(); - AsyncTimerTask asyncTimerTask = createAsyncTimerTask(work); - if (asyncTimerTask == null) - { - throw new NullPointerException("No async timer task has been created"); - } - - long period = getAsyncSchedulePeriod(); - scheduleAtFixedRate(asyncTimerTask, period, period); - return asyncTimerTask; - } - - public Async forkAsync() - { - return forkAsync(ONE); - } - - public void done() - { - if (!isCanceled()) - { - double rest = totalWork - work; - if (rest > 0) - { - worked(rest); - } - } - } - - public double getTotalWork() - { - return totalWork; - } - - public double getWork() - { - return work; - } - - public double getWorkPercent() - { - return percent(work, totalWork); - } - - protected OMMonitor createNestedMonitor(double work) - { - return new NestedMonitor(this, work); - } - - protected AsyncTimerTask createAsyncTimerTask(double work) - { - return new AsyncTimerTask(this, work, DEFAULT_TIME_FACTOR); - } - - protected abstract long getAsyncSchedulePeriod(); - - protected abstract Timer getTimer(); - - /** - * @since 3.0 - */ - protected abstract void scheduleAtFixedRate(TimerTask task, long delay, long period); - - private void checkBegun() throws MonitorCanceledException - { - if (!hasBegun()) - { - throw new IllegalStateException("begin() has not been called"); //$NON-NLS-1$ - } - } - - /** - * @since 3.1 - */ - protected static double percent(double part, double whole) - { - return Math.min(part * HUNDRED / whole, HUNDRED); - } - - /** - * @author Eike Stepper - */ - public static class AsyncTimerTask extends TimerTask implements Async - { - private OMMonitor monitor; - - private boolean canceled; - - public AsyncTimerTask(AbstractMonitor parent, double parentWork, double timeFactor) - { - monitor = parent.fork(parentWork); - monitor.begin(); - } - - @Override - public void run() - { - try - { - if (!canceled) - { - double work = 1 - monitor.getWork(); - monitor.worked(work / TEN); - } - } - catch (Exception ex) - { - OM.LOG.error("AsyncTimerTask failed", ex); - } - } - - public void stop() - { - try - { - monitor.done(); - cancel(); - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - } - - @Override - public boolean cancel() - { - canceled = true; - return super.cancel(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class AbstractMonitor implements OMMonitor
+{
+ private static final long NOT_BEGUN = -1;
+
+ private double totalWork = NOT_BEGUN;
+
+ private double work;
+
+ public AbstractMonitor()
+ {
+ }
+
+ public boolean hasBegun() throws MonitorCanceledException
+ {
+ checkCanceled();
+ return totalWork != NOT_BEGUN;
+ }
+
+ public OMMonitor begin(double totalWork) throws MonitorCanceledException
+ {
+ checkCanceled();
+ this.totalWork = totalWork;
+ return this;
+ }
+
+ public OMMonitor begin() throws MonitorCanceledException
+ {
+ return begin(ONE);
+ }
+
+ public void worked(double work) throws MonitorCanceledException
+ {
+ checkBegun();
+ this.work += work;
+ }
+
+ public void worked() throws MonitorCanceledException
+ {
+ worked(ONE);
+ }
+
+ public OMMonitor fork(double work)
+ {
+ checkBegun();
+ return createNestedMonitor(work);
+ }
+
+ public OMMonitor fork()
+ {
+ return fork(ONE);
+ }
+
+ public Async forkAsync(double work)
+ {
+ checkBegun();
+ AsyncTimerTask asyncTimerTask = createAsyncTimerTask(work);
+ if (asyncTimerTask == null)
+ {
+ throw new NullPointerException("No async timer task has been created");
+ }
+
+ long period = getAsyncSchedulePeriod();
+ scheduleAtFixedRate(asyncTimerTask, period, period);
+ return asyncTimerTask;
+ }
+
+ public Async forkAsync()
+ {
+ return forkAsync(ONE);
+ }
+
+ public void done()
+ {
+ if (!isCanceled())
+ {
+ double rest = totalWork - work;
+ if (rest > 0)
+ {
+ worked(rest);
+ }
+ }
+ }
+
+ public double getTotalWork()
+ {
+ return totalWork;
+ }
+
+ public double getWork()
+ {
+ return work;
+ }
+
+ public double getWorkPercent()
+ {
+ return percent(work, totalWork);
+ }
+
+ protected OMMonitor createNestedMonitor(double work)
+ {
+ return new NestedMonitor(this, work);
+ }
+
+ protected AsyncTimerTask createAsyncTimerTask(double work)
+ {
+ return new AsyncTimerTask(this, work, DEFAULT_TIME_FACTOR);
+ }
+
+ protected abstract long getAsyncSchedulePeriod();
+
+ protected abstract Timer getTimer();
+
+ /**
+ * @since 3.0
+ */
+ protected abstract void scheduleAtFixedRate(TimerTask task, long delay, long period);
+
+ private void checkBegun() throws MonitorCanceledException
+ {
+ if (!hasBegun())
+ {
+ throw new IllegalStateException("begin() has not been called"); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * @since 3.1
+ */
+ protected static double percent(double part, double whole)
+ {
+ return Math.min(part * HUNDRED / whole, HUNDRED);
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class AsyncTimerTask extends TimerTask implements Async
+ {
+ private OMMonitor monitor;
+
+ private boolean canceled;
+
+ public AsyncTimerTask(AbstractMonitor parent, double parentWork, double timeFactor)
+ {
+ monitor = parent.fork(parentWork);
+ monitor.begin();
+ }
+
+ @Override
+ public void run()
+ {
+ try
+ {
+ if (!canceled)
+ {
+ double work = 1 - monitor.getWork();
+ monitor.worked(work / TEN);
+ }
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error("AsyncTimerTask failed", ex);
+ }
+ }
+
+ public void stop()
+ {
+ try
+ {
+ monitor.done();
+ cancel();
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+ }
+
+ @Override
+ public boolean cancel()
+ {
+ canceled = true;
+ return super.cancel();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java index f07ed8a16f..a39766e75c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java @@ -1,105 +1,105 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class DelegatingMonitor implements OMMonitor -{ - private OMMonitor delegate; - - public DelegatingMonitor(OMMonitor delegate) - { - this.delegate = delegate; - } - - public OMMonitor getDelegate() - { - return delegate; - } - - public boolean hasBegun() throws MonitorCanceledException - { - return delegate.hasBegun(); - } - - public OMMonitor begin() throws MonitorCanceledException - { - return delegate.begin(); - } - - public OMMonitor begin(double totalWork) throws MonitorCanceledException - { - return delegate.begin(totalWork); - } - - public void checkCanceled() throws MonitorCanceledException - { - delegate.checkCanceled(); - } - - public void done() - { - delegate.done(); - } - - public OMMonitor fork() - { - return delegate.fork(); - } - - public OMMonitor fork(double work) - { - return delegate.fork(work); - } - - public Async forkAsync() - { - return delegate.forkAsync(); - } - - public Async forkAsync(double work) - { - return delegate.forkAsync(work); - } - - public double getTotalWork() - { - return delegate.getTotalWork(); - } - - public double getWork() - { - return delegate.getWork(); - } - - public double getWorkPercent() - { - return delegate.getWorkPercent(); - } - - public boolean isCanceled() - { - return delegate.isCanceled(); - } - - public void worked() throws MonitorCanceledException - { - delegate.worked(); - } - - public void worked(double work) throws MonitorCanceledException - { - delegate.worked(work); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class DelegatingMonitor implements OMMonitor
+{
+ private OMMonitor delegate;
+
+ public DelegatingMonitor(OMMonitor delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public OMMonitor getDelegate()
+ {
+ return delegate;
+ }
+
+ public boolean hasBegun() throws MonitorCanceledException
+ {
+ return delegate.hasBegun();
+ }
+
+ public OMMonitor begin() throws MonitorCanceledException
+ {
+ return delegate.begin();
+ }
+
+ public OMMonitor begin(double totalWork) throws MonitorCanceledException
+ {
+ return delegate.begin(totalWork);
+ }
+
+ public void checkCanceled() throws MonitorCanceledException
+ {
+ delegate.checkCanceled();
+ }
+
+ public void done()
+ {
+ delegate.done();
+ }
+
+ public OMMonitor fork()
+ {
+ return delegate.fork();
+ }
+
+ public OMMonitor fork(double work)
+ {
+ return delegate.fork(work);
+ }
+
+ public Async forkAsync()
+ {
+ return delegate.forkAsync();
+ }
+
+ public Async forkAsync(double work)
+ {
+ return delegate.forkAsync(work);
+ }
+
+ public double getTotalWork()
+ {
+ return delegate.getTotalWork();
+ }
+
+ public double getWork()
+ {
+ return delegate.getWork();
+ }
+
+ public double getWorkPercent()
+ {
+ return delegate.getWorkPercent();
+ }
+
+ public boolean isCanceled()
+ {
+ return delegate.isCanceled();
+ }
+
+ public void worked() throws MonitorCanceledException
+ {
+ delegate.worked();
+ }
+
+ public void worked(double work) throws MonitorCanceledException
+ {
+ delegate.worked(work);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java index fe8ece6d7e..65764b9c4f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java @@ -1,182 +1,182 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import org.eclipse.net4j.util.StringUtil; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.SubProgressMonitor; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class EclipseMonitor extends Monitor -{ - private IProgressMonitor progressMonitor; - - private String taskName; - - public EclipseMonitor(IProgressMonitor progressMonitor, String taskName) - { - this.progressMonitor = progressMonitor; - this.taskName = taskName; - } - - public EclipseMonitor(IProgressMonitor progressMonitor) - { - this(progressMonitor, StringUtil.EMPTY); - } - - public String getTaskName() - { - return taskName; - } - - @Override - public boolean isCanceled() - { - if (super.isCanceled()) - { - return true; - } - - return progressMonitor.isCanceled(); - } - - @Override - public OMMonitor begin(double totalWork) throws MonitorCanceledException - { - super.begin(totalWork); - int eclipseWork = totalWork > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)totalWork; - progressMonitor.beginTask(taskName, eclipseWork); - return this; - } - - @Override - public void worked(double work) throws MonitorCanceledException - { - super.worked(work); - progressMonitor.internalWorked(work); - } - - @Override - public void done() - { - super.done(); - progressMonitor.done(); - } - - /** - * A sub progress monitor that synchronizes all methods on the parent monitor instance. - * - * @author Eike Stepper - * @since 3.0 - */ - public static class SynchronizedSubProgressMonitor extends SubProgressMonitor - { - public SynchronizedSubProgressMonitor(IProgressMonitor monitor, int ticks) - { - super(monitor, ticks); - } - - @Override - public void beginTask(String name, int totalWork) - { - synchronized (getWrappedProgressMonitor()) - { - super.beginTask(name, totalWork); - } - } - - @Override - public void clearBlocked() - { - synchronized (getWrappedProgressMonitor()) - { - super.clearBlocked(); - } - } - - @Override - public void done() - { - synchronized (getWrappedProgressMonitor()) - { - super.done(); - } - } - - @Override - public void internalWorked(double work) - { - synchronized (getWrappedProgressMonitor()) - { - super.internalWorked(work); - } - } - - @Override - public boolean isCanceled() - { - synchronized (getWrappedProgressMonitor()) - { - return super.isCanceled(); - } - } - - @Override - public void setBlocked(IStatus reason) - { - synchronized (getWrappedProgressMonitor()) - { - super.setBlocked(reason); - } - } - - @Override - public void setCanceled(boolean b) - { - synchronized (getWrappedProgressMonitor()) - { - super.setCanceled(b); - } - } - - @Override - public void setTaskName(String name) - { - synchronized (getWrappedProgressMonitor()) - { - super.setTaskName(name); - } - } - - @Override - public void subTask(String name) - { - synchronized (getWrappedProgressMonitor()) - { - super.subTask(name); - } - } - - @Override - public void worked(int work) - { - synchronized (getWrappedProgressMonitor()) - { - super.worked(work); - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import org.eclipse.net4j.util.StringUtil;
+
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.IStatus;
+import org.eclipse.core.runtime.SubProgressMonitor;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class EclipseMonitor extends Monitor
+{
+ private IProgressMonitor progressMonitor;
+
+ private String taskName;
+
+ public EclipseMonitor(IProgressMonitor progressMonitor, String taskName)
+ {
+ this.progressMonitor = progressMonitor;
+ this.taskName = taskName;
+ }
+
+ public EclipseMonitor(IProgressMonitor progressMonitor)
+ {
+ this(progressMonitor, StringUtil.EMPTY);
+ }
+
+ public String getTaskName()
+ {
+ return taskName;
+ }
+
+ @Override
+ public boolean isCanceled()
+ {
+ if (super.isCanceled())
+ {
+ return true;
+ }
+
+ return progressMonitor.isCanceled();
+ }
+
+ @Override
+ public OMMonitor begin(double totalWork) throws MonitorCanceledException
+ {
+ super.begin(totalWork);
+ int eclipseWork = totalWork > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)totalWork;
+ progressMonitor.beginTask(taskName, eclipseWork);
+ return this;
+ }
+
+ @Override
+ public void worked(double work) throws MonitorCanceledException
+ {
+ super.worked(work);
+ progressMonitor.internalWorked(work);
+ }
+
+ @Override
+ public void done()
+ {
+ super.done();
+ progressMonitor.done();
+ }
+
+ /**
+ * A sub progress monitor that synchronizes all methods on the parent monitor instance.
+ *
+ * @author Eike Stepper
+ * @since 3.0
+ */
+ public static class SynchronizedSubProgressMonitor extends SubProgressMonitor
+ {
+ public SynchronizedSubProgressMonitor(IProgressMonitor monitor, int ticks)
+ {
+ super(monitor, ticks);
+ }
+
+ @Override
+ public void beginTask(String name, int totalWork)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.beginTask(name, totalWork);
+ }
+ }
+
+ @Override
+ public void clearBlocked()
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.clearBlocked();
+ }
+ }
+
+ @Override
+ public void done()
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.done();
+ }
+ }
+
+ @Override
+ public void internalWorked(double work)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.internalWorked(work);
+ }
+ }
+
+ @Override
+ public boolean isCanceled()
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ return super.isCanceled();
+ }
+ }
+
+ @Override
+ public void setBlocked(IStatus reason)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.setBlocked(reason);
+ }
+ }
+
+ @Override
+ public void setCanceled(boolean b)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.setCanceled(b);
+ }
+ }
+
+ @Override
+ public void setTaskName(String name)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.setTaskName(name);
+ }
+ }
+
+ @Override
+ public void subTask(String name)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.subTask(name);
+ }
+ }
+
+ @Override
+ public void worked(int work)
+ {
+ synchronized (getWrappedProgressMonitor())
+ {
+ super.worked(work);
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java index 2b3cb9dc72..3ce10053a2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java @@ -1,97 +1,97 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import org.eclipse.net4j.internal.util.bundle.OM; - -import java.util.Timer; -import java.util.TimerTask; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class Monitor extends AbstractMonitor -{ - public static final long DEFAULT_ASYNC_SCHEDULE_PERIOD = 1000; - - private static Timer TIMER; - - private boolean canceled; - - private RuntimeException cancelException; - - public Monitor() - { - } - - public void cancel() - { - cancel(null); - } - - public void cancel(RuntimeException cancelException) - { - this.cancelException = cancelException; - canceled = true; - } - - public boolean isCanceled() - { - return canceled; - } - - public void checkCanceled() throws MonitorCanceledException - { - if (cancelException != null) - { - throw new MonitorCanceledException(cancelException); - } - - if (canceled) - { - throw new MonitorCanceledException(); - } - } - - @Override - protected long getAsyncSchedulePeriod() - { - return DEFAULT_ASYNC_SCHEDULE_PERIOD; - } - - @Override - protected Timer getTimer() - { - synchronized (Monitor.class) - { - if (TIMER == null) - { - TIMER = new Timer("monitor-timer", true); //$NON-NLS-1$ - } - - return TIMER; - } - } - - @Override - protected void scheduleAtFixedRate(TimerTask task, long delay, long period) - { - try - { - getTimer().scheduleAtFixedRate(task, delay, period); - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class Monitor extends AbstractMonitor
+{
+ public static final long DEFAULT_ASYNC_SCHEDULE_PERIOD = 1000;
+
+ private static Timer TIMER;
+
+ private boolean canceled;
+
+ private RuntimeException cancelException;
+
+ public Monitor()
+ {
+ }
+
+ public void cancel()
+ {
+ cancel(null);
+ }
+
+ public void cancel(RuntimeException cancelException)
+ {
+ this.cancelException = cancelException;
+ canceled = true;
+ }
+
+ public boolean isCanceled()
+ {
+ return canceled;
+ }
+
+ public void checkCanceled() throws MonitorCanceledException
+ {
+ if (cancelException != null)
+ {
+ throw new MonitorCanceledException(cancelException);
+ }
+
+ if (canceled)
+ {
+ throw new MonitorCanceledException();
+ }
+ }
+
+ @Override
+ protected long getAsyncSchedulePeriod()
+ {
+ return DEFAULT_ASYNC_SCHEDULE_PERIOD;
+ }
+
+ @Override
+ protected Timer getTimer()
+ {
+ synchronized (Monitor.class)
+ {
+ if (TIMER == null)
+ {
+ TIMER = new Timer("monitor-timer", true); //$NON-NLS-1$
+ }
+
+ return TIMER;
+ }
+ }
+
+ @Override
+ protected void scheduleAtFixedRate(TimerTask task, long delay, long period)
+ {
+ try
+ {
+ getTimer().scheduleAtFixedRate(task, delay, period);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java index 0c9bf88c57..567cdd1b6e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java @@ -1,40 +1,40 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -/** - * @author Eike Stepper - * @since 2.0 - * @noextend This interface is not intended to be extended by clients. - */ -public class MonitorCanceledException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public MonitorCanceledException() - { - } - - public MonitorCanceledException(String message) - { - super(message); - } - - public MonitorCanceledException(Throwable cause) - { - super(cause); - } - - public MonitorCanceledException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public class MonitorCanceledException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public MonitorCanceledException()
+ {
+ }
+
+ public MonitorCanceledException(String message)
+ {
+ super(message);
+ }
+
+ public MonitorCanceledException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public MonitorCanceledException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java index 1e4fe8b7e3..1cfa5e4c27 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java @@ -1,107 +1,107 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import java.util.Timer; -import java.util.TimerTask; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class NestedMonitor extends AbstractMonitor -{ - private AbstractMonitor parent; - - private double parentWork; - - private double sentToParent; - - private double scale; - - private boolean usedUp; - - public NestedMonitor(AbstractMonitor parent, double parentWork) - { - this.parent = parent; - this.parentWork = parentWork > ZERO ? parentWork : ZERO; - } - - public AbstractMonitor getParent() - { - return parent; - } - - public double getParentWork() - { - return parentWork; - } - - public boolean isCanceled() - { - return parent.isCanceled(); - } - - public void checkCanceled() throws MonitorCanceledException - { - parent.checkCanceled(); - } - - @Override - public OMMonitor begin(double totalWork) throws MonitorCanceledException - { - super.begin(totalWork); - scale = totalWork > ZERO ? parentWork / totalWork : ZERO; - return this; - } - - @Override - public void worked(double work) throws MonitorCanceledException - { - if (!usedUp) - { - super.worked(work); - double realWork = work > ZERO ? scale * work : ZERO; - parent.worked(realWork); - sentToParent += realWork; - if (sentToParent >= parentWork) - { - usedUp = true; - } - } - } - - @Override - public void done() - { - super.done(); - sentToParent = ZERO; - usedUp = true; - } - - @Override - protected long getAsyncSchedulePeriod() - { - return parent.getAsyncSchedulePeriod(); - } - - @Override - protected void scheduleAtFixedRate(TimerTask task, long delay, long period) - { - parent.scheduleAtFixedRate(task, delay, period); - } - - @Override - protected Timer getTimer() - { - return parent.getTimer(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class NestedMonitor extends AbstractMonitor
+{
+ private AbstractMonitor parent;
+
+ private double parentWork;
+
+ private double sentToParent;
+
+ private double scale;
+
+ private boolean usedUp;
+
+ public NestedMonitor(AbstractMonitor parent, double parentWork)
+ {
+ this.parent = parent;
+ this.parentWork = parentWork > ZERO ? parentWork : ZERO;
+ }
+
+ public AbstractMonitor getParent()
+ {
+ return parent;
+ }
+
+ public double getParentWork()
+ {
+ return parentWork;
+ }
+
+ public boolean isCanceled()
+ {
+ return parent.isCanceled();
+ }
+
+ public void checkCanceled() throws MonitorCanceledException
+ {
+ parent.checkCanceled();
+ }
+
+ @Override
+ public OMMonitor begin(double totalWork) throws MonitorCanceledException
+ {
+ super.begin(totalWork);
+ scale = totalWork > ZERO ? parentWork / totalWork : ZERO;
+ return this;
+ }
+
+ @Override
+ public void worked(double work) throws MonitorCanceledException
+ {
+ if (!usedUp)
+ {
+ super.worked(work);
+ double realWork = work > ZERO ? scale * work : ZERO;
+ parent.worked(realWork);
+ sentToParent += realWork;
+ if (sentToParent >= parentWork)
+ {
+ usedUp = true;
+ }
+ }
+ }
+
+ @Override
+ public void done()
+ {
+ super.done();
+ sentToParent = ZERO;
+ usedUp = true;
+ }
+
+ @Override
+ protected long getAsyncSchedulePeriod()
+ {
+ return parent.getAsyncSchedulePeriod();
+ }
+
+ @Override
+ protected void scheduleAtFixedRate(TimerTask task, long delay, long period)
+ {
+ parent.scheduleAtFixedRate(task, delay, period);
+ }
+
+ @Override
+ protected Timer getTimer()
+ {
+ return parent.getTimer();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NotifyingMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NotifyingMonitor.java index 4a9f2ad940..9cf0e1c6c7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NotifyingMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NotifyingMonitor.java @@ -1,124 +1,124 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import org.eclipse.net4j.util.event.Event; -import org.eclipse.net4j.util.event.IListener; -import org.eclipse.net4j.util.event.INotifier; -import org.eclipse.net4j.util.event.Notifier; - -/** - * @author Eike Stepper - * @since 3.1 - */ -public class NotifyingMonitor extends Monitor implements INotifier -{ - private Notifier notifier = new Notifier(); - - private String task; - - public NotifyingMonitor() - { - } - - public NotifyingMonitor(String task) - { - this.task = task; - } - - public NotifyingMonitor(String task, IListener[] listeners) - { - this(task); - if (listeners != null) - { - for (IListener listener : listeners) - { - addListener(listener); - } - } - } - - public String getTask() - { - return task; - } - - public boolean hasListeners() - { - return notifier.hasListeners(); - } - - public IListener[] getListeners() - { - return notifier.getListeners(); - } - - public void addListener(IListener listener) - { - notifier.addListener(listener); - } - - public void removeListener(IListener listener) - { - notifier.removeListener(listener); - } - - @Override - public void worked(double work) throws MonitorCanceledException - { - super.worked(work); - - IListener[] listeners = getListeners(); - if (listeners != null) - { - notifier.fireEvent(new ProgressEvent(getTotalWork(), getWork()), listeners); - } - } - - /** - * @author Eike Stepper - */ - public final class ProgressEvent extends Event implements OMMonitorProgress - { - private static final long serialVersionUID = 1L; - - private double totalWork; - - private double work; - - private ProgressEvent(double totalWork, double work) - { - super(NotifyingMonitor.this); - this.totalWork = totalWork; - this.work = work; - } - - public String getTask() - { - return NotifyingMonitor.this.getTask(); - } - - public double getTotalWork() - { - return totalWork; - } - - public double getWork() - { - return work; - } - - public double getWorkPercent() - { - return percent(work, totalWork); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import org.eclipse.net4j.util.event.Event;
+import org.eclipse.net4j.util.event.IListener;
+import org.eclipse.net4j.util.event.INotifier;
+import org.eclipse.net4j.util.event.Notifier;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+public class NotifyingMonitor extends Monitor implements INotifier
+{
+ private Notifier notifier = new Notifier();
+
+ private String task;
+
+ public NotifyingMonitor()
+ {
+ }
+
+ public NotifyingMonitor(String task)
+ {
+ this.task = task;
+ }
+
+ public NotifyingMonitor(String task, IListener[] listeners)
+ {
+ this(task);
+ if (listeners != null)
+ {
+ for (IListener listener : listeners)
+ {
+ addListener(listener);
+ }
+ }
+ }
+
+ public String getTask()
+ {
+ return task;
+ }
+
+ public boolean hasListeners()
+ {
+ return notifier.hasListeners();
+ }
+
+ public IListener[] getListeners()
+ {
+ return notifier.getListeners();
+ }
+
+ public void addListener(IListener listener)
+ {
+ notifier.addListener(listener);
+ }
+
+ public void removeListener(IListener listener)
+ {
+ notifier.removeListener(listener);
+ }
+
+ @Override
+ public void worked(double work) throws MonitorCanceledException
+ {
+ super.worked(work);
+
+ IListener[] listeners = getListeners();
+ if (listeners != null)
+ {
+ notifier.fireEvent(new ProgressEvent(getTotalWork(), getWork()), listeners);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public final class ProgressEvent extends Event implements OMMonitorProgress
+ {
+ private static final long serialVersionUID = 1L;
+
+ private double totalWork;
+
+ private double work;
+
+ private ProgressEvent(double totalWork, double work)
+ {
+ super(NotifyingMonitor.this);
+ this.totalWork = totalWork;
+ this.work = work;
+ }
+
+ public String getTask()
+ {
+ return NotifyingMonitor.this.getTask();
+ }
+
+ public double getTotalWork()
+ {
+ return totalWork;
+ }
+
+ public double getWork()
+ {
+ return work;
+ }
+
+ public double getWorkPercent()
+ {
+ return percent(work, totalWork);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java index 793aa4f7a3..5888b5834a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java @@ -1,106 +1,106 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMMonitor extends OMMonitorProgress -{ - /** - * @since 2.0 - */ - public static final int THOUSAND = 1000; - - /** - * @since 2.0 - */ - public static final double DEFAULT_TIME_FACTOR = THOUSAND; - - /** - * @since 2.0 - */ - public boolean isCanceled(); - - /** - * @since 2.0 - */ - public void checkCanceled() throws MonitorCanceledException; - - /** - * @since 2.0 - */ - public boolean hasBegun() throws MonitorCanceledException; - - /** - * @since 2.0 - */ - public OMMonitor begin(double totalWork) throws MonitorCanceledException; - - /** - * Same as calling <code>begin(ONE)</code>. - * - * @since 2.0 - */ - public OMMonitor begin() throws MonitorCanceledException; - - /** - * @since 2.0 - */ - public void worked(double work) throws MonitorCanceledException; - - /** - * Same as calling <code>worked(ONE)</code>. - * - * @since 2.0 - */ - public void worked() throws MonitorCanceledException; - - /** - * @since 2.0 - */ - public OMMonitor fork(double work); - - /** - * Same as calling <code>fork(ONE)</code>. - * - * @since 2.0 - */ - public OMMonitor fork(); - - /** - * @since 2.0 - */ - public Async forkAsync(double work); - - /** - * Same as calling <code>forkAsync(ONE)</code>. - * - * @since 2.0 - */ - public Async forkAsync(); - - /** - * @since 2.0 - */ - public void done(); - - /** - * @author Eike Stepper - * @since 2.0 - */ - public interface Async - { - public void stop(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMMonitor extends OMMonitorProgress
+{
+ /**
+ * @since 2.0
+ */
+ public static final int THOUSAND = 1000;
+
+ /**
+ * @since 2.0
+ */
+ public static final double DEFAULT_TIME_FACTOR = THOUSAND;
+
+ /**
+ * @since 2.0
+ */
+ public boolean isCanceled();
+
+ /**
+ * @since 2.0
+ */
+ public void checkCanceled() throws MonitorCanceledException;
+
+ /**
+ * @since 2.0
+ */
+ public boolean hasBegun() throws MonitorCanceledException;
+
+ /**
+ * @since 2.0
+ */
+ public OMMonitor begin(double totalWork) throws MonitorCanceledException;
+
+ /**
+ * Same as calling <code>begin(ONE)</code>.
+ *
+ * @since 2.0
+ */
+ public OMMonitor begin() throws MonitorCanceledException;
+
+ /**
+ * @since 2.0
+ */
+ public void worked(double work) throws MonitorCanceledException;
+
+ /**
+ * Same as calling <code>worked(ONE)</code>.
+ *
+ * @since 2.0
+ */
+ public void worked() throws MonitorCanceledException;
+
+ /**
+ * @since 2.0
+ */
+ public OMMonitor fork(double work);
+
+ /**
+ * Same as calling <code>fork(ONE)</code>.
+ *
+ * @since 2.0
+ */
+ public OMMonitor fork();
+
+ /**
+ * @since 2.0
+ */
+ public Async forkAsync(double work);
+
+ /**
+ * Same as calling <code>forkAsync(ONE)</code>.
+ *
+ * @since 2.0
+ */
+ public Async forkAsync();
+
+ /**
+ * @since 2.0
+ */
+ public void done();
+
+ /**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+ public interface Async
+ {
+ public void stop();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java index b304d3eb5c..a40ff347de 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -/** - * @author Eike Stepper - * @since 3.1 - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMMonitorProgress -{ - public static final double ZERO = 0; - - public static final double ONE = 1; - - public static final double TEN = 10; - - public static final double HUNDRED = 100; - - public double getTotalWork(); - - public double getWork(); - - public double getWorkPercent(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+/**
+ * @author Eike Stepper
+ * @since 3.1
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMMonitorProgress
+{
+ public static final double ZERO = 0;
+
+ public static final double ONE = 1;
+
+ public static final double TEN = 10;
+
+ public static final double HUNDRED = 100;
+
+ public double getTotalWork();
+
+ public double getWork();
+
+ public double getWorkPercent();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java index 91cf03f519..63d4798f24 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java @@ -1,54 +1,54 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface ProgressDistributable<CONTEXT> -{ - public int getLoopCount(CONTEXT context); - - public double getLoopWork(CONTEXT context); - - public void runLoop(int index, CONTEXT context, OMMonitor monitor) throws Exception; - - /** - * @author Eike Stepper - */ - public static abstract class Default<CONTEXT> implements ProgressDistributable<CONTEXT> - { - private int loopCount = 1; - - private double loopWork = OMMonitor.ONE; - - public Default() - { - } - - public Default(int loopCount, double loopWork) - { - this.loopCount = loopCount; - this.loopWork = loopWork; - } - - public int getLoopCount(CONTEXT context) - { - return loopCount; - } - - public double getLoopWork(CONTEXT context) - { - return loopWork; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface ProgressDistributable<CONTEXT>
+{
+ public int getLoopCount(CONTEXT context);
+
+ public double getLoopWork(CONTEXT context);
+
+ public void runLoop(int index, CONTEXT context, OMMonitor monitor) throws Exception;
+
+ /**
+ * @author Eike Stepper
+ */
+ public static abstract class Default<CONTEXT> implements ProgressDistributable<CONTEXT>
+ {
+ private int loopCount = 1;
+
+ private double loopWork = OMMonitor.ONE;
+
+ public Default()
+ {
+ }
+
+ public Default(int loopCount, double loopWork)
+ {
+ this.loopCount = loopCount;
+ this.loopWork = loopWork;
+ }
+
+ public int getLoopCount(CONTEXT context)
+ {
+ return loopCount;
+ }
+
+ public double getLoopWork(CONTEXT context)
+ {
+ return loopWork;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java index 1368a07f7c..d7f3d1b7d3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java @@ -1,173 +1,173 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.CheckUtil; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.util.Arrays; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class ProgressDistributor -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_MONITOR, ProgressDistributor.class); - - private double[] distribution; - - public ProgressDistributor() - { - } - - public final <CONTEXT> void run(ProgressDistributable<CONTEXT>[] distributables, CONTEXT context, OMMonitor monitor) - throws RuntimeException, WrappedException - { - double[] distributionCopy; - synchronized (this) - { - if (distribution == null) - { - distribution = new double[distributables.length]; - Arrays.fill(distribution, OMMonitor.ONE); - } - else - { - CheckUtil.checkArg(distribution.length == distributables.length, "distributables.length"); //$NON-NLS-1$ - } - - distributionCopy = new double[distribution.length]; - System.arraycopy(distribution, 0, distributionCopy, 0, distribution.length); - } - - double total = OMMonitor.ZERO; - for (int i = 0; i < distributionCopy.length; i++) - { - total += distributionCopy[i]; - } - - if (TRACER.isEnabled()) - { - StringBuilder builder = new StringBuilder("Distribution: "); //$NON-NLS-1$ - for (int i = 0; i < distributionCopy.length; i++) - { - builder.append(distributionCopy[i] * OMMonitor.HUNDRED / total); - builder.append("%, "); //$NON-NLS-1$ - } - - builder.append("("); //$NON-NLS-1$ - builder.append(this); - builder.append(")"); //$NON-NLS-1$ - TRACER.trace(builder.toString()); - } - - monitor.begin(total); - - try - { - double[] times = new double[distributables.length]; - for (int i = 0; i < distributables.length; i++) - { - ProgressDistributable<CONTEXT> distributable = distributables[i]; - int count = distributable.getLoopCount(context); - double work = distributable.getLoopWork(context); - - OMMonitor distributableMonitor = monitor.fork(distributionCopy[i]); - distributableMonitor.begin(work * count); - - try - { - long start = System.currentTimeMillis(); - for (int loop = 0; loop < count; loop++) - { - try - { - distributable.runLoop(loop, context, distributableMonitor); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - times[i] = (double)(System.currentTimeMillis() - start) / count; - } - finally - { - distributableMonitor.done(); - } - } - - synchronized (this) - { - distribute(distribution, times); - } - } - finally - { - monitor.done(); - } - } - - protected abstract void distribute(double[] distribution, double[] times); - - public static <CONTEXT> ProgressDistributable<CONTEXT>[] array(ProgressDistributable<CONTEXT>... ops) - { - return ops; - } - - /** - * @author Eike Stepper - */ - public static class Arithmetic extends ProgressDistributor - { - private long count; - - private double[] times; - - public Arithmetic() - { - } - - @Override - protected void distribute(double[] distribution, double[] times) - { - ++count; - for (int i = 0; i < times.length; i++) - { - this.times[i] += times[i]; - distribution[i] = this.times[i] / count; - } - } - } - - /** - * @author Eike Stepper - */ - public static class Geometric extends ProgressDistributor - { - public Geometric() - { - } - - @Override - protected void distribute(double[] distribution, double[] times) - { - for (int i = 0; i < times.length; i++) - { - distribution[i] = (distribution[i] + times[i]) / 2; - } - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.CheckUtil;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.util.Arrays;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class ProgressDistributor
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_MONITOR, ProgressDistributor.class);
+
+ private double[] distribution;
+
+ public ProgressDistributor()
+ {
+ }
+
+ public final <CONTEXT> void run(ProgressDistributable<CONTEXT>[] distributables, CONTEXT context, OMMonitor monitor)
+ throws RuntimeException, WrappedException
+ {
+ double[] distributionCopy;
+ synchronized (this)
+ {
+ if (distribution == null)
+ {
+ distribution = new double[distributables.length];
+ Arrays.fill(distribution, OMMonitor.ONE);
+ }
+ else
+ {
+ CheckUtil.checkArg(distribution.length == distributables.length, "distributables.length"); //$NON-NLS-1$
+ }
+
+ distributionCopy = new double[distribution.length];
+ System.arraycopy(distribution, 0, distributionCopy, 0, distribution.length);
+ }
+
+ double total = OMMonitor.ZERO;
+ for (int i = 0; i < distributionCopy.length; i++)
+ {
+ total += distributionCopy[i];
+ }
+
+ if (TRACER.isEnabled())
+ {
+ StringBuilder builder = new StringBuilder("Distribution: "); //$NON-NLS-1$
+ for (int i = 0; i < distributionCopy.length; i++)
+ {
+ builder.append(distributionCopy[i] * OMMonitor.HUNDRED / total);
+ builder.append("%, "); //$NON-NLS-1$
+ }
+
+ builder.append("("); //$NON-NLS-1$
+ builder.append(this);
+ builder.append(")"); //$NON-NLS-1$
+ TRACER.trace(builder.toString());
+ }
+
+ monitor.begin(total);
+
+ try
+ {
+ double[] times = new double[distributables.length];
+ for (int i = 0; i < distributables.length; i++)
+ {
+ ProgressDistributable<CONTEXT> distributable = distributables[i];
+ int count = distributable.getLoopCount(context);
+ double work = distributable.getLoopWork(context);
+
+ OMMonitor distributableMonitor = monitor.fork(distributionCopy[i]);
+ distributableMonitor.begin(work * count);
+
+ try
+ {
+ long start = System.currentTimeMillis();
+ for (int loop = 0; loop < count; loop++)
+ {
+ try
+ {
+ distributable.runLoop(loop, context, distributableMonitor);
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+
+ times[i] = (double)(System.currentTimeMillis() - start) / count;
+ }
+ finally
+ {
+ distributableMonitor.done();
+ }
+ }
+
+ synchronized (this)
+ {
+ distribute(distribution, times);
+ }
+ }
+ finally
+ {
+ monitor.done();
+ }
+ }
+
+ protected abstract void distribute(double[] distribution, double[] times);
+
+ public static <CONTEXT> ProgressDistributable<CONTEXT>[] array(ProgressDistributable<CONTEXT>... ops)
+ {
+ return ops;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class Arithmetic extends ProgressDistributor
+ {
+ private long count;
+
+ private double[] times;
+
+ public Arithmetic()
+ {
+ }
+
+ @Override
+ protected void distribute(double[] distribution, double[] times)
+ {
+ ++count;
+ for (int i = 0; i < times.length; i++)
+ {
+ this.times[i] += times[i];
+ distribution[i] = this.times[i] / count;
+ }
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class Geometric extends ProgressDistributor
+ {
+ public Geometric()
+ {
+ }
+
+ @Override
+ protected void distribute(double[] distribution, double[] times)
+ {
+ for (int i = 0; i < times.length; i++)
+ {
+ distribution[i] = (distribution[i] + times[i]) / 2;
+ }
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java index 56a9d12a5a..57277c9d09 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java @@ -1,132 +1,132 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.monitor; - -import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; -import org.eclipse.net4j.util.concurrent.Timeouter; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class TimeoutMonitor extends Monitor -{ - private long timeout; - - private transient Timeouter timeouter; - - public TimeoutMonitor(long timeout) - { - this.timeout = timeout; - } - - public long getTimeout() - { - return timeout; - } - - public void setTimeout(long timeout) - { - this.timeout = timeout; - if (timeouter != null) - { - timeouter.setTimeout(timeout); - } - } - - public void touch() - { - if (timeouter != null) - { - timeouter.touch(); - } - } - - @Override - public OMMonitor begin(double totalWork) - { - timeouter = new Timeouter(getTimer(), timeout) - { - @Override - protected void handleTimeout(long untouched) - { - TimeoutMonitor.this.handleTimeout(untouched); - } - }; - - touch(); - super.begin(totalWork); - return this; - } - - @Override - public void worked(double work) - { - touch(); - super.worked(work); - } - - @Override - public OMMonitor fork(double work) - { - touch(); - return super.fork(work); - } - - @Override - public Async forkAsync(double work) - { - touch(); - return super.forkAsync(work); - } - - @Override - public void done() - { - cancelTimeouter(); - super.done(); - } - - @Override - public void cancel(RuntimeException cancelException) - { - cancelTimeouter(); - super.cancel(cancelException); - } - - @Override - public boolean isCanceled() - { - touch(); - return super.isCanceled(); - } - - @Override - public void checkCanceled() throws MonitorCanceledException - { - touch(); - super.checkCanceled(); - } - - protected void handleTimeout(long untouched) - { - cancel(new TimeoutRuntimeException("Timeout after " + untouched + " millis")); - } - - private void cancelTimeouter() - { - if (timeouter != null) - { - timeouter.dispose(); - timeouter = null; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.monitor;
+
+import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
+import org.eclipse.net4j.util.concurrent.Timeouter;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class TimeoutMonitor extends Monitor
+{
+ private long timeout;
+
+ private transient Timeouter timeouter;
+
+ public TimeoutMonitor(long timeout)
+ {
+ this.timeout = timeout;
+ }
+
+ public long getTimeout()
+ {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout)
+ {
+ this.timeout = timeout;
+ if (timeouter != null)
+ {
+ timeouter.setTimeout(timeout);
+ }
+ }
+
+ public void touch()
+ {
+ if (timeouter != null)
+ {
+ timeouter.touch();
+ }
+ }
+
+ @Override
+ public OMMonitor begin(double totalWork)
+ {
+ timeouter = new Timeouter(getTimer(), timeout)
+ {
+ @Override
+ protected void handleTimeout(long untouched)
+ {
+ TimeoutMonitor.this.handleTimeout(untouched);
+ }
+ };
+
+ touch();
+ super.begin(totalWork);
+ return this;
+ }
+
+ @Override
+ public void worked(double work)
+ {
+ touch();
+ super.worked(work);
+ }
+
+ @Override
+ public OMMonitor fork(double work)
+ {
+ touch();
+ return super.fork(work);
+ }
+
+ @Override
+ public Async forkAsync(double work)
+ {
+ touch();
+ return super.forkAsync(work);
+ }
+
+ @Override
+ public void done()
+ {
+ cancelTimeouter();
+ super.done();
+ }
+
+ @Override
+ public void cancel(RuntimeException cancelException)
+ {
+ cancelTimeouter();
+ super.cancel(cancelException);
+ }
+
+ @Override
+ public boolean isCanceled()
+ {
+ touch();
+ return super.isCanceled();
+ }
+
+ @Override
+ public void checkCanceled() throws MonitorCanceledException
+ {
+ touch();
+ super.checkCanceled();
+ }
+
+ protected void handleTimeout(long untouched)
+ {
+ cancel(new TimeoutRuntimeException("Timeout after " + untouched + " millis"));
+ }
+
+ private void cancelTimeouter()
+ {
+ if (timeouter != null)
+ {
+ timeouter.dispose();
+ timeouter = null;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java index 8a824c17b9..a6fe5056ad 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java index 869ce2e487..58e3fd298e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java index b8e1e4eb62..077df5dea0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java @@ -1,43 +1,43 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.pref; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMPreference<T> -{ - public OMPreferences getPreferences(); - - public String getName(); - - public Type getType(); - - public T getDefaultValue(); - - public T getValue(); - - public T setValue(T value); - - public T unSet(); - - public boolean isSet(); - - /** - * @author Eike Stepper - */ - public enum Type - { - BOOLEAN, INTEGER, LONG, FLOAT, DOUBLE, STRING, ARRAY, BYTES - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.pref;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMPreference<T>
+{
+ public OMPreferences getPreferences();
+
+ public String getName();
+
+ public Type getType();
+
+ public T getDefaultValue();
+
+ public T getValue();
+
+ public T setValue(T value);
+
+ public T unSet();
+
+ public boolean isSet();
+
+ /**
+ * @author Eike Stepper
+ */
+ public enum Type
+ {
+ BOOLEAN, INTEGER, LONG, FLOAT, DOUBLE, STRING, ARRAY, BYTES
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java index 70f9e1998a..b0aa754c51 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java @@ -1,96 +1,96 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.pref; - -import org.eclipse.net4j.util.event.INotifier; -import org.eclipse.net4j.util.om.OMBundle; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMPreferences extends INotifier -{ - public static final boolean DEFAULT_BOOLEAN = false; - - public static final int DEFAULT_INTEGER = 0; - - public static final long DEFAULT_LONG = 0L; - - public static final float DEFAULT_FLOAT = 0.0f; - - public static final double DEFAULT_DOUBLE = 0.0d; - - public static final String DEFAULT_STRING = ""; //$NON-NLS-1$ - - public static final String[] DEFAULT_ARRAY = {}; - - public static final byte[] DEFAULT_BYTES = {}; - - public OMBundle getBundle(); - - public boolean isDirty(); - - public void save(); - - public OMPreference<Boolean> init(String name, boolean defaultValue); - - public OMPreference<Integer> init(String name, int defaultValue); - - public OMPreference<Long> init(String name, long defaultValue); - - public OMPreference<Float> init(String name, float defaultValue); - - public OMPreference<Double> init(String name, double defaultValue); - - public OMPreference<String> init(String name, String defaultValue); - - public OMPreference<String[]> init(String name, String[] defaultValue); - - public OMPreference<byte[]> init(String name, byte[] defaultValue); - - public OMPreference<Boolean> initBoolean(String name); - - public OMPreference<Integer> initInteger(String name); - - public OMPreference<Long> initLong(String name); - - public OMPreference<Float> initFloat(String name); - - public OMPreference<Double> initDouble(String name); - - public OMPreference<String> initString(String name); - - public OMPreference<String[]> initArray(String name); - - public OMPreference<byte[]> initBytes(String name); - - public boolean contains(String name); - - public OMPreference<?> get(String name); - - public OMPreference<Boolean> getBoolean(String name); - - public OMPreference<Integer> getInteger(String name); - - public OMPreference<Long> getLong(String name); - - public OMPreference<Float> getFloat(String name); - - public OMPreference<Double> getDouble(String name); - - public OMPreference<String> getString(String name); - - public OMPreference<String[]> getArray(String name); - - public OMPreference<byte[]> getBytes(String name); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.pref;
+
+import org.eclipse.net4j.util.event.INotifier;
+import org.eclipse.net4j.util.om.OMBundle;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMPreferences extends INotifier
+{
+ public static final boolean DEFAULT_BOOLEAN = false;
+
+ public static final int DEFAULT_INTEGER = 0;
+
+ public static final long DEFAULT_LONG = 0L;
+
+ public static final float DEFAULT_FLOAT = 0.0f;
+
+ public static final double DEFAULT_DOUBLE = 0.0d;
+
+ public static final String DEFAULT_STRING = ""; //$NON-NLS-1$
+
+ public static final String[] DEFAULT_ARRAY = {};
+
+ public static final byte[] DEFAULT_BYTES = {};
+
+ public OMBundle getBundle();
+
+ public boolean isDirty();
+
+ public void save();
+
+ public OMPreference<Boolean> init(String name, boolean defaultValue);
+
+ public OMPreference<Integer> init(String name, int defaultValue);
+
+ public OMPreference<Long> init(String name, long defaultValue);
+
+ public OMPreference<Float> init(String name, float defaultValue);
+
+ public OMPreference<Double> init(String name, double defaultValue);
+
+ public OMPreference<String> init(String name, String defaultValue);
+
+ public OMPreference<String[]> init(String name, String[] defaultValue);
+
+ public OMPreference<byte[]> init(String name, byte[] defaultValue);
+
+ public OMPreference<Boolean> initBoolean(String name);
+
+ public OMPreference<Integer> initInteger(String name);
+
+ public OMPreference<Long> initLong(String name);
+
+ public OMPreference<Float> initFloat(String name);
+
+ public OMPreference<Double> initDouble(String name);
+
+ public OMPreference<String> initString(String name);
+
+ public OMPreference<String[]> initArray(String name);
+
+ public OMPreference<byte[]> initBytes(String name);
+
+ public boolean contains(String name);
+
+ public OMPreference<?> get(String name);
+
+ public OMPreference<Boolean> getBoolean(String name);
+
+ public OMPreference<Integer> getInteger(String name);
+
+ public OMPreference<Long> getLong(String name);
+
+ public OMPreference<Float> getFloat(String name);
+
+ public OMPreference<Double> getDouble(String name);
+
+ public OMPreference<String> getString(String name);
+
+ public OMPreference<String[]> getArray(String name);
+
+ public OMPreference<byte[]> getBytes(String name);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java index 11f829e12e..d603f914fa 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java @@ -1,35 +1,35 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.pref; - -import org.eclipse.net4j.util.event.IEvent; - -/** - * An {@link IEvent event} fired from a {@link OMPreferences preferences} object when a {@link OMPreference preference} - * value has changed. - * - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMPreferencesChangeEvent<T> extends IEvent -{ - /** - * @since 3.0 - */ - public OMPreferences getSource(); - - public OMPreference<T> getPreference(); - - public T getOldValue(); - - public T getNewValue(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.pref;
+
+import org.eclipse.net4j.util.event.IEvent;
+
+/**
+ * An {@link IEvent event} fired from a {@link OMPreferences preferences} object when a {@link OMPreference preference}
+ * value has changed.
+ *
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMPreferencesChangeEvent<T> extends IEvent
+{
+ /**
+ * @since 3.0
+ */
+ public OMPreferences getSource();
+
+ public OMPreference<T> getPreference();
+
+ public T getOldValue();
+
+ public T getNewValue();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java index e2ba05a742..f2acb81b95 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/ContextTracer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/ContextTracer.java index 23e789e058..e64f654d0e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/ContextTracer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/ContextTracer.java @@ -1,89 +1,89 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import org.eclipse.net4j.util.om.OMBundle; - -/** - * @author Eike Stepper - */ -public class ContextTracer -{ - private OMTracer delegate; - - private Class<?> context; - - public ContextTracer(OMTracer delegate, Class<?> context) - { - this.delegate = delegate; - this.context = context; - } - - public OMBundle getBundle() - { - return delegate.getBundle(); - } - - public String getFullName() - { - return delegate.getFullName(); - } - - public String getName() - { - return delegate.getName(); - } - - public OMTracer getDelegate() - { - return delegate; - } - - public OMTracer getParent() - { - return delegate.getParent(); - } - - public boolean isEnabled() - { - return delegate.isEnabled(); - } - - public void setEnabled(boolean enabled) - { - delegate.setEnabled(enabled); - } - - public void format(String pattern, Object... args) - { - delegate.format(context, pattern, args); - } - - public void format(String pattern, Throwable t, Object... args) - { - delegate.format(context, pattern, t, args); - } - - public void trace(String msg, Throwable t) - { - delegate.trace(context, msg, t); - } - - public void trace(String msg) - { - delegate.trace(context, msg); - } - - public void trace(Throwable t) - { - delegate.trace(context, t); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import org.eclipse.net4j.util.om.OMBundle;
+
+/**
+ * @author Eike Stepper
+ */
+public class ContextTracer
+{
+ private OMTracer delegate;
+
+ private Class<?> context;
+
+ public ContextTracer(OMTracer delegate, Class<?> context)
+ {
+ this.delegate = delegate;
+ this.context = context;
+ }
+
+ public OMBundle getBundle()
+ {
+ return delegate.getBundle();
+ }
+
+ public String getFullName()
+ {
+ return delegate.getFullName();
+ }
+
+ public String getName()
+ {
+ return delegate.getName();
+ }
+
+ public OMTracer getDelegate()
+ {
+ return delegate;
+ }
+
+ public OMTracer getParent()
+ {
+ return delegate.getParent();
+ }
+
+ public boolean isEnabled()
+ {
+ return delegate.isEnabled();
+ }
+
+ public void setEnabled(boolean enabled)
+ {
+ delegate.setEnabled(enabled);
+ }
+
+ public void format(String pattern, Object... args)
+ {
+ delegate.format(context, pattern, args);
+ }
+
+ public void format(String pattern, Throwable t, Object... args)
+ {
+ delegate.format(context, pattern, t, args);
+ }
+
+ public void trace(String msg, Throwable t)
+ {
+ delegate.trace(context, msg, t);
+ }
+
+ public void trace(String msg)
+ {
+ delegate.trace(context, msg);
+ }
+
+ public void trace(Throwable t)
+ {
+ delegate.trace(context, t);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandler.java index 79b430ff86..0ca72ab987 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandler.java @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -/** - * @author Eike Stepper - */ -public interface OMTraceHandler -{ - public void traced(OMTraceHandlerEvent event); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+/**
+ * @author Eike Stepper
+ */
+public interface OMTraceHandler
+{
+ public void traced(OMTraceHandlerEvent event);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandlerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandlerEvent.java index ee650e7040..c3c5299b36 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandlerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTraceHandlerEvent.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMTraceHandlerEvent -{ - public long getTimeStamp(); - - public OMTracer getTracer(); - - public Class<?> getContext(); - - public String getMessage(); - - public Throwable getThrowable(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMTraceHandlerEvent
+{
+ public long getTimeStamp();
+
+ public OMTracer getTracer();
+
+ public Class<?> getContext();
+
+ public String getMessage();
+
+ public Throwable getThrowable();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTracer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTracer.java index 9672287578..a27fa97458 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTracer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/OMTracer.java @@ -1,47 +1,47 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import org.eclipse.net4j.util.om.OMBundle; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface OMTracer -{ - public OMBundle getBundle(); - - public OMTracer getParent(); - - public String getName(); - - public String getFullName(); - - public boolean isEnabled(); - - public void setEnabled(boolean enabled); - - public void trace(OMTraceHandlerEvent traceRecord); - - public OMTraceHandlerEvent format(Class<?> context, String pattern, Object... args); - - public OMTraceHandlerEvent format(Class<?> context, String pattern, Throwable t, Object... args); - - public OMTraceHandlerEvent trace(Class<?> context, String msg, Throwable t); - - public OMTraceHandlerEvent trace(Class<?> context, String msg); - - public OMTraceHandlerEvent trace(Class<?> context, Throwable t); - - public OMTracer tracer(String name); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import org.eclipse.net4j.util.om.OMBundle;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface OMTracer
+{
+ public OMBundle getBundle();
+
+ public OMTracer getParent();
+
+ public String getName();
+
+ public String getFullName();
+
+ public boolean isEnabled();
+
+ public void setEnabled(boolean enabled);
+
+ public void trace(OMTraceHandlerEvent traceRecord);
+
+ public OMTraceHandlerEvent format(Class<?> context, String pattern, Object... args);
+
+ public OMTraceHandlerEvent format(Class<?> context, String pattern, Throwable t, Object... args);
+
+ public OMTraceHandlerEvent trace(Class<?> context, String msg, Throwable t);
+
+ public OMTraceHandlerEvent trace(Class<?> context, String msg);
+
+ public OMTraceHandlerEvent trace(Class<?> context, Throwable t);
+
+ public OMTracer tracer(String name);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PerfTracer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PerfTracer.java index 6485019232..564b948dc0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PerfTracer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PerfTracer.java @@ -1,81 +1,81 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import java.util.IdentityHashMap; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public class PerfTracer extends ContextTracer -{ - public static final long NOT_STARTED = 0L; - - private Map<Object, Long> timers = new IdentityHashMap<Object, Long>(); - - public PerfTracer(OMTracer delegate, Class<?> context) - { - super(delegate, context); - } - - public void start(Object object) - { - if (isEnabled()) - { - synchronized (timers) - { - timers.put(object, System.currentTimeMillis()); - } - } - } - - public long stop(Object object) - { - long duration = NOT_STARTED; - if (isEnabled()) - { - Long timer; - synchronized (timers) - { - timer = timers.remove(object); - } - - if (timer != null) - { - duration = System.currentTimeMillis() - timer; - format("{0} = {1} millis", object, duration); //$NON-NLS-1$ - } - } - - return duration; - } - - public long getDuration(Object object) - { - long duration = NOT_STARTED; - if (isEnabled()) - { - Long timer; - synchronized (timers) - { - timer = timers.get(object); - } - - if (timer != null) - { - duration = System.currentTimeMillis() - timer; - } - } - - return duration; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import java.util.IdentityHashMap;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public class PerfTracer extends ContextTracer
+{
+ public static final long NOT_STARTED = 0L;
+
+ private Map<Object, Long> timers = new IdentityHashMap<Object, Long>();
+
+ public PerfTracer(OMTracer delegate, Class<?> context)
+ {
+ super(delegate, context);
+ }
+
+ public void start(Object object)
+ {
+ if (isEnabled())
+ {
+ synchronized (timers)
+ {
+ timers.put(object, System.currentTimeMillis());
+ }
+ }
+ }
+
+ public long stop(Object object)
+ {
+ long duration = NOT_STARTED;
+ if (isEnabled())
+ {
+ Long timer;
+ synchronized (timers)
+ {
+ timer = timers.remove(object);
+ }
+
+ if (timer != null)
+ {
+ duration = System.currentTimeMillis() - timer;
+ format("{0} = {1} millis", object, duration); //$NON-NLS-1$
+ }
+ }
+
+ return duration;
+ }
+
+ public long getDuration(Object object)
+ {
+ long duration = NOT_STARTED;
+ if (isEnabled())
+ {
+ Long timer;
+ synchronized (timers)
+ {
+ timer = timers.get(object);
+ }
+
+ if (timer != null)
+ {
+ duration = System.currentTimeMillis() - timer;
+ }
+ }
+
+ return duration;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PrintTraceHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PrintTraceHandler.java index c3858c0d70..d0fd8b3a62 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PrintTraceHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/PrintTraceHandler.java @@ -1,132 +1,132 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import org.eclipse.net4j.util.io.IOUtil; - -import java.io.PrintStream; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class PrintTraceHandler implements OMTraceHandler -{ - public static final PrintTraceHandler CONSOLE = new PrintTraceHandler(); - - private PrintStream stream; - - private String pattern; - - private boolean shortContext; - - public PrintTraceHandler(PrintStream stream) - { - this.stream = stream; - } - - protected PrintTraceHandler() - { - this(IOUtil.OUT()); - } - - public String getPattern() - { - return pattern; - } - - /** - * Pattern arguments: - * <p> - * <ul> - * <li>0} --> String <b>tracerName</b><br> - * <li>1} --> String <b>tracerShort</b><br> - * <li>2} --> String <b>contextName</b><br> - * <li>3} --> String <b>contextShort</b><br> - * <li>4} --> long <b>timeStamp</b><br> - * <li>5} --> String <b>message</b><br> - * <li>6} --> String <b>threadName</b><br> - * <li>7} --> long <b>threadID</b><br> - * <li>8} --> int <b>threadPriority</b><br> - * <li>9} --> Thread.State <b>threadState</b><br> - * </ul> - */ - public void setPattern(String pattern) - { - this.pattern = pattern; - } - - public boolean isShortContext() - { - return shortContext; - } - - public void setShortContext(boolean shortContext) - { - this.shortContext = shortContext; - } - - public void traced(OMTraceHandlerEvent event) - { - String line = pattern == null ? format(shortContext, event) : format(pattern, event); - stream.println(line); - if (event.getThrowable() != null) - { - IOUtil.print(event.getThrowable(), stream); - } - } - - public static String format(boolean shortContext, OMTraceHandlerEvent event) - { - Class<?> context = event.getContext(); - String contextName = shortContext ? context.getSimpleName() : context.getName(); - return Thread.currentThread().getName() + " [" + contextName + "] " + event.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$ - } - - /** - * Pattern arguments: - * <p> - * <ul> - * <li>0} --> String <b>tracerName</b><br> - * <li>1} --> String <b>tracerShort</b><br> - * <li>2} --> String <b>contextName</b><br> - * <li>3} --> String <b>contextShort</b><br> - * <li>4} --> long <b>timeStamp</b><br> - * <li>5} --> String <b>message</b><br> - * <li>6} --> String <b>threadName</b><br> - * <li>7} --> long <b>threadID</b><br> - * <li>8} --> int <b>threadPriority</b><br> - * <li>9} --> Thread.State <b>threadState</b><br> - * </ul> - */ - public static String format(String pattern, OMTraceHandlerEvent event) - { - final OMTracer tracer = event.getTracer(); - final String tracerName = tracer.getFullName(); - final String tracerShort = tracer.getName(); - - final Class<?> context = event.getContext(); - final String contextName = context.getName(); - final String contextShort = context.getName(); - - final long timeStamp = event.getTimeStamp(); - final String message = event.getMessage(); - - final Thread thread = Thread.currentThread(); - final String threadName = thread.getName(); - final long threadID = thread.getId(); - final int threadPriority = thread.getPriority(); - final Thread.State threadState = thread.getState(); - - return MessageFormat.format(pattern, tracerName, tracerShort, contextName, contextShort, timeStamp, message, - threadName, threadID, threadPriority, threadState); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import org.eclipse.net4j.util.io.IOUtil;
+
+import java.io.PrintStream;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class PrintTraceHandler implements OMTraceHandler
+{
+ public static final PrintTraceHandler CONSOLE = new PrintTraceHandler();
+
+ private PrintStream stream;
+
+ private String pattern;
+
+ private boolean shortContext;
+
+ public PrintTraceHandler(PrintStream stream)
+ {
+ this.stream = stream;
+ }
+
+ protected PrintTraceHandler()
+ {
+ this(IOUtil.OUT());
+ }
+
+ public String getPattern()
+ {
+ return pattern;
+ }
+
+ /**
+ * Pattern arguments:
+ * <p>
+ * <ul>
+ * <li>0} --> String <b>tracerName</b><br>
+ * <li>1} --> String <b>tracerShort</b><br>
+ * <li>2} --> String <b>contextName</b><br>
+ * <li>3} --> String <b>contextShort</b><br>
+ * <li>4} --> long <b>timeStamp</b><br>
+ * <li>5} --> String <b>message</b><br>
+ * <li>6} --> String <b>threadName</b><br>
+ * <li>7} --> long <b>threadID</b><br>
+ * <li>8} --> int <b>threadPriority</b><br>
+ * <li>9} --> Thread.State <b>threadState</b><br>
+ * </ul>
+ */
+ public void setPattern(String pattern)
+ {
+ this.pattern = pattern;
+ }
+
+ public boolean isShortContext()
+ {
+ return shortContext;
+ }
+
+ public void setShortContext(boolean shortContext)
+ {
+ this.shortContext = shortContext;
+ }
+
+ public void traced(OMTraceHandlerEvent event)
+ {
+ String line = pattern == null ? format(shortContext, event) : format(pattern, event);
+ stream.println(line);
+ if (event.getThrowable() != null)
+ {
+ IOUtil.print(event.getThrowable(), stream);
+ }
+ }
+
+ public static String format(boolean shortContext, OMTraceHandlerEvent event)
+ {
+ Class<?> context = event.getContext();
+ String contextName = shortContext ? context.getSimpleName() : context.getName();
+ return Thread.currentThread().getName() + " [" + contextName + "] " + event.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ /**
+ * Pattern arguments:
+ * <p>
+ * <ul>
+ * <li>0} --> String <b>tracerName</b><br>
+ * <li>1} --> String <b>tracerShort</b><br>
+ * <li>2} --> String <b>contextName</b><br>
+ * <li>3} --> String <b>contextShort</b><br>
+ * <li>4} --> long <b>timeStamp</b><br>
+ * <li>5} --> String <b>message</b><br>
+ * <li>6} --> String <b>threadName</b><br>
+ * <li>7} --> long <b>threadID</b><br>
+ * <li>8} --> int <b>threadPriority</b><br>
+ * <li>9} --> Thread.State <b>threadState</b><br>
+ * </ul>
+ */
+ public static String format(String pattern, OMTraceHandlerEvent event)
+ {
+ final OMTracer tracer = event.getTracer();
+ final String tracerName = tracer.getFullName();
+ final String tracerShort = tracer.getName();
+
+ final Class<?> context = event.getContext();
+ final String contextName = context.getName();
+ final String contextShort = context.getName();
+
+ final long timeStamp = event.getTimeStamp();
+ final String message = event.getMessage();
+
+ final Thread thread = Thread.currentThread();
+ final String threadName = thread.getName();
+ final long threadID = thread.getId();
+ final int threadPriority = thread.getPriority();
+ final Thread.State threadState = thread.getState();
+
+ return MessageFormat.format(pattern, tracerName, tracerShort, contextName, contextShort, timeStamp, message,
+ threadName, threadID, threadPriority, threadState);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceHandler.java index 4750a32c60..b44cfc81e8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceHandler.java @@ -1,147 +1,147 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.io.IOUtil; - -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.Socket; -import java.util.UUID; - -/** - * @author Eike Stepper - */ -public class RemoteTraceHandler implements OMTraceHandler -{ - public static final String DEFAULT_HOST = "localhost"; //$NON-NLS-1$ - - public static final int DEFAULT_PORT = RemoteTraceServer.DEFAULT_PORT; - - private static int uniqueCounter; - - private String agentID; - - private String host; - - private int port; - - private Socket socket; - - public RemoteTraceHandler() throws IOException - { - this(uniqueAgentID()); - } - - public RemoteTraceHandler(String agentID) throws IOException - { - this(agentID, DEFAULT_HOST); - } - - public RemoteTraceHandler(String agentID, String host) throws IOException - { - this(agentID, host, DEFAULT_PORT); - } - - public RemoteTraceHandler(String agentID, String host, int port) throws IOException - { - this.agentID = agentID; - this.host = host; - this.port = port; - socket = connect(); - } - - public Exception close() - { - try - { - socket.close(); - return null; - } - catch (IOException ex) - { - OM.LOG.error(ex); - return ex; - } - } - - public void traced(OMTraceHandlerEvent event) - { - try - { - OutputStream outputStream = socket.getOutputStream(); - DataOutputStream out = new DataOutputStream(outputStream); - - out.writeLong(event.getTimeStamp()); - writeUTF(out, agentID); - writeUTF(out, event.getTracer().getBundle().getBundleID()); - writeUTF(out, event.getTracer().getFullName()); - writeUTF(out, event.getContext() == null ? "" : event.getContext().getName()); //$NON-NLS-1$ - writeUTF(out, event.getMessage()); - if (event.getThrowable() == null) - { - out.writeBoolean(false); - } - else - { - out.writeBoolean(true); - String message = event.getThrowable().getMessage(); - writeUTF(out, message); - - StackTraceElement[] stackTrace = event.getThrowable().getStackTrace(); - int size = stackTrace == null ? 0 : stackTrace.length; - out.writeInt(size); - - for (int i = 0; i < size; i++) - { - StackTraceElement element = stackTrace[i]; - writeUTF(out, element.getClassName()); - writeUTF(out, element.getMethodName()); - writeUTF(out, element.getFileName()); - out.writeInt(element.getLineNumber()); - } - } - - out.flush(); - } - catch (IOException ex) - { - IOUtil.print(ex); - } - } - - protected Socket connect() throws IOException - { - return new Socket(host, port); - } - - protected void writeUTF(DataOutputStream out, String str) throws IOException - { - out.writeUTF(str == null ? "" : str); //$NON-NLS-1$ - } - - public static String uniqueAgentID() - { - try - { - InetAddress localMachine = InetAddress.getLocalHost(); - return localMachine.getHostName() + "#" + ++uniqueCounter; //$NON-NLS-1$ - } - catch (Exception ex) - { - UUID uuid = UUID.randomUUID(); - return uuid.toString(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.io.IOUtil;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.util.UUID;
+
+/**
+ * @author Eike Stepper
+ */
+public class RemoteTraceHandler implements OMTraceHandler
+{
+ public static final String DEFAULT_HOST = "localhost"; //$NON-NLS-1$
+
+ public static final int DEFAULT_PORT = RemoteTraceServer.DEFAULT_PORT;
+
+ private static int uniqueCounter;
+
+ private String agentID;
+
+ private String host;
+
+ private int port;
+
+ private Socket socket;
+
+ public RemoteTraceHandler() throws IOException
+ {
+ this(uniqueAgentID());
+ }
+
+ public RemoteTraceHandler(String agentID) throws IOException
+ {
+ this(agentID, DEFAULT_HOST);
+ }
+
+ public RemoteTraceHandler(String agentID, String host) throws IOException
+ {
+ this(agentID, host, DEFAULT_PORT);
+ }
+
+ public RemoteTraceHandler(String agentID, String host, int port) throws IOException
+ {
+ this.agentID = agentID;
+ this.host = host;
+ this.port = port;
+ socket = connect();
+ }
+
+ public Exception close()
+ {
+ try
+ {
+ socket.close();
+ return null;
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error(ex);
+ return ex;
+ }
+ }
+
+ public void traced(OMTraceHandlerEvent event)
+ {
+ try
+ {
+ OutputStream outputStream = socket.getOutputStream();
+ DataOutputStream out = new DataOutputStream(outputStream);
+
+ out.writeLong(event.getTimeStamp());
+ writeUTF(out, agentID);
+ writeUTF(out, event.getTracer().getBundle().getBundleID());
+ writeUTF(out, event.getTracer().getFullName());
+ writeUTF(out, event.getContext() == null ? "" : event.getContext().getName()); //$NON-NLS-1$
+ writeUTF(out, event.getMessage());
+ if (event.getThrowable() == null)
+ {
+ out.writeBoolean(false);
+ }
+ else
+ {
+ out.writeBoolean(true);
+ String message = event.getThrowable().getMessage();
+ writeUTF(out, message);
+
+ StackTraceElement[] stackTrace = event.getThrowable().getStackTrace();
+ int size = stackTrace == null ? 0 : stackTrace.length;
+ out.writeInt(size);
+
+ for (int i = 0; i < size; i++)
+ {
+ StackTraceElement element = stackTrace[i];
+ writeUTF(out, element.getClassName());
+ writeUTF(out, element.getMethodName());
+ writeUTF(out, element.getFileName());
+ out.writeInt(element.getLineNumber());
+ }
+ }
+
+ out.flush();
+ }
+ catch (IOException ex)
+ {
+ IOUtil.print(ex);
+ }
+ }
+
+ protected Socket connect() throws IOException
+ {
+ return new Socket(host, port);
+ }
+
+ protected void writeUTF(DataOutputStream out, String str) throws IOException
+ {
+ out.writeUTF(str == null ? "" : str); //$NON-NLS-1$
+ }
+
+ public static String uniqueAgentID()
+ {
+ try
+ {
+ InetAddress localMachine = InetAddress.getLocalHost();
+ return localMachine.getHostName() + "#" + ++uniqueCounter; //$NON-NLS-1$
+ }
+ catch (Exception ex)
+ {
+ UUID uuid = UUID.randomUUID();
+ return uuid.toString();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceServer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceServer.java index de312e6057..771b444989 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceServer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/RemoteTraceServer.java @@ -1,399 +1,399 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.io.IOUtil; - -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintStream; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Date; -import java.util.EventObject; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -/** - * @author Eike Stepper - */ -public class RemoteTraceServer -{ - public static final String DEFAULT_ADDRESS = "0.0.0.0"; //$NON-NLS-1$ - - public static final int DEFAULT_PORT = 2035; - - public static final int ANY_PORT = 0; - - private static long lastEventID; - - private int port; - - private String address; - - private ServerSocket serverSocket; - - private Queue<Listener> listeners = new ConcurrentLinkedQueue<Listener>(); - - public RemoteTraceServer() throws IOException - { - this(DEFAULT_PORT); - } - - public RemoteTraceServer(int port) throws IOException - { - this(port, DEFAULT_ADDRESS); - } - - public RemoteTraceServer(int port, String address) throws IOException - { - this.port = port; - this.address = address; - serverSocket = bind(); - start(); - } - - /** - * @since 3.0 - */ - public void start() - { - new Thread("RemoteTraceServer") //$NON-NLS-1$ - { - @Override - public void run() - { - handleConnections(); - } - }.start(); - } - - public void addListener(Listener listener) - { - if (!listeners.contains(listener)) - { - listeners.add(listener); - } - } - - public void removeListener(Listener listener) - { - listeners.remove(listener); - } - - public Exception close() - { - try - { - serverSocket.close(); - return null; - } - catch (IOException ex) - { - OM.LOG.error(ex); - return ex; - } - } - - protected ServerSocket bind() throws IOException - { - InetAddress addr = InetAddress.getByName(address); - return new ServerSocket(port, 5, addr); - } - - protected void handleConnections() - { - for (;;) - { - try - { - final Socket socket = serverSocket.accept(); - new Thread() - { - @Override - public void run() - { - handleSession(socket); - } - }.start(); - } - catch (IOException ex) - { - if (!serverSocket.isClosed()) - { - IOUtil.print(ex); - } - - break; - } - } - } - - protected void handleSession(Socket socket) - { - try - { - InputStream inputStream = socket.getInputStream(); - DataInputStream in = new DataInputStream(inputStream); - - for (;;) - { - handleTrace(in); - } - } - catch (IOException ex) - { - IOUtil.print(ex); - } - } - - protected void handleTrace(DataInputStream in) throws IOException - { - Event event = new Event(); - event.timeStamp = in.readLong(); - event.agentID = in.readUTF(); - event.bundleID = in.readUTF(); - event.tracerName = in.readUTF(); - event.context = in.readUTF(); - event.message = in.readUTF(); - if (in.readBoolean()) - { - event.throwable = in.readUTF(); - int size = in.readInt(); - event.stackTrace = new StackTraceElement[size]; - for (int i = 0; i < size; i++) - { - String className = in.readUTF(); - String methodName = in.readUTF(); - String fileName = in.readUTF(); - int lineNumber = in.readInt(); - event.stackTrace[i] = new StackTraceElement(className, methodName, fileName, lineNumber); - } - } - - fireEvent(event); - } - - protected void fireEvent(Event event) - { - for (Listener listener : listeners) - { - try - { - listener.notifyRemoteTrace(event); - } - catch (RuntimeException ex) - { - IOUtil.print(ex); - } - } - } - - /** - * @author Eike Stepper - */ - public class Event extends EventObject - { - private static final long serialVersionUID = 1L; - - private long id; - - long timeStamp; - - String agentID; - - String bundleID; - - String tracerName; - - String context; - - String message; - - String throwable; - - StackTraceElement[] stackTrace; - - Event() - { - super(RemoteTraceServer.this); - id = ++lastEventID; - } - - public RemoteTraceServer getRemoteTraceServer() - { - return (RemoteTraceServer)source; - } - - public long getID() - { - return id; - } - - public long getTimeStamp() - { - return timeStamp; - } - - public String getAgentID() - { - return agentID; - } - - public String getBundleID() - { - return bundleID; - } - - public String getContext() - { - return context; - } - - public String getMessage() - { - return message; - } - - public StackTraceElement[] getStackTrace() - { - return stackTrace; - } - - public String getThrowable() - { - return throwable; - } - - public String getTracerName() - { - return tracerName; - } - - @Override - public String toString() - { - StringBuilder builder = new StringBuilder(); - builder.append("TraceEvent[agentID="); //$NON-NLS-1$ - builder.append(agentID); - - builder.append(", bundleID="); //$NON-NLS-1$ - builder.append(bundleID); - - builder.append(", tracerName="); //$NON-NLS-1$ - builder.append(tracerName); - - builder.append(", context="); //$NON-NLS-1$ - builder.append(context); - - builder.append(", message="); //$NON-NLS-1$ - builder.append(message); - - builder.append(", throwable="); //$NON-NLS-1$ - builder.append(throwable); - - builder.append(", stackTrace="); //$NON-NLS-1$ - builder.append(stackTrace); - - builder.append("]"); //$NON-NLS-1$ - return builder.toString(); - } - - public String getText(int index) - { - switch (index) - { - case 0: - return Long.toString(id); - case 1: - return new Date(timeStamp).toString(); - case 2: - return agentID; - case 3: - return bundleID; - case 4: - return tracerName; - case 5: - return context; - case 6: - return message; - case 7: - return throwable; - } - - throw new IllegalArgumentException("Invalid index: " + index); //$NON-NLS-1$ - } - - public boolean hasError() - { - return throwable != null && throwable.length() != 0 // - || stackTrace != null && stackTrace.length != 0; - } - } - - /** - * @author Eike Stepper - */ - public interface Listener - { - public void notifyRemoteTrace(Event event); - } - - public static class PrintListener implements Listener - { - public static final PrintListener CONSOLE = new PrintListener(); - - private PrintStream stream; - - public PrintListener(PrintStream stream) - { - this.stream = stream; - } - - protected PrintListener() - { - this(IOUtil.OUT()); - } - - public void notifyRemoteTrace(Event event) - { - stream.println("[TRACE] " + event.getAgentID()); //$NON-NLS-1$ - stream.println(event.getBundleID()); - stream.println(event.getTracerName()); - stream.println(event.getContext()); - stream.println(event.getMessage()); - - String throwable = event.getThrowable(); - if (throwable != null && throwable.length() != 0) - { - stream.println(throwable); - } - - StackTraceElement[] stackTrace = event.getStackTrace(); - if (stackTrace != null) - { - for (StackTraceElement element : stackTrace) - { - stream.print(element.getClassName()); - stream.print("." + element.getMethodName()); //$NON-NLS-1$ - stream.print("(" + element.getFileName()); //$NON-NLS-1$ - stream.print(":" + element.getLineNumber()); //$NON-NLS-1$ - stream.println(")"); //$NON-NLS-1$ - } - } - - stream.println(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.io.IOUtil;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Date;
+import java.util.EventObject;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+/**
+ * @author Eike Stepper
+ */
+public class RemoteTraceServer
+{
+ public static final String DEFAULT_ADDRESS = "0.0.0.0"; //$NON-NLS-1$
+
+ public static final int DEFAULT_PORT = 2035;
+
+ public static final int ANY_PORT = 0;
+
+ private static long lastEventID;
+
+ private int port;
+
+ private String address;
+
+ private ServerSocket serverSocket;
+
+ private Queue<Listener> listeners = new ConcurrentLinkedQueue<Listener>();
+
+ public RemoteTraceServer() throws IOException
+ {
+ this(DEFAULT_PORT);
+ }
+
+ public RemoteTraceServer(int port) throws IOException
+ {
+ this(port, DEFAULT_ADDRESS);
+ }
+
+ public RemoteTraceServer(int port, String address) throws IOException
+ {
+ this.port = port;
+ this.address = address;
+ serverSocket = bind();
+ start();
+ }
+
+ /**
+ * @since 3.0
+ */
+ public void start()
+ {
+ new Thread("RemoteTraceServer") //$NON-NLS-1$
+ {
+ @Override
+ public void run()
+ {
+ handleConnections();
+ }
+ }.start();
+ }
+
+ public void addListener(Listener listener)
+ {
+ if (!listeners.contains(listener))
+ {
+ listeners.add(listener);
+ }
+ }
+
+ public void removeListener(Listener listener)
+ {
+ listeners.remove(listener);
+ }
+
+ public Exception close()
+ {
+ try
+ {
+ serverSocket.close();
+ return null;
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error(ex);
+ return ex;
+ }
+ }
+
+ protected ServerSocket bind() throws IOException
+ {
+ InetAddress addr = InetAddress.getByName(address);
+ return new ServerSocket(port, 5, addr);
+ }
+
+ protected void handleConnections()
+ {
+ for (;;)
+ {
+ try
+ {
+ final Socket socket = serverSocket.accept();
+ new Thread()
+ {
+ @Override
+ public void run()
+ {
+ handleSession(socket);
+ }
+ }.start();
+ }
+ catch (IOException ex)
+ {
+ if (!serverSocket.isClosed())
+ {
+ IOUtil.print(ex);
+ }
+
+ break;
+ }
+ }
+ }
+
+ protected void handleSession(Socket socket)
+ {
+ try
+ {
+ InputStream inputStream = socket.getInputStream();
+ DataInputStream in = new DataInputStream(inputStream);
+
+ for (;;)
+ {
+ handleTrace(in);
+ }
+ }
+ catch (IOException ex)
+ {
+ IOUtil.print(ex);
+ }
+ }
+
+ protected void handleTrace(DataInputStream in) throws IOException
+ {
+ Event event = new Event();
+ event.timeStamp = in.readLong();
+ event.agentID = in.readUTF();
+ event.bundleID = in.readUTF();
+ event.tracerName = in.readUTF();
+ event.context = in.readUTF();
+ event.message = in.readUTF();
+ if (in.readBoolean())
+ {
+ event.throwable = in.readUTF();
+ int size = in.readInt();
+ event.stackTrace = new StackTraceElement[size];
+ for (int i = 0; i < size; i++)
+ {
+ String className = in.readUTF();
+ String methodName = in.readUTF();
+ String fileName = in.readUTF();
+ int lineNumber = in.readInt();
+ event.stackTrace[i] = new StackTraceElement(className, methodName, fileName, lineNumber);
+ }
+ }
+
+ fireEvent(event);
+ }
+
+ protected void fireEvent(Event event)
+ {
+ for (Listener listener : listeners)
+ {
+ try
+ {
+ listener.notifyRemoteTrace(event);
+ }
+ catch (RuntimeException ex)
+ {
+ IOUtil.print(ex);
+ }
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public class Event extends EventObject
+ {
+ private static final long serialVersionUID = 1L;
+
+ private long id;
+
+ long timeStamp;
+
+ String agentID;
+
+ String bundleID;
+
+ String tracerName;
+
+ String context;
+
+ String message;
+
+ String throwable;
+
+ StackTraceElement[] stackTrace;
+
+ Event()
+ {
+ super(RemoteTraceServer.this);
+ id = ++lastEventID;
+ }
+
+ public RemoteTraceServer getRemoteTraceServer()
+ {
+ return (RemoteTraceServer)source;
+ }
+
+ public long getID()
+ {
+ return id;
+ }
+
+ public long getTimeStamp()
+ {
+ return timeStamp;
+ }
+
+ public String getAgentID()
+ {
+ return agentID;
+ }
+
+ public String getBundleID()
+ {
+ return bundleID;
+ }
+
+ public String getContext()
+ {
+ return context;
+ }
+
+ public String getMessage()
+ {
+ return message;
+ }
+
+ public StackTraceElement[] getStackTrace()
+ {
+ return stackTrace;
+ }
+
+ public String getThrowable()
+ {
+ return throwable;
+ }
+
+ public String getTracerName()
+ {
+ return tracerName;
+ }
+
+ @Override
+ public String toString()
+ {
+ StringBuilder builder = new StringBuilder();
+ builder.append("TraceEvent[agentID="); //$NON-NLS-1$
+ builder.append(agentID);
+
+ builder.append(", bundleID="); //$NON-NLS-1$
+ builder.append(bundleID);
+
+ builder.append(", tracerName="); //$NON-NLS-1$
+ builder.append(tracerName);
+
+ builder.append(", context="); //$NON-NLS-1$
+ builder.append(context);
+
+ builder.append(", message="); //$NON-NLS-1$
+ builder.append(message);
+
+ builder.append(", throwable="); //$NON-NLS-1$
+ builder.append(throwable);
+
+ builder.append(", stackTrace="); //$NON-NLS-1$
+ builder.append(stackTrace);
+
+ builder.append("]"); //$NON-NLS-1$
+ return builder.toString();
+ }
+
+ public String getText(int index)
+ {
+ switch (index)
+ {
+ case 0:
+ return Long.toString(id);
+ case 1:
+ return new Date(timeStamp).toString();
+ case 2:
+ return agentID;
+ case 3:
+ return bundleID;
+ case 4:
+ return tracerName;
+ case 5:
+ return context;
+ case 6:
+ return message;
+ case 7:
+ return throwable;
+ }
+
+ throw new IllegalArgumentException("Invalid index: " + index); //$NON-NLS-1$
+ }
+
+ public boolean hasError()
+ {
+ return throwable != null && throwable.length() != 0 //
+ || stackTrace != null && stackTrace.length != 0;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public interface Listener
+ {
+ public void notifyRemoteTrace(Event event);
+ }
+
+ public static class PrintListener implements Listener
+ {
+ public static final PrintListener CONSOLE = new PrintListener();
+
+ private PrintStream stream;
+
+ public PrintListener(PrintStream stream)
+ {
+ this.stream = stream;
+ }
+
+ protected PrintListener()
+ {
+ this(IOUtil.OUT());
+ }
+
+ public void notifyRemoteTrace(Event event)
+ {
+ stream.println("[TRACE] " + event.getAgentID()); //$NON-NLS-1$
+ stream.println(event.getBundleID());
+ stream.println(event.getTracerName());
+ stream.println(event.getContext());
+ stream.println(event.getMessage());
+
+ String throwable = event.getThrowable();
+ if (throwable != null && throwable.length() != 0)
+ {
+ stream.println(throwable);
+ }
+
+ StackTraceElement[] stackTrace = event.getStackTrace();
+ if (stackTrace != null)
+ {
+ for (StackTraceElement element : stackTrace)
+ {
+ stream.print(element.getClassName());
+ stream.print("." + element.getMethodName()); //$NON-NLS-1$
+ stream.print("(" + element.getFileName()); //$NON-NLS-1$
+ stream.print(":" + element.getLineNumber()); //$NON-NLS-1$
+ stream.println(")"); //$NON-NLS-1$
+ }
+ }
+
+ stream.println();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/TraceHandlerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/TraceHandlerEvent.java index 7f51b221ab..01f129aa90 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/TraceHandlerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/TraceHandlerEvent.java @@ -1,76 +1,76 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import java.io.Serializable; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - */ -public class TraceHandlerEvent implements OMTraceHandlerEvent, Serializable -{ - private static final long serialVersionUID = 1L; - - protected long timeStamp; - - protected OMTracer tracer; - - protected Class<?> context; - - protected String message; - - protected Throwable throwable; - - public TraceHandlerEvent(OMTracer tracer, Class<?> context, String message, Throwable throwable) - { - if (tracer == null) - { - throw new IllegalArgumentException("tracer == null"); //$NON-NLS-1$ - } - - if (context == null) - { - throw new IllegalArgumentException("context == null"); //$NON-NLS-1$ - } - - timeStamp = System.currentTimeMillis(); - this.tracer = tracer; - this.context = context; - this.message = message; - this.throwable = throwable; - } - - public long getTimeStamp() - { - return timeStamp; - } - - public OMTracer getTracer() - { - return tracer; - } - - public Class<?> getContext() - { - return context; - } - - public String getMessage() - { - return message; - } - - public Throwable getThrowable() - { - return throwable; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import java.io.Serializable;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public class TraceHandlerEvent implements OMTraceHandlerEvent, Serializable
+{
+ private static final long serialVersionUID = 1L;
+
+ protected long timeStamp;
+
+ protected OMTracer tracer;
+
+ protected Class<?> context;
+
+ protected String message;
+
+ protected Throwable throwable;
+
+ public TraceHandlerEvent(OMTracer tracer, Class<?> context, String message, Throwable throwable)
+ {
+ if (tracer == null)
+ {
+ throw new IllegalArgumentException("tracer == null"); //$NON-NLS-1$
+ }
+
+ if (context == null)
+ {
+ throw new IllegalArgumentException("context == null"); //$NON-NLS-1$
+ }
+
+ timeStamp = System.currentTimeMillis();
+ this.tracer = tracer;
+ this.context = context;
+ this.message = message;
+ this.throwable = throwable;
+ }
+
+ public long getTimeStamp()
+ {
+ return timeStamp;
+ }
+
+ public OMTracer getTracer()
+ {
+ return tracer;
+ }
+
+ public Class<?> getContext()
+ {
+ return context;
+ }
+
+ public String getMessage()
+ {
+ return message;
+ }
+
+ public Throwable getThrowable()
+ {
+ return throwable;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/Tracer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/Tracer.java index 9cb88e11ba..0fb1b821e6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/Tracer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/Tracer.java @@ -1,128 +1,128 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.om.trace; - -import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; -import org.eclipse.net4j.util.om.OMBundle; -import org.eclipse.net4j.util.om.OMBundle.DebugSupport; - -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class Tracer implements OMTracer -{ - /** - * @since 3.0 - */ - public static final String PROP_DISABLE_TRACING = "org.eclipse.net4j.util.om.trace.disable"; - - private static final boolean isGloballyDisabled = Boolean.valueOf(System.getProperty(PROP_DISABLE_TRACING, "false")); - - private OMBundle bundle; - - private Tracer parent; - - private String name; - - private String fullName; - - public Tracer(OMBundle bundle, String name) - { - this.bundle = bundle; - this.name = name; - fullName = name; - } - - private Tracer(Tracer parent, String name) - { - bundle = parent.getBundle(); - this.parent = parent; - this.name = name; - fullName = parent.getFullName() + "." + name; //$NON-NLS-1$ - } - - public OMBundle getBundle() - { - return bundle; - } - - public OMTracer getParent() - { - return parent; - } - - public String getName() - { - return name; - } - - public String getFullName() - { - return fullName; - } - - public boolean isEnabled() - { - if (isGloballyDisabled) - { - return false; - } - - DebugSupport debugSupport = bundle.getDebugSupport(); - return debugSupport.isDebugging() && debugSupport.getDebugOption(fullName, false); - } - - public void setEnabled(boolean enabled) - { - DebugSupport debugSupport = bundle.getDebugSupport(); - debugSupport.setDebugOption(fullName, enabled); - } - - public void trace(OMTraceHandlerEvent event) - { - ((AbstractPlatform)bundle.getPlatform()).trace(event); - } - - public OMTraceHandlerEvent trace(Class<?> context, String msg, Throwable t) - { - OMTraceHandlerEvent event = new TraceHandlerEvent(this, context, msg, t); - trace(event); - return event; - } - - public OMTraceHandlerEvent format(Class<?> context, String pattern, Throwable t, Object... args) - { - String msg = MessageFormat.format(pattern, args); - return trace(context, msg, t); - } - - public OMTraceHandlerEvent format(Class<?> context, String pattern, Object... args) - { - return format(context, pattern, (Throwable)null, args); - } - - public OMTraceHandlerEvent trace(Class<?> context, String msg) - { - return trace(context, msg, (Throwable)null); - } - - public OMTraceHandlerEvent trace(Class<?> context, Throwable t) - { - return trace(context, (String)null, t); - } - - public OMTracer tracer(String name) - { - return new Tracer(this, name); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.om.trace;
+
+import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
+import org.eclipse.net4j.util.om.OMBundle;
+import org.eclipse.net4j.util.om.OMBundle.DebugSupport;
+
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class Tracer implements OMTracer
+{
+ /**
+ * @since 3.0
+ */
+ public static final String PROP_DISABLE_TRACING = "org.eclipse.net4j.util.om.trace.disable";
+
+ private static final boolean isGloballyDisabled = Boolean.valueOf(System.getProperty(PROP_DISABLE_TRACING, "false"));
+
+ private OMBundle bundle;
+
+ private Tracer parent;
+
+ private String name;
+
+ private String fullName;
+
+ public Tracer(OMBundle bundle, String name)
+ {
+ this.bundle = bundle;
+ this.name = name;
+ fullName = name;
+ }
+
+ private Tracer(Tracer parent, String name)
+ {
+ bundle = parent.getBundle();
+ this.parent = parent;
+ this.name = name;
+ fullName = parent.getFullName() + "." + name; //$NON-NLS-1$
+ }
+
+ public OMBundle getBundle()
+ {
+ return bundle;
+ }
+
+ public OMTracer getParent()
+ {
+ return parent;
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public String getFullName()
+ {
+ return fullName;
+ }
+
+ public boolean isEnabled()
+ {
+ if (isGloballyDisabled)
+ {
+ return false;
+ }
+
+ DebugSupport debugSupport = bundle.getDebugSupport();
+ return debugSupport.isDebugging() && debugSupport.getDebugOption(fullName, false);
+ }
+
+ public void setEnabled(boolean enabled)
+ {
+ DebugSupport debugSupport = bundle.getDebugSupport();
+ debugSupport.setDebugOption(fullName, enabled);
+ }
+
+ public void trace(OMTraceHandlerEvent event)
+ {
+ ((AbstractPlatform)bundle.getPlatform()).trace(event);
+ }
+
+ public OMTraceHandlerEvent trace(Class<?> context, String msg, Throwable t)
+ {
+ OMTraceHandlerEvent event = new TraceHandlerEvent(this, context, msg, t);
+ trace(event);
+ return event;
+ }
+
+ public OMTraceHandlerEvent format(Class<?> context, String pattern, Throwable t, Object... args)
+ {
+ String msg = MessageFormat.format(pattern, args);
+ return trace(context, msg, t);
+ }
+
+ public OMTraceHandlerEvent format(Class<?> context, String pattern, Object... args)
+ {
+ return format(context, pattern, (Throwable)null, args);
+ }
+
+ public OMTraceHandlerEvent trace(Class<?> context, String msg)
+ {
+ return trace(context, msg, (Throwable)null);
+ }
+
+ public OMTraceHandlerEvent trace(Class<?> context, Throwable t)
+ {
+ return trace(context, (String)null, t);
+ }
+
+ public OMTracer tracer(String name)
+ {
+ return new Tracer(this, name);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java index 3df533477f..af29c7ba01 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptions.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptions.java index 8e0f8ee628..8384574b82 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptions.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptions.java @@ -1,28 +1,28 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Victor Roldan Betancort - initial API and implementation - * Eike Stepper - maintenance - */ -package org.eclipse.net4j.util.options; - -import org.eclipse.net4j.util.event.INotifier; - -/** - * Encapsulates a set of notifying configuration options. - * - * @author Victor Roldan Betancort - * @since 2.0 - */ -public interface IOptions extends INotifier -{ - /** - * Returns the container of this options object. - */ - public IOptionsContainer getContainer(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Victor Roldan Betancort - initial API and implementation
+ * Eike Stepper - maintenance
+ */
+package org.eclipse.net4j.util.options;
+
+import org.eclipse.net4j.util.event.INotifier;
+
+/**
+ * Encapsulates a set of notifying configuration options.
+ *
+ * @author Victor Roldan Betancort
+ * @since 2.0
+ */
+public interface IOptions extends INotifier
+{
+ /**
+ * Returns the container of this options object.
+ */
+ public IOptionsContainer getContainer();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsContainer.java index dc93960f3e..c5a7ea0fe8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsContainer.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Victor Roldan Betancort - initial API and implementation - * Eike Stepper - maintenance - */ -package org.eclipse.net4j.util.options; - -/** - * @author Victor Roldan Betancort - * @since 2.0 - */ -public interface IOptionsContainer -{ - public IOptions options(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Victor Roldan Betancort - initial API and implementation
+ * Eike Stepper - maintenance
+ */
+package org.eclipse.net4j.util.options;
+
+/**
+ * @author Victor Roldan Betancort
+ * @since 2.0
+ */
+public interface IOptionsContainer
+{
+ public IOptions options();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java index fb0c59fd95..ea862e8653 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java @@ -1,25 +1,25 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Victor Roldan Betancort - initial API and implementation - * Eike Stepper - maintenance - */ -package org.eclipse.net4j.util.options; - -import org.eclipse.net4j.util.event.IEvent; - -/** - * A generic {@link IEvent event} fired from an {@link IOptions options} object when an option has changed. - * - * @author Victor Roldan Betancort - * @since 2.0 - */ -public interface IOptionsEvent extends IEvent -{ - public IOptions getSource(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Victor Roldan Betancort - initial API and implementation
+ * Eike Stepper - maintenance
+ */
+package org.eclipse.net4j.util.options;
+
+import org.eclipse.net4j.util.event.IEvent;
+
+/**
+ * A generic {@link IEvent event} fired from an {@link IOptions options} object when an option has changed.
+ *
+ * @author Victor Roldan Betancort
+ * @since 2.0
+ */
+public interface IOptionsEvent extends IEvent
+{
+ public IOptions getSource();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/OptionsEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/OptionsEvent.java index f59ed50533..603df28db5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/OptionsEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/OptionsEvent.java @@ -1,34 +1,34 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Victor Roldan Betancort - initial API and implementation - * Eike Stepper - maintenance - */ -package org.eclipse.net4j.util.options; - -import org.eclipse.net4j.util.event.Event; - -/** - * @author Victor Roldan Betancort - * @since 2.0 - */ -public class OptionsEvent extends Event implements IOptionsEvent -{ - private static final long serialVersionUID = 1L; - - public OptionsEvent(IOptions source) - { - super(source); - } - - @Override - public IOptions getSource() - { - return (IOptions)super.getSource(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Victor Roldan Betancort - initial API and implementation
+ * Eike Stepper - maintenance
+ */
+package org.eclipse.net4j.util.options;
+
+import org.eclipse.net4j.util.event.Event;
+
+/**
+ * @author Victor Roldan Betancort
+ * @since 2.0
+ */
+public class OptionsEvent extends Event implements IOptionsEvent
+{
+ private static final long serialVersionUID = 1L;
+
+ public OptionsEvent(IOptions source)
+ {
+ super(source);
+ }
+
+ @Override
+ public IOptions getSource()
+ {
+ return (IOptions)super.getSource();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java index f7151c134d..38fe59907b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java index 942a96f24b..729b0aac6c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java index ad46e4d1fe..324c70aed1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.properties; - -import org.eclipse.core.expressions.PropertyTester; - -import java.util.List; - -/** - * Tests properties of receiver objects against expected values. - * - * @author Eike Stepper - * @since 3.2 - */ -public class DefaultPropertyTester<RECEIVER> extends PropertyTester implements IProperties<RECEIVER> -{ - private final String namespace; - - private final IProperties<RECEIVER> properties; - - public DefaultPropertyTester(String namespace, IProperties<RECEIVER> properties) - { - this.namespace = namespace; - this.properties = properties; - } - - public final String getNamespace() - { - return namespace; - } - - public Class<RECEIVER> getReceiverType() - { - return properties.getReceiverType(); - } - - public Property<RECEIVER> getProperty(String name) - { - return properties.getProperty(name); - } - - public List<Property<RECEIVER>> getProperties() - { - return properties.getProperties(); - } - - public void add(Property<RECEIVER> property) - { - properties.add(property); - } - - public boolean test(Object receiver, String propertyName, Object[] args, Object expectedValue) - { - Property<RECEIVER> property = getProperty(propertyName); - if (property == null) - { - return false; - } - - @SuppressWarnings("unchecked") - RECEIVER typed = (RECEIVER)receiver; - return property.testValue(typed, args, expectedValue); - } - - public void dumpContributionMarkup() - { - System.out.println(" <extension point=\"org.eclipse.core.expressions.propertyTesters\">"); - System.out.println(" <propertyTester"); - System.out.println(" id=\"" + getNamespace() + ".properties\""); - System.out.println(" type=\"" + getReceiverType().getName() + "\""); - System.out.println(" namespace=\"" + getNamespace() + "\""); - System.out.print(" properties=\""); - - boolean first = true; - for (Property<RECEIVER> property : getProperties()) - { - if (first) - { - first = false; - } - else - { - System.out.print(","); - } - - System.out.print(property.getName()); - } - - System.out.println("\""); - System.out.println(" class=\"" + getClass().getName() + "\"/>"); - System.out.println(" </extension>"); - - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.properties;
+
+import org.eclipse.core.expressions.PropertyTester;
+
+import java.util.List;
+
+/**
+ * Tests properties of receiver objects against expected values.
+ *
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public class DefaultPropertyTester<RECEIVER> extends PropertyTester implements IProperties<RECEIVER>
+{
+ private final String namespace;
+
+ private final IProperties<RECEIVER> properties;
+
+ public DefaultPropertyTester(String namespace, IProperties<RECEIVER> properties)
+ {
+ this.namespace = namespace;
+ this.properties = properties;
+ }
+
+ public final String getNamespace()
+ {
+ return namespace;
+ }
+
+ public Class<RECEIVER> getReceiverType()
+ {
+ return properties.getReceiverType();
+ }
+
+ public Property<RECEIVER> getProperty(String name)
+ {
+ return properties.getProperty(name);
+ }
+
+ public List<Property<RECEIVER>> getProperties()
+ {
+ return properties.getProperties();
+ }
+
+ public void add(Property<RECEIVER> property)
+ {
+ properties.add(property);
+ }
+
+ public boolean test(Object receiver, String propertyName, Object[] args, Object expectedValue)
+ {
+ Property<RECEIVER> property = getProperty(propertyName);
+ if (property == null)
+ {
+ return false;
+ }
+
+ @SuppressWarnings("unchecked")
+ RECEIVER typed = (RECEIVER)receiver;
+ return property.testValue(typed, args, expectedValue);
+ }
+
+ public void dumpContributionMarkup()
+ {
+ System.out.println(" <extension point=\"org.eclipse.core.expressions.propertyTesters\">");
+ System.out.println(" <propertyTester");
+ System.out.println(" id=\"" + getNamespace() + ".properties\"");
+ System.out.println(" type=\"" + getReceiverType().getName() + "\"");
+ System.out.println(" namespace=\"" + getNamespace() + "\"");
+ System.out.print(" properties=\"");
+
+ boolean first = true;
+ for (Property<RECEIVER> property : getProperties())
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ System.out.print(",");
+ }
+
+ System.out.print(property.getName());
+ }
+
+ System.out.println("\"");
+ System.out.println(" class=\"" + getClass().getName() + "\"/>");
+ System.out.println(" </extension>");
+
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java index 4830b9f2f3..15cba8cae6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.properties; - -/** - * Contains a list of {@link Property properties}. - * - * @author Eike Stepper - * @since 3.2 - */ -public interface IProperties<RECEIVER> extends IPropertyProvider<RECEIVER> -{ - public Class<RECEIVER> getReceiverType(); - - public Property<RECEIVER> getProperty(String name); - - public void add(Property<RECEIVER> property); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.properties;
+
+/**
+ * Contains a list of {@link Property properties}.
+ *
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public interface IProperties<RECEIVER> extends IPropertyProvider<RECEIVER>
+{
+ public Class<RECEIVER> getReceiverType();
+
+ public Property<RECEIVER> getProperty(String name);
+
+ public void add(Property<RECEIVER> property);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java index 5133353d29..1edcb25bb1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java index 44ce4c7f5a..677708ed0f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java @@ -1,64 +1,64 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.properties; - -import org.eclipse.net4j.util.CheckUtil; - -import java.util.ArrayList; -import java.util.List; - -/** - * Contains a list of {@link Property properties}. - * - * @author Eike Stepper - * @since 3.2 - */ -public class Properties<RECEIVER> implements IProperties<RECEIVER> -{ - private final List<Property<RECEIVER>> properties = new ArrayList<Property<RECEIVER>>(); - - private final Class<RECEIVER> receiverType; - - public Properties(Class<RECEIVER> receiverType) - { - this.receiverType = receiverType; - } - - public final Class<RECEIVER> getReceiverType() - { - return receiverType; - } - - public final void add(Property<RECEIVER> property) - { - CheckUtil.checkArg(property, "property"); - CheckUtil.checkArg(property.getName(), "property.getName()"); - properties.add(property); - } - - public final List<Property<RECEIVER>> getProperties() - { - return properties; - } - - public final Property<RECEIVER> getProperty(String name) - { - for (Property<RECEIVER> property : properties) - { - if (property.getName().equals(name)) - { - return property; - } - } - - return null; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.properties;
+
+import org.eclipse.net4j.util.CheckUtil;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Contains a list of {@link Property properties}.
+ *
+ * @author Eike Stepper
+ * @since 3.2
+ */
+public class Properties<RECEIVER> implements IProperties<RECEIVER>
+{
+ private final List<Property<RECEIVER>> properties = new ArrayList<Property<RECEIVER>>();
+
+ private final Class<RECEIVER> receiverType;
+
+ public Properties(Class<RECEIVER> receiverType)
+ {
+ this.receiverType = receiverType;
+ }
+
+ public final Class<RECEIVER> getReceiverType()
+ {
+ return receiverType;
+ }
+
+ public final void add(Property<RECEIVER> property)
+ {
+ CheckUtil.checkArg(property, "property");
+ CheckUtil.checkArg(property.getName(), "property.getName()");
+ properties.add(property);
+ }
+
+ public final List<Property<RECEIVER>> getProperties()
+ {
+ return properties;
+ }
+
+ public final Property<RECEIVER> getProperty(String name)
+ {
+ for (Property<RECEIVER> property : properties)
+ {
+ if (property.getName().equals(name))
+ {
+ return property;
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java index 8de1db9d79..39f667d7f1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java index 1cd5e9f46a..15397daa96 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java index a9a77d09d0..f5463d3891 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java @@ -1,45 +1,45 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -import java.lang.ref.PhantomReference; -import java.lang.ref.ReferenceQueue; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class KeyedPhantomReference<K, T> extends PhantomReference<T> implements KeyedReference<K, T> -{ - private K key; - - public KeyedPhantomReference(K key, T ref, ReferenceQueue<T> queue) - { - super(ref, queue); - this.key = key; - } - - public ReferenceType getType() - { - return ReferenceType.PHANTOM; - } - - public K getKey() - { - return key; - } - - @Override - public String toString() - { - return MessageFormat.format("KeyedPhantomReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+import java.lang.ref.PhantomReference;
+import java.lang.ref.ReferenceQueue;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class KeyedPhantomReference<K, T> extends PhantomReference<T> implements KeyedReference<K, T>
+{
+ private K key;
+
+ public KeyedPhantomReference(K key, T ref, ReferenceQueue<T> queue)
+ {
+ super(ref, queue);
+ this.key = key;
+ }
+
+ public ReferenceType getType()
+ {
+ return ReferenceType.PHANTOM;
+ }
+
+ public K getKey()
+ {
+ return key;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("KeyedPhantomReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java index 754ac3e596..457150957f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java @@ -1,44 +1,44 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -import java.lang.ref.Reference; - -/** - * @see Reference - * @author Eike Stepper - */ -public interface KeyedReference<K, T> -{ - public ReferenceType getType(); - - public K getKey(); - - /** - * @see Reference#get() - */ - public T get(); - - /** - * @see Reference#clear() - */ - public void clear(); - - /** - * @see Reference#isEnqueued() - */ - public boolean isEnqueued(); - - /** - * @see Reference#enqueue() - */ - public boolean enqueue(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+import java.lang.ref.Reference;
+
+/**
+ * @see Reference
+ * @author Eike Stepper
+ */
+public interface KeyedReference<K, T>
+{
+ public ReferenceType getType();
+
+ public K getKey();
+
+ /**
+ * @see Reference#get()
+ */
+ public T get();
+
+ /**
+ * @see Reference#clear()
+ */
+ public void clear();
+
+ /**
+ * @see Reference#isEnqueued()
+ */
+ public boolean isEnqueued();
+
+ /**
+ * @see Reference#enqueue()
+ */
+ public boolean enqueue();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java index 99a2f4cc7e..c4b5c52798 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class KeyedSoftReference<K, T> extends SoftReference<T> implements KeyedReference<K, T> -{ - private K key; - - public KeyedSoftReference(K key, T ref) - { - super(ref); - this.key = key; - } - - public KeyedSoftReference(K key, T ref, ReferenceQueue<T> queue) - { - super(ref, queue); - this.key = key; - } - - public ReferenceType getType() - { - return ReferenceType.SOFT; - } - - public K getKey() - { - return key; - } - - @Override - public String toString() - { - return MessageFormat.format("KeyedSoftReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class KeyedSoftReference<K, T> extends SoftReference<T> implements KeyedReference<K, T>
+{
+ private K key;
+
+ public KeyedSoftReference(K key, T ref)
+ {
+ super(ref);
+ this.key = key;
+ }
+
+ public KeyedSoftReference(K key, T ref, ReferenceQueue<T> queue)
+ {
+ super(ref, queue);
+ this.key = key;
+ }
+
+ public ReferenceType getType()
+ {
+ return ReferenceType.SOFT;
+ }
+
+ public K getKey()
+ {
+ return key;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("KeyedSoftReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java index f57f8f77bf..3455f5bace 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java @@ -1,65 +1,65 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class KeyedStrongReference<K, T> implements KeyedReference<K, T> -{ - private K key; - - private T ref; - - public KeyedStrongReference(K key, T ref) - { - this.key = key; - this.ref = ref; - } - - public ReferenceType getType() - { - return ReferenceType.STRONG; - } - - public K getKey() - { - return key; - } - - public T get() - { - return ref; - } - - public void clear() - { - ref = null; - } - - public boolean isEnqueued() - { - return false; - } - - public boolean enqueue() - { - return false; - } - - @Override - public String toString() - { - return MessageFormat.format("KeyedStrongReference[{0} -> {1}]", key, ref); //$NON-NLS-1$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class KeyedStrongReference<K, T> implements KeyedReference<K, T>
+{
+ private K key;
+
+ private T ref;
+
+ public KeyedStrongReference(K key, T ref)
+ {
+ this.key = key;
+ this.ref = ref;
+ }
+
+ public ReferenceType getType()
+ {
+ return ReferenceType.STRONG;
+ }
+
+ public K getKey()
+ {
+ return key;
+ }
+
+ public T get()
+ {
+ return ref;
+ }
+
+ public void clear()
+ {
+ ref = null;
+ }
+
+ public boolean isEnqueued()
+ {
+ return false;
+ }
+
+ public boolean enqueue()
+ {
+ return false;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("KeyedStrongReference[{0} -> {1}]", key, ref); //$NON-NLS-1$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java index 9cc4874271..e8c6e2bdb4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class KeyedWeakReference<K, T> extends WeakReference<T> implements KeyedReference<K, T> -{ - private K key; - - public KeyedWeakReference(K key, T ref) - { - super(ref); - this.key = key; - } - - public KeyedWeakReference(K key, T ref, ReferenceQueue<T> queue) - { - super(ref, queue); - this.key = key; - } - - public ReferenceType getType() - { - return ReferenceType.WEAK; - } - - public K getKey() - { - return key; - } - - @Override - public String toString() - { - return MessageFormat.format("KeyedWeakReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$ - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class KeyedWeakReference<K, T> extends WeakReference<T> implements KeyedReference<K, T>
+{
+ private K key;
+
+ public KeyedWeakReference(K key, T ref)
+ {
+ super(ref);
+ this.key = key;
+ }
+
+ public KeyedWeakReference(K key, T ref, ReferenceQueue<T> queue)
+ {
+ super(ref, queue);
+ this.key = key;
+ }
+
+ public ReferenceType getType()
+ {
+ return ReferenceType.WEAK;
+ }
+
+ public K getKey()
+ {
+ return key;
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("KeyedWeakReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java index 1ec35c91e6..9cc25c7397 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java @@ -1,101 +1,101 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - * Victor Roldan Betancort - Bug 311840 - OutOfMemory with fast population of revision cache - */ -package org.eclipse.net4j.util.ref; - -import org.eclipse.net4j.util.concurrent.Worker; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class ReferenceQueueWorker<T> extends Worker -{ - /** - * @since 3.0 - */ - public static final int DEFAULT_POLL_MILLIS = 1000 * 60; // One minute - - /** - * @since 3.0 - */ - public static final int ALL_WORK_PER_POLL = -1; - - /** - * @since 3.0 - */ - public static final int DEFAULT_MAX_WORK_PER_POLL = ALL_WORK_PER_POLL; - - private ReferenceQueue<T> queue = new ReferenceQueue<T>(); - - private long pollMillis; - - private int maxWorkPerPoll; - - public ReferenceQueueWorker() - { - setPollMillis(DEFAULT_POLL_MILLIS); - setMaxWorkPerPoll(DEFAULT_MAX_WORK_PER_POLL); - } - - public long getPollMillis() - { - return pollMillis; - } - - public void setPollMillis(long pollMillis) - { - this.pollMillis = pollMillis; - } - - public int getMaxWorkPerPoll() - { - return maxWorkPerPoll; - } - - public void setMaxWorkPerPoll(int maxWorkPerPoll) - { - this.maxWorkPerPoll = maxWorkPerPoll; - } - - protected ReferenceQueue<T> getQueue() - { - return queue; - } - - @Override - protected final void work(WorkContext context) throws Exception - { - int count = maxWorkPerPoll; - if (count == ALL_WORK_PER_POLL) - { - count = Integer.MAX_VALUE; - } - - for (int i = 0; i < count; i++) - { - Reference<? extends T> reference = queue.poll(); - if (reference == null) - { - break; - } - - work(reference); - } - - context.nextWork(pollMillis); - } - - protected abstract void work(Reference<? extends T> reference); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ * Victor Roldan Betancort - Bug 311840 - OutOfMemory with fast population of revision cache
+ */
+package org.eclipse.net4j.util.ref;
+
+import org.eclipse.net4j.util.concurrent.Worker;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class ReferenceQueueWorker<T> extends Worker
+{
+ /**
+ * @since 3.0
+ */
+ public static final int DEFAULT_POLL_MILLIS = 1000 * 60; // One minute
+
+ /**
+ * @since 3.0
+ */
+ public static final int ALL_WORK_PER_POLL = -1;
+
+ /**
+ * @since 3.0
+ */
+ public static final int DEFAULT_MAX_WORK_PER_POLL = ALL_WORK_PER_POLL;
+
+ private ReferenceQueue<T> queue = new ReferenceQueue<T>();
+
+ private long pollMillis;
+
+ private int maxWorkPerPoll;
+
+ public ReferenceQueueWorker()
+ {
+ setPollMillis(DEFAULT_POLL_MILLIS);
+ setMaxWorkPerPoll(DEFAULT_MAX_WORK_PER_POLL);
+ }
+
+ public long getPollMillis()
+ {
+ return pollMillis;
+ }
+
+ public void setPollMillis(long pollMillis)
+ {
+ this.pollMillis = pollMillis;
+ }
+
+ public int getMaxWorkPerPoll()
+ {
+ return maxWorkPerPoll;
+ }
+
+ public void setMaxWorkPerPoll(int maxWorkPerPoll)
+ {
+ this.maxWorkPerPoll = maxWorkPerPoll;
+ }
+
+ protected ReferenceQueue<T> getQueue()
+ {
+ return queue;
+ }
+
+ @Override
+ protected final void work(WorkContext context) throws Exception
+ {
+ int count = maxWorkPerPoll;
+ if (count == ALL_WORK_PER_POLL)
+ {
+ count = Integer.MAX_VALUE;
+ }
+
+ for (int i = 0; i < count; i++)
+ {
+ Reference<? extends T> reference = queue.poll();
+ if (reference == null)
+ {
+ break;
+ }
+
+ work(reference);
+ }
+
+ context.nextWork(pollMillis);
+ }
+
+ protected abstract void work(Reference<? extends T> reference);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java index 197ba2c935..cc364bbc33 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java @@ -1,20 +1,20 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - */ -public enum ReferenceType -{ - STRONG, SOFT, WEAK, PHANTOM; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public enum ReferenceType
+{
+ STRONG, SOFT, WEAK, PHANTOM;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java index db4fb6508a..c731a5e9f8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java @@ -1,503 +1,503 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.ref; - -import org.eclipse.net4j.util.collection.MapEntry; - -import java.lang.ref.ReferenceQueue; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * A {@link ConcurrentMap} implementation that uses {@link KeyedReference} instances ({@link KeyedStrongReference}, - * {@link KeyedSoftReference}, {@link KeyedWeakReference} or {@link KeyedPhantomReference}) as its values. - * <p> - * A <code>ReferenceValueMap</code> can be used to cache mappings until the <em>value</em> of the mapping is no longer - * reachable from outside of the map - * <p> - * <b>Note:</b> This map is not synchronized. If it is to be used by multiple threads concurrently the user is - * responsible for applying proper external synchronization! - * - * @author Eike Stepper - */ -public abstract class ReferenceValueMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> -{ - private ConcurrentMap<K, KeyedReference<K, V>> map; - - private ReferenceQueue<V> queue; - - private EntrySet entrySet; - - public ReferenceValueMap() - { - this(new ConcurrentHashMap<K, KeyedReference<K, V>>()); - } - - public ReferenceValueMap(ConcurrentMap<K, KeyedReference<K, V>> map) - { - if (!map.isEmpty()) - { - throw new IllegalArgumentException("!map.isEmpty()"); //$NON-NLS-1$ - } - - this.map = map; - queue = createQueue(); - } - - @Override - public int size() - { - purgeQueue(); - return map.size(); - } - - @Override - public boolean isEmpty() - { - purgeQueue(); - return map.isEmpty(); - } - - @Override - public boolean containsKey(Object key) - { - KeyedReference<K, V> ref = map.get(key); - if (ref != null) - { - if (ref.get() == null) - { - // ref.enqueue(); - return false; - } - - return true; - } - - return false; - } - - @Override - public boolean containsValue(Object value) - { - if (value == null) - { - throw new IllegalArgumentException("value == null"); //$NON-NLS-1$ - } - - for (KeyedReference<K, V> ref : map.values()) - { - V v = ref.get(); - if (v == null) - { - // ref.enqueue(); - return false; - } - - if (value.equals(v)) - { - return true; - } - } - - return false; - } - - @Override - public V get(Object key) - { - KeyedReference<K, V> ref = map.get(key); - return dereference(ref); - } - - @Override - public V put(K key, V value) - { - try - { - KeyedReference<K, V> ref = createReference(key, value, queue); - KeyedReference<K, V> oldRef = map.put(key, ref); - return dereference(oldRef); - } - finally - { - purgeQueue(); - } - } - - public V putIfAbsent(K key, V value) - { - try - { - KeyedReference<K, V> ref = createReference(key, value, queue); - KeyedReference<K, V> oldRef = map.putIfAbsent(key, ref); - return dereference(oldRef); - } - finally - { - purgeQueue(); - } - } - - public V replace(K key, V value) - { - try - { - KeyedReference<K, V> ref = createReference(key, value, queue); - KeyedReference<K, V> oldRef = map.replace(key, ref); - return dereference(oldRef); - } - finally - { - purgeQueue(); - } - } - - public boolean replace(K key, V oldValue, V newValue) - { - try - { - // TODO Consider a dummy KeyedReference class for oldRef - KeyedReference<K, V> oldRef = createReference(key, oldValue, queue); - KeyedReference<K, V> newRef = createReference(key, newValue, queue); - return map.replace(key, oldRef, newRef); - } - finally - { - purgeQueue(); - } - } - - @Override - public V remove(Object key) - { - KeyedReference<K, V> ref = map.remove(key); - return dereference(ref); - } - - public boolean remove(Object key, Object value) - { - // TODO Consider a dummy KeyedReference class for value - return map.remove(key, value); - } - - @Override - public void clear() - { - purgeQueue(); - map.clear(); - } - - @Override - public Set<Map.Entry<K, V>> entrySet() - { - if (entrySet == null) - { - purgeQueue(); - entrySet = new EntrySet(); - } - - return entrySet; - } - - protected ReferenceQueue<V> createQueue() - { - return new ReferenceQueue<V>(); - } - - @SuppressWarnings("unchecked") - protected void purgeQueue() - { - if (queue != null) - { - KeyedReference<K, V> ref; - while ((ref = (KeyedReference<K, V>)queue.poll()) != null) - { - // Slightly faster than map.get() + map.remove() - K key = ref.getKey(); - map.remove(key, ref); - purged(key); - } - } - } - - protected void purged(K key) - { - } - - protected V dereference(KeyedReference<K, V> ref) - { - if (ref == null) - { - return null; - } - - return ref.get(); - } - - protected abstract KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue); - - /** - * @author Eike Stepper - */ - public static class Strong<K, V> extends ReferenceValueMap<K, V> - { - public Strong() - { - } - - public Strong(ConcurrentMap<K, KeyedReference<K, V>> map) - { - super(map); - } - - @Override - protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue) - { - return new KeyedStrongReference<K, V>(key, value); - } - - @Override - protected ReferenceQueue<V> createQueue() - { - return null; - } - } - - /** - * @author Eike Stepper - */ - public static class Soft<K, V> extends ReferenceValueMap<K, V> - { - public Soft() - { - } - - public Soft(ConcurrentMap<K, KeyedReference<K, V>> map) - { - super(map); - } - - @Override - protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue) - { - return new KeyedSoftReference<K, V>(key, value, queue); - } - } - - /** - * @author Eike Stepper - */ - public static class Weak<K, V> extends ReferenceValueMap<K, V> - { - public Weak() - { - } - - public Weak(ConcurrentMap<K, KeyedReference<K, V>> map) - { - super(map); - } - - @Override - protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue) - { - return new KeyedWeakReference<K, V>(key, value, queue); - } - } - - /** - * @author Eike Stepper - */ - private class EntrySet extends AbstractSet<Map.Entry<K, V>> - { - public EntrySet() - { - } - - @Override - public int size() - { - return map.size(); - } - - @Override - public boolean isEmpty() - { - return map.isEmpty(); - } - - @Override - public boolean contains(Object object) - { - if (object == null) - { - throw new IllegalArgumentException("object == null"); //$NON-NLS-1$ - } - - if (object instanceof Map.Entry<?, ?>) - { - Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object; - Object key = entry.getKey(); - Object value = entry.getValue(); - return key != null && value != null && value.equals(get(key)); - } - - return false; - } - - @Override - public Iterator<Map.Entry<K, V>> iterator() - { - return new EntrySetIterator(); - } - - @Override - public Object[] toArray() - { - Object[] a = new Object[size()]; - int i = 0; - for (Map.Entry<K, V> entry : this) - { - a[i++] = entry; - } - - return a; - } - - @SuppressWarnings("unchecked") - @Override - public <T> T[] toArray(T[] a) - { - if (a == null) - { - throw new IllegalArgumentException("array == null"); //$NON-NLS-1$ - } - - int size = size(); - if (a.length < size) - { - a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); - } - - int i = 0; - for (Map.Entry<K, V> entry : this) - { - a[i++] = (T)entry; - } - - if (a.length > size) - { - a[size] = null; - } - - return a; - } - - @Override - public boolean remove(Object object) - { - if (object == null) - { - throw new IllegalArgumentException("object == null"); //$NON-NLS-1$ - } - - if (object instanceof Map.Entry<?, ?>) - { - Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object; - return map.remove(entry.getKey(), entry.getValue()); - } - - return false; - } - - @Override - public void clear() - { - map.clear(); - } - } - - /** - * @author Eike Stepper - */ - private class EntrySetIterator implements Iterator<Map.Entry<K, V>> - { - private Iterator<Entry<K, KeyedReference<K, V>>> it = map.entrySet().iterator(); - - private MapEntry<K, V> nextEntry; - - private K lastKey; - - public EntrySetIterator() - { - } - - public boolean hasNext() - { - if (nextEntry != null) - { - return true; - } - - while (it.hasNext()) - { - Entry<K, KeyedReference<K, V>> entry = it.next(); - lastKey = entry.getKey(); - V value = dereference(entry.getValue()); - if (value != null) - { - nextEntry = new MapEntry<K, V>(lastKey, value); - return true; - } - } - - return false; - } - - public Entry<K, V> next() - { - if (nextEntry == null) - { - if (!hasNext()) - { - throw new NoSuchElementException(); - } - } - - try - { - return nextEntry; - } - finally - { - nextEntry = null; - } - } - - public void remove() - { - if (lastKey == null) - { - throw new IllegalStateException("lastKey == null"); //$NON-NLS-1$ - } - - map.remove(lastKey); - lastKey = null; - nextEntry = null; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.ref;
+
+import org.eclipse.net4j.util.collection.MapEntry;
+
+import java.lang.ref.ReferenceQueue;
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * A {@link ConcurrentMap} implementation that uses {@link KeyedReference} instances ({@link KeyedStrongReference},
+ * {@link KeyedSoftReference}, {@link KeyedWeakReference} or {@link KeyedPhantomReference}) as its values.
+ * <p>
+ * A <code>ReferenceValueMap</code> can be used to cache mappings until the <em>value</em> of the mapping is no longer
+ * reachable from outside of the map
+ * <p>
+ * <b>Note:</b> This map is not synchronized. If it is to be used by multiple threads concurrently the user is
+ * responsible for applying proper external synchronization!
+ *
+ * @author Eike Stepper
+ */
+public abstract class ReferenceValueMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
+{
+ private ConcurrentMap<K, KeyedReference<K, V>> map;
+
+ private ReferenceQueue<V> queue;
+
+ private EntrySet entrySet;
+
+ public ReferenceValueMap()
+ {
+ this(new ConcurrentHashMap<K, KeyedReference<K, V>>());
+ }
+
+ public ReferenceValueMap(ConcurrentMap<K, KeyedReference<K, V>> map)
+ {
+ if (!map.isEmpty())
+ {
+ throw new IllegalArgumentException("!map.isEmpty()"); //$NON-NLS-1$
+ }
+
+ this.map = map;
+ queue = createQueue();
+ }
+
+ @Override
+ public int size()
+ {
+ purgeQueue();
+ return map.size();
+ }
+
+ @Override
+ public boolean isEmpty()
+ {
+ purgeQueue();
+ return map.isEmpty();
+ }
+
+ @Override
+ public boolean containsKey(Object key)
+ {
+ KeyedReference<K, V> ref = map.get(key);
+ if (ref != null)
+ {
+ if (ref.get() == null)
+ {
+ // ref.enqueue();
+ return false;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean containsValue(Object value)
+ {
+ if (value == null)
+ {
+ throw new IllegalArgumentException("value == null"); //$NON-NLS-1$
+ }
+
+ for (KeyedReference<K, V> ref : map.values())
+ {
+ V v = ref.get();
+ if (v == null)
+ {
+ // ref.enqueue();
+ return false;
+ }
+
+ if (value.equals(v))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public V get(Object key)
+ {
+ KeyedReference<K, V> ref = map.get(key);
+ return dereference(ref);
+ }
+
+ @Override
+ public V put(K key, V value)
+ {
+ try
+ {
+ KeyedReference<K, V> ref = createReference(key, value, queue);
+ KeyedReference<K, V> oldRef = map.put(key, ref);
+ return dereference(oldRef);
+ }
+ finally
+ {
+ purgeQueue();
+ }
+ }
+
+ public V putIfAbsent(K key, V value)
+ {
+ try
+ {
+ KeyedReference<K, V> ref = createReference(key, value, queue);
+ KeyedReference<K, V> oldRef = map.putIfAbsent(key, ref);
+ return dereference(oldRef);
+ }
+ finally
+ {
+ purgeQueue();
+ }
+ }
+
+ public V replace(K key, V value)
+ {
+ try
+ {
+ KeyedReference<K, V> ref = createReference(key, value, queue);
+ KeyedReference<K, V> oldRef = map.replace(key, ref);
+ return dereference(oldRef);
+ }
+ finally
+ {
+ purgeQueue();
+ }
+ }
+
+ public boolean replace(K key, V oldValue, V newValue)
+ {
+ try
+ {
+ // TODO Consider a dummy KeyedReference class for oldRef
+ KeyedReference<K, V> oldRef = createReference(key, oldValue, queue);
+ KeyedReference<K, V> newRef = createReference(key, newValue, queue);
+ return map.replace(key, oldRef, newRef);
+ }
+ finally
+ {
+ purgeQueue();
+ }
+ }
+
+ @Override
+ public V remove(Object key)
+ {
+ KeyedReference<K, V> ref = map.remove(key);
+ return dereference(ref);
+ }
+
+ public boolean remove(Object key, Object value)
+ {
+ // TODO Consider a dummy KeyedReference class for value
+ return map.remove(key, value);
+ }
+
+ @Override
+ public void clear()
+ {
+ purgeQueue();
+ map.clear();
+ }
+
+ @Override
+ public Set<Map.Entry<K, V>> entrySet()
+ {
+ if (entrySet == null)
+ {
+ purgeQueue();
+ entrySet = new EntrySet();
+ }
+
+ return entrySet;
+ }
+
+ protected ReferenceQueue<V> createQueue()
+ {
+ return new ReferenceQueue<V>();
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void purgeQueue()
+ {
+ if (queue != null)
+ {
+ KeyedReference<K, V> ref;
+ while ((ref = (KeyedReference<K, V>)queue.poll()) != null)
+ {
+ // Slightly faster than map.get() + map.remove()
+ K key = ref.getKey();
+ map.remove(key, ref);
+ purged(key);
+ }
+ }
+ }
+
+ protected void purged(K key)
+ {
+ }
+
+ protected V dereference(KeyedReference<K, V> ref)
+ {
+ if (ref == null)
+ {
+ return null;
+ }
+
+ return ref.get();
+ }
+
+ protected abstract KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue);
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class Strong<K, V> extends ReferenceValueMap<K, V>
+ {
+ public Strong()
+ {
+ }
+
+ public Strong(ConcurrentMap<K, KeyedReference<K, V>> map)
+ {
+ super(map);
+ }
+
+ @Override
+ protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue)
+ {
+ return new KeyedStrongReference<K, V>(key, value);
+ }
+
+ @Override
+ protected ReferenceQueue<V> createQueue()
+ {
+ return null;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class Soft<K, V> extends ReferenceValueMap<K, V>
+ {
+ public Soft()
+ {
+ }
+
+ public Soft(ConcurrentMap<K, KeyedReference<K, V>> map)
+ {
+ super(map);
+ }
+
+ @Override
+ protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue)
+ {
+ return new KeyedSoftReference<K, V>(key, value, queue);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static class Weak<K, V> extends ReferenceValueMap<K, V>
+ {
+ public Weak()
+ {
+ }
+
+ public Weak(ConcurrentMap<K, KeyedReference<K, V>> map)
+ {
+ super(map);
+ }
+
+ @Override
+ protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue)
+ {
+ return new KeyedWeakReference<K, V>(key, value, queue);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private class EntrySet extends AbstractSet<Map.Entry<K, V>>
+ {
+ public EntrySet()
+ {
+ }
+
+ @Override
+ public int size()
+ {
+ return map.size();
+ }
+
+ @Override
+ public boolean isEmpty()
+ {
+ return map.isEmpty();
+ }
+
+ @Override
+ public boolean contains(Object object)
+ {
+ if (object == null)
+ {
+ throw new IllegalArgumentException("object == null"); //$NON-NLS-1$
+ }
+
+ if (object instanceof Map.Entry<?, ?>)
+ {
+ Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object;
+ Object key = entry.getKey();
+ Object value = entry.getValue();
+ return key != null && value != null && value.equals(get(key));
+ }
+
+ return false;
+ }
+
+ @Override
+ public Iterator<Map.Entry<K, V>> iterator()
+ {
+ return new EntrySetIterator();
+ }
+
+ @Override
+ public Object[] toArray()
+ {
+ Object[] a = new Object[size()];
+ int i = 0;
+ for (Map.Entry<K, V> entry : this)
+ {
+ a[i++] = entry;
+ }
+
+ return a;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <T> T[] toArray(T[] a)
+ {
+ if (a == null)
+ {
+ throw new IllegalArgumentException("array == null"); //$NON-NLS-1$
+ }
+
+ int size = size();
+ if (a.length < size)
+ {
+ a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
+ }
+
+ int i = 0;
+ for (Map.Entry<K, V> entry : this)
+ {
+ a[i++] = (T)entry;
+ }
+
+ if (a.length > size)
+ {
+ a[size] = null;
+ }
+
+ return a;
+ }
+
+ @Override
+ public boolean remove(Object object)
+ {
+ if (object == null)
+ {
+ throw new IllegalArgumentException("object == null"); //$NON-NLS-1$
+ }
+
+ if (object instanceof Map.Entry<?, ?>)
+ {
+ Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object;
+ return map.remove(entry.getKey(), entry.getValue());
+ }
+
+ return false;
+ }
+
+ @Override
+ public void clear()
+ {
+ map.clear();
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private class EntrySetIterator implements Iterator<Map.Entry<K, V>>
+ {
+ private Iterator<Entry<K, KeyedReference<K, V>>> it = map.entrySet().iterator();
+
+ private MapEntry<K, V> nextEntry;
+
+ private K lastKey;
+
+ public EntrySetIterator()
+ {
+ }
+
+ public boolean hasNext()
+ {
+ if (nextEntry != null)
+ {
+ return true;
+ }
+
+ while (it.hasNext())
+ {
+ Entry<K, KeyedReference<K, V>> entry = it.next();
+ lastKey = entry.getKey();
+ V value = dereference(entry.getValue());
+ if (value != null)
+ {
+ nextEntry = new MapEntry<K, V>(lastKey, value);
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ public Entry<K, V> next()
+ {
+ if (nextEntry == null)
+ {
+ if (!hasNext())
+ {
+ throw new NoSuchElementException();
+ }
+ }
+
+ try
+ {
+ return nextEntry;
+ }
+ finally
+ {
+ nextEntry = null;
+ }
+ }
+
+ public void remove()
+ {
+ if (lastKey == null)
+ {
+ throw new IllegalStateException("lastKey == null"); //$NON-NLS-1$
+ }
+
+ map.remove(lastKey);
+ lastKey = null;
+ nextEntry = null;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java index 7edb2f7190..57bb9fed38 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java index acece78f70..c5863d4331 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java @@ -1,149 +1,149 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Implementation note: AbstractDelegatingRegistry does not preserve the "modifyable view" contract of - * {@link Map#entrySet()} as well as of {@link Map#keySet()}, i.e. they are disconnected sets and modifications applied - * to them are not applied to their underlying AbstractDelegatingRegistry. - * <p> - * - * @author Eike Stepper - */ -public abstract class DelegatingRegistry<K, V> extends Registry<K, V> -{ - private IRegistry<K, V> delegate; - - public DelegatingRegistry(IRegistry<K, V> delegate) - { - this.delegate = delegate; - } - - public DelegatingRegistry(IRegistry<K, V> delegate, boolean autoCommit) - { - super(autoCommit); - this.delegate = delegate; - } - - @Override - public V get(Object key) - { - V result = getMap().get(key); - if (result == null && delegate != null) - { - result = delegate.get(key); - } - - return result; - } - - @Override - public Set<Entry<K, V>> entrySet() - { - return mergedEntrySet(); - } - - @Override - public Set<K> keySet() - { - return mergedKeySet(); - } - - @Override - public Collection<V> values() - { - return mergedValues(); - } - - @Override - protected V register(K key, V value) - { - V delegated = delegate != null ? delegate.get(key) : null; - V old = getMap().put(key, value); - if (old == null) - { - if (delegated != null) - { - // Unhidden delegated element now becomes hidden - getTransaction().rememberDeregistered(key, delegated); - } - - getTransaction().rememberRegistered(key, value); - return delegated; - } - - getTransaction().rememberDeregistered(key, old); - getTransaction().rememberRegistered(key, value); - return old; - } - - @SuppressWarnings("unchecked") - @Override - protected V deregister(Object key) - { - V delegated = delegate != null ? delegate.get(key) : null; - V old = getMap().remove(key); - if (old != null) - { - getTransaction().rememberDeregistered((K)key, old); - if (delegated != null) - { - // Hidden delegated element now becomes unhidden - getTransaction().rememberRegistered((K)key, delegated); - } - } - - return old; - } - - protected Set<Entry<K, V>> mergedEntrySet() - { - final Map<K, V> merged = new HashMap<K, V>(); - if (delegate != null) - { - merged.putAll(delegate); - } - - merged.putAll(getMap()); - return merged.entrySet(); - } - - protected Set<K> mergedKeySet() - { - final Set<K> merged = new HashSet<K>(); - if (delegate != null) - { - merged.addAll(delegate.keySet()); - } - - merged.addAll(getMap().keySet()); - return merged; - } - - protected Collection<V> mergedValues() - { - final List<V> result = new ArrayList<V>(); - for (K key : keySet()) - { - result.add(get(key)); - } - - return result; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Implementation note: AbstractDelegatingRegistry does not preserve the "modifyable view" contract of
+ * {@link Map#entrySet()} as well as of {@link Map#keySet()}, i.e. they are disconnected sets and modifications applied
+ * to them are not applied to their underlying AbstractDelegatingRegistry.
+ * <p>
+ *
+ * @author Eike Stepper
+ */
+public abstract class DelegatingRegistry<K, V> extends Registry<K, V>
+{
+ private IRegistry<K, V> delegate;
+
+ public DelegatingRegistry(IRegistry<K, V> delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public DelegatingRegistry(IRegistry<K, V> delegate, boolean autoCommit)
+ {
+ super(autoCommit);
+ this.delegate = delegate;
+ }
+
+ @Override
+ public V get(Object key)
+ {
+ V result = getMap().get(key);
+ if (result == null && delegate != null)
+ {
+ result = delegate.get(key);
+ }
+
+ return result;
+ }
+
+ @Override
+ public Set<Entry<K, V>> entrySet()
+ {
+ return mergedEntrySet();
+ }
+
+ @Override
+ public Set<K> keySet()
+ {
+ return mergedKeySet();
+ }
+
+ @Override
+ public Collection<V> values()
+ {
+ return mergedValues();
+ }
+
+ @Override
+ protected V register(K key, V value)
+ {
+ V delegated = delegate != null ? delegate.get(key) : null;
+ V old = getMap().put(key, value);
+ if (old == null)
+ {
+ if (delegated != null)
+ {
+ // Unhidden delegated element now becomes hidden
+ getTransaction().rememberDeregistered(key, delegated);
+ }
+
+ getTransaction().rememberRegistered(key, value);
+ return delegated;
+ }
+
+ getTransaction().rememberDeregistered(key, old);
+ getTransaction().rememberRegistered(key, value);
+ return old;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected V deregister(Object key)
+ {
+ V delegated = delegate != null ? delegate.get(key) : null;
+ V old = getMap().remove(key);
+ if (old != null)
+ {
+ getTransaction().rememberDeregistered((K)key, old);
+ if (delegated != null)
+ {
+ // Hidden delegated element now becomes unhidden
+ getTransaction().rememberRegistered((K)key, delegated);
+ }
+ }
+
+ return old;
+ }
+
+ protected Set<Entry<K, V>> mergedEntrySet()
+ {
+ final Map<K, V> merged = new HashMap<K, V>();
+ if (delegate != null)
+ {
+ merged.putAll(delegate);
+ }
+
+ merged.putAll(getMap());
+ return merged.entrySet();
+ }
+
+ protected Set<K> mergedKeySet()
+ {
+ final Set<K> merged = new HashSet<K>();
+ if (delegate != null)
+ {
+ merged.addAll(delegate.keySet());
+ }
+
+ merged.addAll(getMap().keySet());
+ return merged;
+ }
+
+ protected Collection<V> mergedValues()
+ {
+ final List<V> result = new ArrayList<V>();
+ for (K key : keySet())
+ {
+ result.add(get(key));
+ }
+
+ return result;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java index 577fd47aa8..a65b03216d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java @@ -1,52 +1,52 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public class HashMapDelegatingRegistry<K, V> extends DelegatingRegistry<K, V> -{ - private Map<K, V> map; - - public HashMapDelegatingRegistry(IRegistry<K, V> delegate) - { - super(delegate); - map = new HashMap<K, V>(); - } - - public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity) - { - super(delegate); - map = new HashMap<K, V>(initialCapacity); - } - - public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity, float loadFactor) - { - super(delegate); - map = new HashMap<K, V>(initialCapacity, loadFactor); - } - - public HashMapDelegatingRegistry(IRegistry<K, V> delegate, Map<? extends K, ? extends V> m) - { - super(delegate); - map = new HashMap<K, V>(m); - } - - @Override - protected Map<K, V> getMap() - { - return map; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public class HashMapDelegatingRegistry<K, V> extends DelegatingRegistry<K, V>
+{
+ private Map<K, V> map;
+
+ public HashMapDelegatingRegistry(IRegistry<K, V> delegate)
+ {
+ super(delegate);
+ map = new HashMap<K, V>();
+ }
+
+ public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity)
+ {
+ super(delegate);
+ map = new HashMap<K, V>(initialCapacity);
+ }
+
+ public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity, float loadFactor)
+ {
+ super(delegate);
+ map = new HashMap<K, V>(initialCapacity, loadFactor);
+ }
+
+ public HashMapDelegatingRegistry(IRegistry<K, V> delegate, Map<? extends K, ? extends V> m)
+ {
+ super(delegate);
+ map = new HashMap<K, V>(m);
+ }
+
+ @Override
+ protected Map<K, V> getMap()
+ {
+ return map;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java index 31b343914c..da77b19312 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java @@ -1,48 +1,48 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public class HashMapRegistry<K, V> extends Registry<K, V> -{ - private Map<K, V> map; - - public HashMapRegistry() - { - map = new HashMap<K, V>(); - } - - public HashMapRegistry(int initialCapacity) - { - map = new HashMap<K, V>(initialCapacity); - } - - public HashMapRegistry(int initialCapacity, float loadFactor) - { - map = new HashMap<K, V>(initialCapacity, loadFactor); - } - - public HashMapRegistry(Map<? extends K, ? extends V> m) - { - map = new HashMap<K, V>(m); - } - - @Override - protected Map<K, V> getMap() - { - return map; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public class HashMapRegistry<K, V> extends Registry<K, V>
+{
+ private Map<K, V> map;
+
+ public HashMapRegistry()
+ {
+ map = new HashMap<K, V>();
+ }
+
+ public HashMapRegistry(int initialCapacity)
+ {
+ map = new HashMap<K, V>(initialCapacity);
+ }
+
+ public HashMapRegistry(int initialCapacity, float loadFactor)
+ {
+ map = new HashMap<K, V>(initialCapacity, loadFactor);
+ }
+
+ public HashMapRegistry(Map<? extends K, ? extends V> m)
+ {
+ map = new HashMap<K, V>(m);
+ }
+
+ @Override
+ protected Map<K, V> getMap()
+ {
+ return map;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java index c61854c9f6..0a1365231e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -import org.eclipse.net4j.util.container.IContainer; - -import java.util.Map; - -/** - * @author Eike Stepper - */ -public interface IRegistry<K, V> extends Map<K, V>, IContainer<Map.Entry<K, V>> -{ - public boolean isAutoCommit(); - - public void setAutoCommit(boolean on); - - public void commit(boolean notifications); - - public void commit(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+import org.eclipse.net4j.util.container.IContainer;
+
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IRegistry<K, V> extends Map<K, V>, IContainer<Map.Entry<K, V>>
+{
+ public boolean isAutoCommit();
+
+ public void setAutoCommit(boolean on);
+
+ public void commit(boolean notifications);
+
+ public void commit();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java index 338188e139..2bd61c5e45 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java @@ -1,328 +1,328 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -import org.eclipse.net4j.internal.util.bundle.OM; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.container.Container; -import org.eclipse.net4j.util.container.ContainerEvent; -import org.eclipse.net4j.util.container.IContainerDelta; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -/** - * @author Eike Stepper - */ -public abstract class Registry<K, V> extends Container<Map.Entry<K, V>> implements IRegistry<K, V> -{ - private boolean autoCommit; - - private Transaction transaction; - - protected Registry(boolean autoCommit) - { - this.autoCommit = autoCommit; - } - - protected Registry() - { - this(true); - } - - @Override - public boolean isEmpty() - { - return keySet().isEmpty(); - } - - public int size() - { - return keySet().size(); - } - - public Set<Entry<K, V>> entrySet() - { - return getMap().entrySet(); - } - - public Set<K> keySet() - { - return getMap().keySet(); - } - - public Collection<V> values() - { - return getMap().values(); - } - - public boolean containsKey(Object key) - { - return keySet().contains(key); - } - - public boolean containsValue(Object value) - { - return values().contains(value); - } - - public V get(Object key) - { - return getMap().get(key); - } - - /** - * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. - */ - public synchronized V put(K key, V value) - { - V result = register(key, value); - autoCommit(); - return result; - } - - /** - * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. - */ - public synchronized void putAll(Map<? extends K, ? extends V> t) - { - if (!t.isEmpty()) - { - Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator(); - while (i.hasNext()) - { - Entry<? extends K, ? extends V> e = i.next(); - register(e.getKey(), e.getValue()); - } - - autoCommit(); - } - } - - /** - * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. - */ - public synchronized V remove(Object key) - { - V result = deregister(key); - autoCommit(); - return result; - } - - /** - * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. - */ - public synchronized void clear() - { - if (!isEmpty()) - { - for (Object key : keySet().toArray()) - { - deregister(key); - } - - autoCommit(); - } - } - - @SuppressWarnings("unchecked") - public Entry<K, V>[] getElements() - { - return entrySet().toArray(new Entry[size()]); - } - - public boolean isAutoCommit() - { - return autoCommit; - } - - public void setAutoCommit(boolean autoCommit) - { - this.autoCommit = autoCommit; - } - - public synchronized void commit(boolean notifications) - { - if (transaction != null) - { - if (!transaction.isOwned()) - { - OM.LOG.warn("Committing thread is not owner of transaction: " + Thread.currentThread()); //$NON-NLS-1$ - } - - transaction.commit(notifications); - transaction = null; - notifyAll(); - } - } - - public void commit() - { - commit(true); - } - - @Override - public String toString() - { - return getMap().toString(); - } - - protected V register(K key, V value) - { - Transaction transaction = getTransaction(); - V oldValue = getMap().put(key, value); - if (oldValue != null) - { - transaction.rememberDeregistered(key, oldValue); - } - - transaction.rememberRegistered(key, value); - return oldValue; - } - - @SuppressWarnings("unchecked") - protected V deregister(Object key) - { - V value = getMap().remove(key); - if (value != null) - { - getTransaction().rememberDeregistered((K)key, value); - } - - return value; - } - - protected Transaction getTransaction() - { - for (;;) - { - if (transaction == null) - { - transaction = new Transaction(); - return transaction; - } - - if (transaction.isOwned()) - { - transaction.increaseNesting(); - return transaction; - } - - try - { - wait(); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - } - } - - protected void autoCommit() - { - if (autoCommit) - { - commit(); - } - } - - protected abstract Map<K, V> getMap(); - - /** - * @author Eike Stepper - */ - protected class Transaction - { - private int nesting = 1; - - private ContainerEvent<Map.Entry<K, V>> event; - - private Thread owner; - - public Transaction() - { - owner = Thread.currentThread(); - initEvent(); - } - - private void initEvent() - { - event = newContainerEvent(); - } - - public boolean isOwned() - { - return owner == Thread.currentThread(); - } - - public void increaseNesting() - { - ++nesting; - } - - public void commit(boolean notifications) - { - if (--nesting == 0) - { - if (notifications && !event.isEmpty()) - { - fireEvent(event); - } - - initEvent(); - } - } - - public void rememberRegistered(K key, V value) - { - event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.ADDED); - } - - public void rememberDeregistered(K key, V value) - { - event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.REMOVED); - } - } - - /** - * @author Eike Stepper - */ - private static final class Element<K, V> implements Map.Entry<K, V> - { - private final K key; - - private final V value; - - private Element(K key, V value) - { - this.key = key; - this.value = value; - } - - public K getKey() - { - return key; - } - - public V getValue() - { - return value; - } - - public V setValue(V value) - { - throw new UnsupportedOperationException(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.container.Container;
+import org.eclipse.net4j.util.container.ContainerEvent;
+import org.eclipse.net4j.util.container.IContainerDelta;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class Registry<K, V> extends Container<Map.Entry<K, V>> implements IRegistry<K, V>
+{
+ private boolean autoCommit;
+
+ private Transaction transaction;
+
+ protected Registry(boolean autoCommit)
+ {
+ this.autoCommit = autoCommit;
+ }
+
+ protected Registry()
+ {
+ this(true);
+ }
+
+ @Override
+ public boolean isEmpty()
+ {
+ return keySet().isEmpty();
+ }
+
+ public int size()
+ {
+ return keySet().size();
+ }
+
+ public Set<Entry<K, V>> entrySet()
+ {
+ return getMap().entrySet();
+ }
+
+ public Set<K> keySet()
+ {
+ return getMap().keySet();
+ }
+
+ public Collection<V> values()
+ {
+ return getMap().values();
+ }
+
+ public boolean containsKey(Object key)
+ {
+ return keySet().contains(key);
+ }
+
+ public boolean containsValue(Object value)
+ {
+ return values().contains(value);
+ }
+
+ public V get(Object key)
+ {
+ return getMap().get(key);
+ }
+
+ /**
+ * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
+ */
+ public synchronized V put(K key, V value)
+ {
+ V result = register(key, value);
+ autoCommit();
+ return result;
+ }
+
+ /**
+ * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
+ */
+ public synchronized void putAll(Map<? extends K, ? extends V> t)
+ {
+ if (!t.isEmpty())
+ {
+ Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator();
+ while (i.hasNext())
+ {
+ Entry<? extends K, ? extends V> e = i.next();
+ register(e.getKey(), e.getValue());
+ }
+
+ autoCommit();
+ }
+ }
+
+ /**
+ * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
+ */
+ public synchronized V remove(Object key)
+ {
+ V result = deregister(key);
+ autoCommit();
+ return result;
+ }
+
+ /**
+ * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
+ */
+ public synchronized void clear()
+ {
+ if (!isEmpty())
+ {
+ for (Object key : keySet().toArray())
+ {
+ deregister(key);
+ }
+
+ autoCommit();
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ public Entry<K, V>[] getElements()
+ {
+ return entrySet().toArray(new Entry[size()]);
+ }
+
+ public boolean isAutoCommit()
+ {
+ return autoCommit;
+ }
+
+ public void setAutoCommit(boolean autoCommit)
+ {
+ this.autoCommit = autoCommit;
+ }
+
+ public synchronized void commit(boolean notifications)
+ {
+ if (transaction != null)
+ {
+ if (!transaction.isOwned())
+ {
+ OM.LOG.warn("Committing thread is not owner of transaction: " + Thread.currentThread()); //$NON-NLS-1$
+ }
+
+ transaction.commit(notifications);
+ transaction = null;
+ notifyAll();
+ }
+ }
+
+ public void commit()
+ {
+ commit(true);
+ }
+
+ @Override
+ public String toString()
+ {
+ return getMap().toString();
+ }
+
+ protected V register(K key, V value)
+ {
+ Transaction transaction = getTransaction();
+ V oldValue = getMap().put(key, value);
+ if (oldValue != null)
+ {
+ transaction.rememberDeregistered(key, oldValue);
+ }
+
+ transaction.rememberRegistered(key, value);
+ return oldValue;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected V deregister(Object key)
+ {
+ V value = getMap().remove(key);
+ if (value != null)
+ {
+ getTransaction().rememberDeregistered((K)key, value);
+ }
+
+ return value;
+ }
+
+ protected Transaction getTransaction()
+ {
+ for (;;)
+ {
+ if (transaction == null)
+ {
+ transaction = new Transaction();
+ return transaction;
+ }
+
+ if (transaction.isOwned())
+ {
+ transaction.increaseNesting();
+ return transaction;
+ }
+
+ try
+ {
+ wait();
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ }
+ }
+
+ protected void autoCommit()
+ {
+ if (autoCommit)
+ {
+ commit();
+ }
+ }
+
+ protected abstract Map<K, V> getMap();
+
+ /**
+ * @author Eike Stepper
+ */
+ protected class Transaction
+ {
+ private int nesting = 1;
+
+ private ContainerEvent<Map.Entry<K, V>> event;
+
+ private Thread owner;
+
+ public Transaction()
+ {
+ owner = Thread.currentThread();
+ initEvent();
+ }
+
+ private void initEvent()
+ {
+ event = newContainerEvent();
+ }
+
+ public boolean isOwned()
+ {
+ return owner == Thread.currentThread();
+ }
+
+ public void increaseNesting()
+ {
+ ++nesting;
+ }
+
+ public void commit(boolean notifications)
+ {
+ if (--nesting == 0)
+ {
+ if (notifications && !event.isEmpty())
+ {
+ fireEvent(event);
+ }
+
+ initEvent();
+ }
+ }
+
+ public void rememberRegistered(K key, V value)
+ {
+ event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.ADDED);
+ }
+
+ public void rememberDeregistered(K key, V value)
+ {
+ event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.REMOVED);
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private static final class Element<K, V> implements Map.Entry<K, V>
+ {
+ private final K key;
+
+ private final V value;
+
+ private Element(K key, V value)
+ {
+ this.key = key;
+ this.value = value;
+ }
+
+ public K getKey()
+ {
+ return key;
+ }
+
+ public V getValue()
+ {
+ return value;
+ }
+
+ public V setValue(V value)
+ {
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java index d0eede7756..14469845a1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java @@ -1,31 +1,31 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -/** - * @author Eike Stepper - */ -public final class RegistryUtil -{ - private RegistryUtil() - { - } - - public <K, V> IRegistry<K, V> unmodifiableRegistry(IRegistry<K, V> registry) - { - if (registry instanceof UnmodifiableRegistry<?, ?>) - { - return registry; - } - - return new UnmodifiableRegistry<K, V>(registry); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+/**
+ * @author Eike Stepper
+ */
+public final class RegistryUtil
+{
+ private RegistryUtil()
+ {
+ }
+
+ public <K, V> IRegistry<K, V> unmodifiableRegistry(IRegistry<K, V> registry)
+ {
+ if (registry instanceof UnmodifiableRegistry<?, ?>)
+ {
+ return registry;
+ }
+
+ return new UnmodifiableRegistry<K, V>(registry);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java index 6613137e06..a9b9a18f85 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java @@ -1,150 +1,150 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.registry; - -import org.eclipse.net4j.util.event.IListener; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -public class UnmodifiableRegistry<K, V> implements IRegistry<K, V> -{ - private IRegistry<K, V> delegate; - - public UnmodifiableRegistry(IRegistry<K, V> delegate) - { - this.delegate = delegate; - } - - public void addListener(IListener listener) - { - delegate.addListener(listener); - } - - public void removeListener(IListener listener) - { - delegate.removeListener(listener); - } - - /** - * @since 3.0 - */ - public IListener[] getListeners() - { - return delegate.getListeners(); - } - - /** - * @since 3.0 - */ - public boolean hasListeners() - { - return delegate.hasListeners(); - } - - public V put(K key, V value) - { - throw new UnsupportedOperationException(); - } - - public void putAll(Map<? extends K, ? extends V> t) - { - throw new UnsupportedOperationException(); - } - - public V remove(Object key) - { - throw new UnsupportedOperationException(); - } - - public void clear() - { - throw new UnsupportedOperationException(); - } - - public void commit() - { - throw new UnsupportedOperationException(); - } - - public void commit(boolean notifications) - { - throw new UnsupportedOperationException(); - } - - public void setAutoCommit(boolean on) - { - throw new UnsupportedOperationException(); - } - - public boolean isAutoCommit() - { - return delegate.isAutoCommit(); - } - - public boolean isEmpty() - { - return delegate.isEmpty(); - } - - public int size() - { - return delegate.size(); - } - - public Entry<K, V>[] getElements() - { - return delegate.getElements(); - } - - public V get(Object key) - { - return delegate.get(key); - } - - public boolean containsKey(Object key) - { - return delegate.containsKey(key); - } - - public boolean containsValue(Object value) - { - return delegate.containsValue(value); - } - - public Set<Entry<K, V>> entrySet() - { - return delegate.entrySet(); - } - - public Set<K> keySet() - { - return delegate.keySet(); - } - - public Collection<V> values() - { - return delegate.values(); - } - - @Override - public boolean equals(Object o) - { - return delegate.equals(o); - } - - @Override - public int hashCode() - { - return delegate.hashCode(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.registry;
+
+import org.eclipse.net4j.util.event.IListener;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+
+public class UnmodifiableRegistry<K, V> implements IRegistry<K, V>
+{
+ private IRegistry<K, V> delegate;
+
+ public UnmodifiableRegistry(IRegistry<K, V> delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public void addListener(IListener listener)
+ {
+ delegate.addListener(listener);
+ }
+
+ public void removeListener(IListener listener)
+ {
+ delegate.removeListener(listener);
+ }
+
+ /**
+ * @since 3.0
+ */
+ public IListener[] getListeners()
+ {
+ return delegate.getListeners();
+ }
+
+ /**
+ * @since 3.0
+ */
+ public boolean hasListeners()
+ {
+ return delegate.hasListeners();
+ }
+
+ public V put(K key, V value)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void putAll(Map<? extends K, ? extends V> t)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public V remove(Object key)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void commit()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void commit(boolean notifications)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void setAutoCommit(boolean on)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public boolean isAutoCommit()
+ {
+ return delegate.isAutoCommit();
+ }
+
+ public boolean isEmpty()
+ {
+ return delegate.isEmpty();
+ }
+
+ public int size()
+ {
+ return delegate.size();
+ }
+
+ public Entry<K, V>[] getElements()
+ {
+ return delegate.getElements();
+ }
+
+ public V get(Object key)
+ {
+ return delegate.get(key);
+ }
+
+ public boolean containsKey(Object key)
+ {
+ return delegate.containsKey(key);
+ }
+
+ public boolean containsValue(Object value)
+ {
+ return delegate.containsValue(value);
+ }
+
+ public Set<Entry<K, V>> entrySet()
+ {
+ return delegate.entrySet();
+ }
+
+ public Set<K> keySet()
+ {
+ return delegate.keySet();
+ }
+
+ public Collection<V> values()
+ {
+ return delegate.values();
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ return delegate.equals(o);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return delegate.hashCode();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java index 5d67913bcc..2a27162b50 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java index 129c46362d..18bb25752c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java @@ -1,146 +1,146 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.internal.util.bundle.OM; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -/** - * @author Eike Stepper - */ -public class ChallengeNegotiator extends ChallengeResponseNegotiator -{ - public static final int DEFAULT_TOKEN_LENGTH = 1024; - - private int tokenLength = DEFAULT_TOKEN_LENGTH; - - private IRandomizer randomizer; - - private IUserManager userManager; - - public ChallengeNegotiator() - { - super(true); - } - - public int getTokenLength() - { - return tokenLength; - } - - public void setTokenLength(int tokenLength) - { - this.tokenLength = tokenLength; - } - - public IRandomizer getRandomizer() - { - return randomizer; - } - - public void setRandomizer(IRandomizer randomizer) - { - this.randomizer = randomizer; - } - - public IUserManager getUserManager() - { - return userManager; - } - - public void setUserManager(IUserManager userManager) - { - this.userManager = userManager; - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (tokenLength <= 0) - { - throw new IllegalStateException("tokenLength must be positive"); //$NON-NLS-1$ - } - - if (randomizer == null) - { - throw new IllegalStateException("randomizer == null"); //$NON-NLS-1$ - } - - if (userManager == null) - { - throw new IllegalStateException("userManager == null"); //$NON-NLS-1$ - } - } - - protected byte[] createRandomToken() - { - byte[] token = new byte[tokenLength]; - randomizer.nextBytes(token); - return token; - } - - protected byte[] encryptToken(String userID, byte[] token) throws NegotiationException - { - try - { - return userManager.encrypt(userID, token, getEncryptionAlgorithmName(), getEncryptionSaltBytes(), - getEncryptionIterationCount()); - } - catch (Exception ex) - { - OM.LOG.error("Token encryption failed", ex); //$NON-NLS-1$ - return null; - } - } - - @Override - protected void createChallenge(INegotiationContext context, ByteBuffer challenge) - { - // Create and remember a random token - byte[] randomToken = createRandomToken(); - context.setInfo(randomToken); - - // Set the token into challenge - challenge.putInt(randomToken.length); - challenge.put(randomToken); - } - - @Override - protected boolean handleResponse(INegotiationContext context, ByteBuffer response) - { - // Get remembered random token - byte[] randomToken = (byte[])context.getInfo(); - - // Get userID from response - int size = response.getInt(); - byte[] userIDBytes = new byte[size]; - response.get(userIDBytes); - String userID = new String(userIDBytes); - - // Get crypted token from response - size = response.getInt(); - byte[] responseToken = new byte[size]; - response.get(responseToken); - - // Encrypt the remembered token and compare to crypted token from response - byte[] cryptedToken = encryptToken(userID, randomToken); - boolean success = Arrays.equals(responseToken, cryptedToken); - if (success) - { - context.setUserID(userID); - } - - return success; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.internal.util.bundle.OM;
+
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
+/**
+ * @author Eike Stepper
+ */
+public class ChallengeNegotiator extends ChallengeResponseNegotiator
+{
+ public static final int DEFAULT_TOKEN_LENGTH = 1024;
+
+ private int tokenLength = DEFAULT_TOKEN_LENGTH;
+
+ private IRandomizer randomizer;
+
+ private IUserManager userManager;
+
+ public ChallengeNegotiator()
+ {
+ super(true);
+ }
+
+ public int getTokenLength()
+ {
+ return tokenLength;
+ }
+
+ public void setTokenLength(int tokenLength)
+ {
+ this.tokenLength = tokenLength;
+ }
+
+ public IRandomizer getRandomizer()
+ {
+ return randomizer;
+ }
+
+ public void setRandomizer(IRandomizer randomizer)
+ {
+ this.randomizer = randomizer;
+ }
+
+ public IUserManager getUserManager()
+ {
+ return userManager;
+ }
+
+ public void setUserManager(IUserManager userManager)
+ {
+ this.userManager = userManager;
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (tokenLength <= 0)
+ {
+ throw new IllegalStateException("tokenLength must be positive"); //$NON-NLS-1$
+ }
+
+ if (randomizer == null)
+ {
+ throw new IllegalStateException("randomizer == null"); //$NON-NLS-1$
+ }
+
+ if (userManager == null)
+ {
+ throw new IllegalStateException("userManager == null"); //$NON-NLS-1$
+ }
+ }
+
+ protected byte[] createRandomToken()
+ {
+ byte[] token = new byte[tokenLength];
+ randomizer.nextBytes(token);
+ return token;
+ }
+
+ protected byte[] encryptToken(String userID, byte[] token) throws NegotiationException
+ {
+ try
+ {
+ return userManager.encrypt(userID, token, getEncryptionAlgorithmName(), getEncryptionSaltBytes(),
+ getEncryptionIterationCount());
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error("Token encryption failed", ex); //$NON-NLS-1$
+ return null;
+ }
+ }
+
+ @Override
+ protected void createChallenge(INegotiationContext context, ByteBuffer challenge)
+ {
+ // Create and remember a random token
+ byte[] randomToken = createRandomToken();
+ context.setInfo(randomToken);
+
+ // Set the token into challenge
+ challenge.putInt(randomToken.length);
+ challenge.put(randomToken);
+ }
+
+ @Override
+ protected boolean handleResponse(INegotiationContext context, ByteBuffer response)
+ {
+ // Get remembered random token
+ byte[] randomToken = (byte[])context.getInfo();
+
+ // Get userID from response
+ int size = response.getInt();
+ byte[] userIDBytes = new byte[size];
+ response.get(userIDBytes);
+ String userID = new String(userIDBytes);
+
+ // Get crypted token from response
+ size = response.getInt();
+ byte[] responseToken = new byte[size];
+ response.get(responseToken);
+
+ // Encrypt the remembered token and compare to crypted token from response
+ byte[] cryptedToken = encryptToken(userID, randomToken);
+ boolean success = Arrays.equals(responseToken, cryptedToken);
+ if (success)
+ {
+ context.setUserID(userID);
+ }
+
+ return success;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java index 44b2ed70ac..cacc2b51ea 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java @@ -1,80 +1,80 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.container.IElementProcessor; -import org.eclipse.net4j.util.container.IManagedContainer; - -/** - * @author Eike Stepper - */ -public class ChallengeNegotiatorConfigurer implements IElementProcessor -{ - public ChallengeNegotiatorConfigurer() - { - } - - public Object process(IManagedContainer container, String productGroup, String factoryType, String description, - Object element) - { - if (element instanceof ChallengeNegotiator) - { - ChallengeNegotiator negotiator = (ChallengeNegotiator)element; - if (negotiator.getRandomizer() == null) - { - IRandomizer randomizer = getRandomizer(container, description); - negotiator.setRandomizer(randomizer); - } - - if (negotiator.getUserManager() == null) - { - IUserManager userManager = getUserManager(container, description); - negotiator.setUserManager(userManager); - } - } - - return element; - } - - protected IRandomizer getRandomizer(IManagedContainer container, String description) - { - String productGroup = RandomizerFactory.PRODUCT_GROUP; - String type = getRandomizerType(description); - return (IRandomizer)container.getElement(productGroup, type, getRandomizerDescription(description)); - } - - protected String getRandomizerType(String description) - { - return RandomizerFactory.TYPE; - } - - protected String getRandomizerDescription(String description) - { - return null; - } - - protected IUserManager getUserManager(IManagedContainer container, String description) - { - String productGroup = FileUserManagerFactory.PRODUCT_GROUP; - String type = getUserManagerType(description); - return (IUserManager)container.getElement(productGroup, type, getUserManagerDescription(description)); - } - - protected String getUserManagerType(String description) - { - return FileUserManagerFactory.TYPE; - } - - protected String getUserManagerDescription(String description) - { - return description; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.container.IElementProcessor;
+import org.eclipse.net4j.util.container.IManagedContainer;
+
+/**
+ * @author Eike Stepper
+ */
+public class ChallengeNegotiatorConfigurer implements IElementProcessor
+{
+ public ChallengeNegotiatorConfigurer()
+ {
+ }
+
+ public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
+ Object element)
+ {
+ if (element instanceof ChallengeNegotiator)
+ {
+ ChallengeNegotiator negotiator = (ChallengeNegotiator)element;
+ if (negotiator.getRandomizer() == null)
+ {
+ IRandomizer randomizer = getRandomizer(container, description);
+ negotiator.setRandomizer(randomizer);
+ }
+
+ if (negotiator.getUserManager() == null)
+ {
+ IUserManager userManager = getUserManager(container, description);
+ negotiator.setUserManager(userManager);
+ }
+ }
+
+ return element;
+ }
+
+ protected IRandomizer getRandomizer(IManagedContainer container, String description)
+ {
+ String productGroup = RandomizerFactory.PRODUCT_GROUP;
+ String type = getRandomizerType(description);
+ return (IRandomizer)container.getElement(productGroup, type, getRandomizerDescription(description));
+ }
+
+ protected String getRandomizerType(String description)
+ {
+ return RandomizerFactory.TYPE;
+ }
+
+ protected String getRandomizerDescription(String description)
+ {
+ return null;
+ }
+
+ protected IUserManager getUserManager(IManagedContainer container, String description)
+ {
+ String productGroup = FileUserManagerFactory.PRODUCT_GROUP;
+ String type = getUserManagerType(description);
+ return (IUserManager)container.getElement(productGroup, type, getUserManagerDescription(description));
+ }
+
+ protected String getUserManagerType(String description)
+ {
+ return FileUserManagerFactory.TYPE;
+ }
+
+ protected String getUserManagerDescription(String description)
+ {
+ return description;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java index 9c5551dab4..ac4dd6ab9f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public class ChallengeNegotiatorFactory extends NegotiatorFactory -{ - public static final String TYPE = "challenge"; //$NON-NLS-1$ - - public ChallengeNegotiatorFactory() - { - super(TYPE); - } - - public ChallengeNegotiator create(String description) - { - return new ChallengeNegotiator(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public class ChallengeNegotiatorFactory extends NegotiatorFactory
+{
+ public static final String TYPE = "challenge"; //$NON-NLS-1$
+
+ public ChallengeNegotiatorFactory()
+ {
+ super(TYPE);
+ }
+
+ public ChallengeNegotiator create(String description)
+ {
+ return new ChallengeNegotiator();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java index 7caf1cb1bd..505459cdcf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java @@ -1,200 +1,200 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; -import org.eclipse.net4j.util.fsm.ITransition; - -import java.nio.ByteBuffer; - -/** - * @author Eike Stepper - */ -public abstract class ChallengeResponseNegotiator extends - Negotiator<IChallengeResponse.State, IChallengeResponse.Event> implements IChallengeResponse -{ - private String encryptionAlgorithmName = SecurityUtil.PBE_WITH_MD5_AND_DES; - - private byte[] encryptionSaltBytes = SecurityUtil.DEFAULT_SALT; - - private int encryptionIterationCount = SecurityUtil.DEFAULT_ITERATION_COUNT; - - public ChallengeResponseNegotiator(boolean initiator) - { - super(State.class, Event.class, State.INITIAL, State.SUCCESS, State.FAILURE, Event.START, Event.BUFFER, initiator); - - init(State.INITIAL, Event.START, new Transition() - { - @Override - protected void execute(INegotiationContext context, ByteBuffer NULL) - { - // Create and transmit challenge - ByteBuffer challenge = context.getBuffer(); - createChallenge(context, challenge); - context.transmitBuffer(challenge); - - // Set context state - changeState(context, State.CHALLENGE); - } - }); - - init(State.INITIAL, Event.BUFFER, new Transition() - { - @Override - protected void execute(INegotiationContext context, ByteBuffer challenge) - { - // Handle challenge and transmit response - ByteBuffer response = context.getBuffer(); - handleChallenge(context, challenge, response); - context.transmitBuffer(response); - - // Set context state - changeState(context, State.RESPONSE); - } - }); - - init(State.CHALLENGE, Event.BUFFER, new Transition() - { - @Override - protected void execute(INegotiationContext context, ByteBuffer response) - { - // Handle response - boolean success = handleResponse(context, response); - - // Transmit acknowledgement - ByteBuffer acknowledgement = context.getBuffer(); - acknowledgement.put(success ? ACKNOWLEDGE_SUCCESS : ACKNOWLEDGE_FAILURE); - context.transmitBuffer(acknowledgement); - ConcurrencyUtil.sleep(500); - - // Set context state - changeState(context, success ? State.SUCCESS : State.FAILURE); - } - }); - - init(State.RESPONSE, Event.BUFFER, new Transition() - { - @Override - protected void execute(INegotiationContext context, ByteBuffer acknowledgement) - { - boolean success = acknowledgement.get() == ACKNOWLEDGE_SUCCESS; - changeState(context, success ? State.SUCCESS : State.FAILURE); - handleAcknowledgement(context, success); - } - }); - } - - /** - * @since 2.0 - */ - public String getEncryptionAlgorithmName() - { - return encryptionAlgorithmName; - } - - /** - * @since 2.0 - */ - public void setEncryptionAlgorithmName(String encryptionAlgorithmName) - { - this.encryptionAlgorithmName = encryptionAlgorithmName; - } - - /** - * @since 2.0 - */ - public byte[] getEncryptionSaltBytes() - { - return encryptionSaltBytes; - } - - /** - * @since 2.0 - */ - public void setEncryptionSaltBytes(byte[] encryptionSaltBytes) - { - this.encryptionSaltBytes = encryptionSaltBytes; - } - - /** - * @since 2.0 - */ - public int getEncryptionIterationCount() - { - return encryptionIterationCount; - } - - /** - * @since 2.0 - */ - public void setEncryptionIterationCount(int encryptionIterationCount) - { - this.encryptionIterationCount = encryptionIterationCount; - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - checkState(encryptionAlgorithmName, "encryptionAlgorithmName"); //$NON-NLS-1$ - checkState(encryptionSaltBytes, "encryptionSaltBytes"); //$NON-NLS-1$ - checkState(encryptionSaltBytes.length > 0, "encryptionSaltBytes"); //$NON-NLS-1$ - checkState(encryptionIterationCount > 0, "encryptionIterationCount"); //$NON-NLS-1$ - } - - @Override - protected State getState(INegotiationContext subject) - { - return (State)subject.getState(); - } - - @Override - protected void setState(INegotiationContext subject, State state) - { - subject.setState(state); - } - - protected void createChallenge(INegotiationContext context, ByteBuffer challenge) - { - throw new UnsupportedOperationException(); - } - - protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response) - { - throw new UnsupportedOperationException(); - } - - protected boolean handleResponse(INegotiationContext context, ByteBuffer response) - { - throw new UnsupportedOperationException(); - } - - /** - * @since 2.0 - */ - protected void handleAcknowledgement(INegotiationContext context, boolean success) - { - throw new UnsupportedOperationException(); - } - - /** - * @author Eike Stepper - */ - protected abstract class Transition implements ITransition<State, Event, INegotiationContext, ByteBuffer> - { - public final void execute(INegotiationContext context, State state, Event event, ByteBuffer buffer) - { - execute(context, buffer); - } - - protected abstract void execute(INegotiationContext context, ByteBuffer buffer); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
+import org.eclipse.net4j.util.fsm.ITransition;
+
+import java.nio.ByteBuffer;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class ChallengeResponseNegotiator extends
+ Negotiator<IChallengeResponse.State, IChallengeResponse.Event> implements IChallengeResponse
+{
+ private String encryptionAlgorithmName = SecurityUtil.PBE_WITH_MD5_AND_DES;
+
+ private byte[] encryptionSaltBytes = SecurityUtil.DEFAULT_SALT;
+
+ private int encryptionIterationCount = SecurityUtil.DEFAULT_ITERATION_COUNT;
+
+ public ChallengeResponseNegotiator(boolean initiator)
+ {
+ super(State.class, Event.class, State.INITIAL, State.SUCCESS, State.FAILURE, Event.START, Event.BUFFER, initiator);
+
+ init(State.INITIAL, Event.START, new Transition()
+ {
+ @Override
+ protected void execute(INegotiationContext context, ByteBuffer NULL)
+ {
+ // Create and transmit challenge
+ ByteBuffer challenge = context.getBuffer();
+ createChallenge(context, challenge);
+ context.transmitBuffer(challenge);
+
+ // Set context state
+ changeState(context, State.CHALLENGE);
+ }
+ });
+
+ init(State.INITIAL, Event.BUFFER, new Transition()
+ {
+ @Override
+ protected void execute(INegotiationContext context, ByteBuffer challenge)
+ {
+ // Handle challenge and transmit response
+ ByteBuffer response = context.getBuffer();
+ handleChallenge(context, challenge, response);
+ context.transmitBuffer(response);
+
+ // Set context state
+ changeState(context, State.RESPONSE);
+ }
+ });
+
+ init(State.CHALLENGE, Event.BUFFER, new Transition()
+ {
+ @Override
+ protected void execute(INegotiationContext context, ByteBuffer response)
+ {
+ // Handle response
+ boolean success = handleResponse(context, response);
+
+ // Transmit acknowledgement
+ ByteBuffer acknowledgement = context.getBuffer();
+ acknowledgement.put(success ? ACKNOWLEDGE_SUCCESS : ACKNOWLEDGE_FAILURE);
+ context.transmitBuffer(acknowledgement);
+ ConcurrencyUtil.sleep(500);
+
+ // Set context state
+ changeState(context, success ? State.SUCCESS : State.FAILURE);
+ }
+ });
+
+ init(State.RESPONSE, Event.BUFFER, new Transition()
+ {
+ @Override
+ protected void execute(INegotiationContext context, ByteBuffer acknowledgement)
+ {
+ boolean success = acknowledgement.get() == ACKNOWLEDGE_SUCCESS;
+ changeState(context, success ? State.SUCCESS : State.FAILURE);
+ handleAcknowledgement(context, success);
+ }
+ });
+ }
+
+ /**
+ * @since 2.0
+ */
+ public String getEncryptionAlgorithmName()
+ {
+ return encryptionAlgorithmName;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void setEncryptionAlgorithmName(String encryptionAlgorithmName)
+ {
+ this.encryptionAlgorithmName = encryptionAlgorithmName;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public byte[] getEncryptionSaltBytes()
+ {
+ return encryptionSaltBytes;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void setEncryptionSaltBytes(byte[] encryptionSaltBytes)
+ {
+ this.encryptionSaltBytes = encryptionSaltBytes;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public int getEncryptionIterationCount()
+ {
+ return encryptionIterationCount;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public void setEncryptionIterationCount(int encryptionIterationCount)
+ {
+ this.encryptionIterationCount = encryptionIterationCount;
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ checkState(encryptionAlgorithmName, "encryptionAlgorithmName"); //$NON-NLS-1$
+ checkState(encryptionSaltBytes, "encryptionSaltBytes"); //$NON-NLS-1$
+ checkState(encryptionSaltBytes.length > 0, "encryptionSaltBytes"); //$NON-NLS-1$
+ checkState(encryptionIterationCount > 0, "encryptionIterationCount"); //$NON-NLS-1$
+ }
+
+ @Override
+ protected State getState(INegotiationContext subject)
+ {
+ return (State)subject.getState();
+ }
+
+ @Override
+ protected void setState(INegotiationContext subject, State state)
+ {
+ subject.setState(state);
+ }
+
+ protected void createChallenge(INegotiationContext context, ByteBuffer challenge)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ protected boolean handleResponse(INegotiationContext context, ByteBuffer response)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected void handleAcknowledgement(INegotiationContext context, boolean success)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ protected abstract class Transition implements ITransition<State, Event, INegotiationContext, ByteBuffer>
+ {
+ public final void execute(INegotiationContext context, State state, Event event, ByteBuffer buffer)
+ {
+ execute(context, buffer);
+ }
+
+ protected abstract void execute(INegotiationContext context, ByteBuffer buffer);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java index 0a7297bc1a..001280e4ac 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public class Credentials implements ICredentials -{ - private String userID; - - public Credentials(String userID) - { - this.userID = userID; - } - - public String getUserID() - { - return userID; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public class Credentials implements ICredentials
+{
+ private String userID;
+
+ public Credentials(String userID)
+ {
+ this.userID = userID;
+ }
+
+ public String getUserID()
+ {
+ return userID;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java index 2dca5a17d6..8ba0bda86f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java @@ -1,30 +1,30 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.factory.Factory; -import org.eclipse.net4j.util.factory.ProductCreationException; - -/** - * @author Eike Stepper - * @since 3.0 - */ -public abstract class CredentialsProviderFactory extends Factory -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.security.credentialsProviders"; //$NON-NLS-1$ - - public CredentialsProviderFactory(String type) - { - super(PRODUCT_GROUP, type); - } - - public abstract ICredentialsProvider create(String description) throws ProductCreationException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.factory.Factory;
+import org.eclipse.net4j.util.factory.ProductCreationException;
+
+/**
+ * @author Eike Stepper
+ * @since 3.0
+ */
+public abstract class CredentialsProviderFactory extends Factory
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.security.credentialsProviders"; //$NON-NLS-1$
+
+ public CredentialsProviderFactory(String type)
+ {
+ super(PRODUCT_GROUP, type);
+ }
+
+ public abstract ICredentialsProvider create(String description) throws ProductCreationException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java index e749a7bbba..aa6206657d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java @@ -1,142 +1,142 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.io.IORuntimeException; -import org.eclipse.net4j.util.io.IOUtil; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.MessageFormat; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - -/** - * @author Eike Stepper - */ -public class FileUserManager extends UserManager -{ - protected String fileName; - - public FileUserManager() - { - } - - public String getFileName() - { - return fileName; - } - - public void setFileName(String fileName) - { - this.fileName = fileName; - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (fileName == null) - { - throw new IllegalStateException("fileName == null"); //$NON-NLS-1$ - } - - File file = new File(fileName); - if (file.exists()) - { - if (!file.isFile()) - { - throw new IllegalStateException("Not a file: " + fileName); //$NON-NLS-1$ - } - } - else - { - throw new FileNotFoundException("User manager file not found: " + fileName); - } - } - - @Override - protected void load(Map<String, char[]> users) throws IORuntimeException - { - File file = new File(fileName); - if (!file.exists()) - { - return; - } - - FileInputStream stream = IOUtil.openInputStream(new File(fileName)); - try - { - load(users, stream); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - IOUtil.closeSilent(stream); - } - } - - protected void load(Map<String, char[]> users, InputStream stream) throws IOException - { - Properties properties = new Properties(); - properties.load(stream); - for (Entry<Object, Object> entry : properties.entrySet()) - { - String userID = (String)entry.getKey(); - char[] password = ((String)entry.getValue()).toCharArray(); - users.put(userID, password); - } - } - - @Override - protected void save(Map<String, char[]> users) throws IORuntimeException - { - File file = new File(fileName); - if (!file.exists()) - { - return; - } - - FileOutputStream stream = IOUtil.openOutputStream(new File(fileName)); - try - { - save(users, stream); - } - catch (IOException ex) - { - throw new IORuntimeException(ex); - } - finally - { - IOUtil.closeSilent(stream); - } - } - - protected void save(Map<String, char[]> users, FileOutputStream stream) throws IOException - { - Properties properties = new Properties(); - for (Entry<String, char[]> entry : users.entrySet()) - { - properties.put(entry.getKey(), new String(entry.getValue())); - } - - String comment = MessageFormat.format("User database {0,date} {0,time,HH:mm:ss:SSS}", System.currentTimeMillis()); - properties.store(stream, comment); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.io.IORuntimeException;
+import org.eclipse.net4j.util.io.IOUtil;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.MessageFormat;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Properties;
+
+/**
+ * @author Eike Stepper
+ */
+public class FileUserManager extends UserManager
+{
+ protected String fileName;
+
+ public FileUserManager()
+ {
+ }
+
+ public String getFileName()
+ {
+ return fileName;
+ }
+
+ public void setFileName(String fileName)
+ {
+ this.fileName = fileName;
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (fileName == null)
+ {
+ throw new IllegalStateException("fileName == null"); //$NON-NLS-1$
+ }
+
+ File file = new File(fileName);
+ if (file.exists())
+ {
+ if (!file.isFile())
+ {
+ throw new IllegalStateException("Not a file: " + fileName); //$NON-NLS-1$
+ }
+ }
+ else
+ {
+ throw new FileNotFoundException("User manager file not found: " + fileName);
+ }
+ }
+
+ @Override
+ protected void load(Map<String, char[]> users) throws IORuntimeException
+ {
+ File file = new File(fileName);
+ if (!file.exists())
+ {
+ return;
+ }
+
+ FileInputStream stream = IOUtil.openInputStream(new File(fileName));
+ try
+ {
+ load(users, stream);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ IOUtil.closeSilent(stream);
+ }
+ }
+
+ protected void load(Map<String, char[]> users, InputStream stream) throws IOException
+ {
+ Properties properties = new Properties();
+ properties.load(stream);
+ for (Entry<Object, Object> entry : properties.entrySet())
+ {
+ String userID = (String)entry.getKey();
+ char[] password = ((String)entry.getValue()).toCharArray();
+ users.put(userID, password);
+ }
+ }
+
+ @Override
+ protected void save(Map<String, char[]> users) throws IORuntimeException
+ {
+ File file = new File(fileName);
+ if (!file.exists())
+ {
+ return;
+ }
+
+ FileOutputStream stream = IOUtil.openOutputStream(new File(fileName));
+ try
+ {
+ save(users, stream);
+ }
+ catch (IOException ex)
+ {
+ throw new IORuntimeException(ex);
+ }
+ finally
+ {
+ IOUtil.closeSilent(stream);
+ }
+ }
+
+ protected void save(Map<String, char[]> users, FileOutputStream stream) throws IOException
+ {
+ Properties properties = new Properties();
+ for (Entry<String, char[]> entry : users.entrySet())
+ {
+ properties.put(entry.getKey(), new String(entry.getValue()));
+ }
+
+ String comment = MessageFormat.format("User database {0,date} {0,time,HH:mm:ss:SSS}", System.currentTimeMillis());
+ properties.store(stream, comment);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java index 6c9c7f42bd..437ef9c948 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java @@ -1,33 +1,33 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * TODO Consider file attributes when creating initially empty file - * - * @author Eike Stepper - */ -public class FileUserManagerFactory extends UserManagerFactory -{ - public static final String TYPE = "file"; //$NON-NLS-1$ - - public FileUserManagerFactory() - { - super(TYPE); - } - - public FileUserManager create(String description) - { - FileUserManager userManager = new FileUserManager(); - userManager.setFileName(description); - return userManager; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * TODO Consider file attributes when creating initially empty file
+ *
+ * @author Eike Stepper
+ */
+public class FileUserManagerFactory extends UserManagerFactory
+{
+ public static final String TYPE = "file"; //$NON-NLS-1$
+
+ public FileUserManagerFactory()
+ {
+ super(TYPE);
+ }
+
+ public FileUserManager create(String description)
+ {
+ FileUserManager userManager = new FileUserManager();
+ userManager.setFileName(description);
+ return userManager;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java index 93b0711ef8..9e00189477 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java @@ -1,37 +1,37 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface IChallengeResponse -{ - public static final byte ACKNOWLEDGE_SUCCESS = 1; - - public static final byte ACKNOWLEDGE_FAILURE = 0; - - /** - * @author Eike Stepper - */ - public enum State - { - INITIAL, CHALLENGE, RESPONSE, SUCCESS, FAILURE - } - - /** - * @author Eike Stepper - */ - public enum Event - { - START, BUFFER - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IChallengeResponse
+{
+ public static final byte ACKNOWLEDGE_SUCCESS = 1;
+
+ public static final byte ACKNOWLEDGE_FAILURE = 0;
+
+ /**
+ * @author Eike Stepper
+ */
+ public enum State
+ {
+ INITIAL, CHALLENGE, RESPONSE, SUCCESS, FAILURE
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public enum Event
+ {
+ START, BUFFER
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java index c35e91c72f..80f3c3f4d0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java @@ -1,18 +1,18 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface ICredentials extends IUserAware -{ -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICredentials extends IUserAware
+{
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java index fa811d67f9..b979ca567d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java @@ -1,21 +1,21 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface ICredentialsProvider -{ - public boolean isInteractive(); - - public ICredentials getCredentials(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ICredentialsProvider
+{
+ public boolean isInteractive();
+
+ public ICredentials getCredentials();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java index 0bb7e25f9d..69188fa911 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import java.nio.ByteBuffer; - -/** - * @author Eike Stepper - */ -public interface INegotiationContext -{ - /** - * @since 2.0 - */ - public static final int NO_TIMEOUT = -1; - - public ByteBuffer getBuffer(); - - public void transmitBuffer(ByteBuffer buffer); - - public Receiver getReceiver(); - - public void setReceiver(Receiver receiver); - - public Enum<?> getState(); - - public void setState(Enum<?> state); - - public void setUserID(String userID); - - public Object getInfo(); - - public void setInfo(Object info); - - public void setFinished(boolean success); - - /** - * @since 2.0 - */ - public Enum<?> waitUntilFinished(long timeout); - - /** - * @author Eike Stepper - */ - public interface Receiver - { - public void receiveBuffer(INegotiationContext context, ByteBuffer buffer); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import java.nio.ByteBuffer;
+
+/**
+ * @author Eike Stepper
+ */
+public interface INegotiationContext
+{
+ /**
+ * @since 2.0
+ */
+ public static final int NO_TIMEOUT = -1;
+
+ public ByteBuffer getBuffer();
+
+ public void transmitBuffer(ByteBuffer buffer);
+
+ public Receiver getReceiver();
+
+ public void setReceiver(Receiver receiver);
+
+ public Enum<?> getState();
+
+ public void setState(Enum<?> state);
+
+ public void setUserID(String userID);
+
+ public Object getInfo();
+
+ public void setInfo(Object info);
+
+ public void setFinished(boolean success);
+
+ /**
+ * @since 2.0
+ */
+ public Enum<?> waitUntilFinished(long timeout);
+
+ /**
+ * @author Eike Stepper
+ */
+ public interface Receiver
+ {
+ public void receiveBuffer(INegotiationContext context, ByteBuffer buffer);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java index 1e6e4f4ce2..2005589fac 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java @@ -1,24 +1,24 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface INegotiator -{ - /** - * @since 2.0 - */ - public boolean isInitiator(); - - public void negotiate(INegotiationContext context); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface INegotiator
+{
+ /**
+ * @since 2.0
+ */
+ public boolean isInitiator();
+
+ public void negotiate(INegotiationContext context);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java index eab927f949..4c6f0df6d5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface INegotiatorAware -{ - public INegotiator getNegotiator(); - - public void setNegotiator(INegotiator negotiator); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface INegotiatorAware
+{
+ public INegotiator getNegotiator();
+
+ public void setNegotiator(INegotiator negotiator);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java index d4e1a56eb6..952f9b7901 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface IPasswordCredentials extends ICredentials -{ - public char[] getPassword(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IPasswordCredentials extends ICredentials
+{
+ public char[] getPassword();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java index d67e645aa6..42b92466cb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java @@ -1,19 +1,19 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface IPasswordCredentialsProvider extends ICredentialsProvider -{ - public IPasswordCredentials getCredentials(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IPasswordCredentialsProvider extends ICredentialsProvider
+{
+ public IPasswordCredentials getCredentials();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java index 9bff745410..1883d7d7b1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java @@ -1,37 +1,37 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface IRandomizer -{ - public byte[] generateSeed(int numBytes); - - public boolean nextBoolean(); - - public double nextDouble(); - - public float nextFloat(); - - public double nextGaussian(); - - public int nextInt(); - - public int nextInt(int n); - - public long nextLong(); - - public void nextBytes(byte[] bytes); - - public String nextString(int length, String alphabet); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IRandomizer
+{
+ public byte[] generateSeed(int numBytes);
+
+ public boolean nextBoolean();
+
+ public double nextDouble();
+
+ public float nextFloat();
+
+ public double nextGaussian();
+
+ public int nextInt();
+
+ public int nextInt(int n);
+
+ public long nextLong();
+
+ public void nextBytes(byte[] bytes);
+
+ public String nextString(int length, String alphabet);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java index ba837003e6..c2c68a11e2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java @@ -1,20 +1,20 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public interface IUserAware -{ - public String getUserID(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public interface IUserAware
+{
+ public String getUserID();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java index 9a5e855b85..8f7148c996 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public interface IUserManager -{ - public void addUser(String userID, char[] password); - - public void removeUser(String userID); - - /** - * @since 2.0 - */ - public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count) - throws SecurityException; -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public interface IUserManager
+{
+ public void addUser(String userID, char[] password);
+
+ public void removeUser(String userID);
+
+ /**
+ * @since 2.0
+ */
+ public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count)
+ throws SecurityException;
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java index e8ff0b7b17..235a5942eb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.WrappedException; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * @author Eike Stepper - */ -public abstract class NegotiationContext implements INegotiationContext -{ - private Receiver receiver; - - private Enum<?> state; - - private Object info; - - private CountDownLatch finishedLatch = new CountDownLatch(1); - - public NegotiationContext() - { - } - - public Receiver getReceiver() - { - return receiver; - } - - public void setReceiver(Receiver receiver) - { - this.receiver = receiver; - } - - public Enum<?> getState() - { - return state; - } - - public void setState(Enum<?> state) - { - this.state = state; - } - - public Object getInfo() - { - return info; - } - - public void setInfo(Object info) - { - this.info = info; - } - - public void setFinished(boolean success) - { - if (finishedLatch != null) - { - finishedLatch.countDown(); - } - } - - public Enum<?> waitUntilFinished(long timeout) - { - if (finishedLatch == null) - { - throw new IllegalStateException("finishedLatch == null"); //$NON-NLS-1$ - } - - try - { - if (timeout == NO_TIMEOUT) - { - finishedLatch.await(); - } - else - { - finishedLatch.await(timeout, TimeUnit.MILLISECONDS); - } - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - finally - { - finishedLatch = null; - } - - return state; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.WrappedException;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class NegotiationContext implements INegotiationContext
+{
+ private Receiver receiver;
+
+ private Enum<?> state;
+
+ private Object info;
+
+ private CountDownLatch finishedLatch = new CountDownLatch(1);
+
+ public NegotiationContext()
+ {
+ }
+
+ public Receiver getReceiver()
+ {
+ return receiver;
+ }
+
+ public void setReceiver(Receiver receiver)
+ {
+ this.receiver = receiver;
+ }
+
+ public Enum<?> getState()
+ {
+ return state;
+ }
+
+ public void setState(Enum<?> state)
+ {
+ this.state = state;
+ }
+
+ public Object getInfo()
+ {
+ return info;
+ }
+
+ public void setInfo(Object info)
+ {
+ this.info = info;
+ }
+
+ public void setFinished(boolean success)
+ {
+ if (finishedLatch != null)
+ {
+ finishedLatch.countDown();
+ }
+ }
+
+ public Enum<?> waitUntilFinished(long timeout)
+ {
+ if (finishedLatch == null)
+ {
+ throw new IllegalStateException("finishedLatch == null"); //$NON-NLS-1$
+ }
+
+ try
+ {
+ if (timeout == NO_TIMEOUT)
+ {
+ finishedLatch.await();
+ }
+ else
+ {
+ finishedLatch.await(timeout, TimeUnit.MILLISECONDS);
+ }
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+ finally
+ {
+ finishedLatch = null;
+ }
+
+ return state;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java index 6f6f4b34df..2fb8901411 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public class NegotiationException extends SecurityException -{ - private static final long serialVersionUID = 1L; - - public NegotiationException() - { - } - - public NegotiationException(String s) - { - super(s); - } - - public NegotiationException(Throwable cause) - { - super(cause); - } - - public NegotiationException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public class NegotiationException extends SecurityException
+{
+ private static final long serialVersionUID = 1L;
+
+ public NegotiationException()
+ {
+ }
+
+ public NegotiationException(String s)
+ {
+ super(s);
+ }
+
+ public NegotiationException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public NegotiationException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java index 69495d86a8..e10d2efb1f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java @@ -1,147 +1,147 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.fsm.FiniteStateMachine; - -import java.nio.ByteBuffer; - -/** - * @author Eike Stepper - */ -public abstract class Negotiator<STATE extends Enum<?>, EVENT extends Enum<?>> extends - FiniteStateMachine<STATE, EVENT, INegotiationContext> implements INegotiator, INegotiationContext.Receiver -{ - private transient STATE initialState; - - private transient STATE successState; - - private transient STATE failureState; - - private transient EVENT startEvent; - - private transient EVENT bufferEvent; - - private boolean initiator; - - public Negotiator(Class<STATE> stateEnum, Class<EVENT> eventEnum, STATE initialState, STATE successState, - STATE failureState, EVENT startEvent, EVENT bufferEvent, boolean initiator) - { - super(stateEnum, eventEnum); - if (initialState == null) - { - throw new IllegalStateException("initialState == null"); //$NON-NLS-1$ - } - - if (successState == null) - { - throw new IllegalStateException("successState == null"); //$NON-NLS-1$ - } - - if (failureState == null) - { - throw new IllegalStateException("failureState == null"); //$NON-NLS-1$ - } - - if (startEvent == null) - { - throw new IllegalStateException("startEvent == null"); //$NON-NLS-1$ - } - - if (bufferEvent == null) - { - throw new IllegalStateException("bufferEvent == null"); //$NON-NLS-1$ - } - - this.initialState = initialState; - this.successState = successState; - this.failureState = failureState; - this.startEvent = startEvent; - this.bufferEvent = bufferEvent; - this.initiator = initiator; - } - - public STATE getInitialState() - { - return initialState; - } - - public STATE getSuccessState() - { - return successState; - } - - public STATE getFailureState() - { - return failureState; - } - - public EVENT getBufferEvent() - { - return bufferEvent; - } - - public EVENT getStartEvent() - { - return startEvent; - } - - public boolean isInitiator() - { - return initiator; - } - - public void negotiate(INegotiationContext context) - { - context.setReceiver(this); - context.setState(initialState); - if (initiator) - { - process(context, startEvent, null); - postProcess(context); - } - } - - public void receiveBuffer(INegotiationContext context, ByteBuffer buffer) - { - process(context, bufferEvent, buffer); - postProcess(context); - } - - protected void postProcess(INegotiationContext context) - { - Enum<?> state = context.getState(); - if (state == successState) - { - handleSuccess(context); - } - else if (state == failureState) - { - handleFailure(context); - } - } - - /** - * @since 2.0 - */ - protected void handleSuccess(INegotiationContext context) - { - context.setFinished(true); - } - - /** - * @since 2.0 - */ - protected void handleFailure(INegotiationContext context) - { - context.setFinished(false); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.fsm.FiniteStateMachine;
+
+import java.nio.ByteBuffer;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class Negotiator<STATE extends Enum<?>, EVENT extends Enum<?>> extends
+ FiniteStateMachine<STATE, EVENT, INegotiationContext> implements INegotiator, INegotiationContext.Receiver
+{
+ private transient STATE initialState;
+
+ private transient STATE successState;
+
+ private transient STATE failureState;
+
+ private transient EVENT startEvent;
+
+ private transient EVENT bufferEvent;
+
+ private boolean initiator;
+
+ public Negotiator(Class<STATE> stateEnum, Class<EVENT> eventEnum, STATE initialState, STATE successState,
+ STATE failureState, EVENT startEvent, EVENT bufferEvent, boolean initiator)
+ {
+ super(stateEnum, eventEnum);
+ if (initialState == null)
+ {
+ throw new IllegalStateException("initialState == null"); //$NON-NLS-1$
+ }
+
+ if (successState == null)
+ {
+ throw new IllegalStateException("successState == null"); //$NON-NLS-1$
+ }
+
+ if (failureState == null)
+ {
+ throw new IllegalStateException("failureState == null"); //$NON-NLS-1$
+ }
+
+ if (startEvent == null)
+ {
+ throw new IllegalStateException("startEvent == null"); //$NON-NLS-1$
+ }
+
+ if (bufferEvent == null)
+ {
+ throw new IllegalStateException("bufferEvent == null"); //$NON-NLS-1$
+ }
+
+ this.initialState = initialState;
+ this.successState = successState;
+ this.failureState = failureState;
+ this.startEvent = startEvent;
+ this.bufferEvent = bufferEvent;
+ this.initiator = initiator;
+ }
+
+ public STATE getInitialState()
+ {
+ return initialState;
+ }
+
+ public STATE getSuccessState()
+ {
+ return successState;
+ }
+
+ public STATE getFailureState()
+ {
+ return failureState;
+ }
+
+ public EVENT getBufferEvent()
+ {
+ return bufferEvent;
+ }
+
+ public EVENT getStartEvent()
+ {
+ return startEvent;
+ }
+
+ public boolean isInitiator()
+ {
+ return initiator;
+ }
+
+ public void negotiate(INegotiationContext context)
+ {
+ context.setReceiver(this);
+ context.setState(initialState);
+ if (initiator)
+ {
+ process(context, startEvent, null);
+ postProcess(context);
+ }
+ }
+
+ public void receiveBuffer(INegotiationContext context, ByteBuffer buffer)
+ {
+ process(context, bufferEvent, buffer);
+ postProcess(context);
+ }
+
+ protected void postProcess(INegotiationContext context)
+ {
+ Enum<?> state = context.getState();
+ if (state == successState)
+ {
+ handleSuccess(context);
+ }
+ else if (state == failureState)
+ {
+ handleFailure(context);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected void handleSuccess(INegotiationContext context)
+ {
+ context.setFinished(true);
+ }
+
+ /**
+ * @since 2.0
+ */
+ protected void handleFailure(INegotiationContext context)
+ {
+ context.setFinished(false);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java index 0873c7b184..c9c2c4851f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.factory.Factory; - -/** - * @author Eike Stepper - */ -public abstract class NegotiatorFactory extends Factory -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.Negotiators"; //$NON-NLS-1$ - - public NegotiatorFactory(String type) - { - super(PRODUCT_GROUP, type); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.factory.Factory;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class NegotiatorFactory extends Factory
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.Negotiators"; //$NON-NLS-1$
+
+ public NegotiatorFactory(String type)
+ {
+ super(PRODUCT_GROUP, type);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java index d0e310b331..72f80b455c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java @@ -1,35 +1,35 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public class PasswordCredentials extends Credentials implements IPasswordCredentials -{ - private char[] password; - - public PasswordCredentials(String userID, char[] password) - { - super(userID); - this.password = password; - } - - public char[] getPassword() - { - return password; - } - - public void setPassword(char[] password) - { - this.password = password; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public class PasswordCredentials extends Credentials implements IPasswordCredentials
+{
+ private char[] password;
+
+ public PasswordCredentials(String userID, char[] password)
+ {
+ super(userID);
+ this.password = password;
+ }
+
+ public char[] getPassword()
+ {
+ return password;
+ }
+
+ public void setPassword(char[] password)
+ {
+ this.password = password;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java index 7f9eadf8ec..1dac8f502a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java @@ -1,103 +1,103 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public class PasswordCredentialsProvider implements IPasswordCredentialsProvider -{ - private IPasswordCredentials credentials; - - /** - * @since 3.1 - */ - public PasswordCredentialsProvider() - { - } - - public PasswordCredentialsProvider(IPasswordCredentials credentials) - { - this.credentials = credentials; - } - - /** - * @since 2.0 - */ - public PasswordCredentialsProvider(String userID, char[] password) - { - this(new PasswordCredentials(userID, password)); - } - - /** - * @since 2.0 - */ - public PasswordCredentialsProvider(String userID, String password) - { - this(userID, password.toCharArray()); - } - - public boolean isInteractive() - { - return false; - } - - public IPasswordCredentials getCredentials() - { - return credentials; - } - - /** - * @since 3.1 - */ - public void setCredentials(IPasswordCredentials credentials) - { - this.credentials = credentials; - } - - /** - * @author Eike Stepper - * @since 3.1 - */ - public static class Delegating extends PasswordCredentialsProvider - { - private IPasswordCredentialsProvider delegate; - - public Delegating(IPasswordCredentialsProvider delegate) - { - this.delegate = delegate; - } - - public IPasswordCredentialsProvider getDelegate() - { - return delegate; - } - - @Override - public boolean isInteractive() - { - return delegate.isInteractive(); - } - - @Override - public IPasswordCredentials getCredentials() - { - IPasswordCredentials credentials = super.getCredentials(); - if (credentials == null) - { - credentials = delegate.getCredentials(); - setCredentials(credentials); - } - - return credentials; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public class PasswordCredentialsProvider implements IPasswordCredentialsProvider
+{
+ private IPasswordCredentials credentials;
+
+ /**
+ * @since 3.1
+ */
+ public PasswordCredentialsProvider()
+ {
+ }
+
+ public PasswordCredentialsProvider(IPasswordCredentials credentials)
+ {
+ this.credentials = credentials;
+ }
+
+ /**
+ * @since 2.0
+ */
+ public PasswordCredentialsProvider(String userID, char[] password)
+ {
+ this(new PasswordCredentials(userID, password));
+ }
+
+ /**
+ * @since 2.0
+ */
+ public PasswordCredentialsProvider(String userID, String password)
+ {
+ this(userID, password.toCharArray());
+ }
+
+ public boolean isInteractive()
+ {
+ return false;
+ }
+
+ public IPasswordCredentials getCredentials()
+ {
+ return credentials;
+ }
+
+ /**
+ * @since 3.1
+ */
+ public void setCredentials(IPasswordCredentials credentials)
+ {
+ this.credentials = credentials;
+ }
+
+ /**
+ * @author Eike Stepper
+ * @since 3.1
+ */
+ public static class Delegating extends PasswordCredentialsProvider
+ {
+ private IPasswordCredentialsProvider delegate;
+
+ public Delegating(IPasswordCredentialsProvider delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ public IPasswordCredentialsProvider getDelegate()
+ {
+ return delegate;
+ }
+
+ @Override
+ public boolean isInteractive()
+ {
+ return delegate.isInteractive();
+ }
+
+ @Override
+ public IPasswordCredentials getCredentials()
+ {
+ IPasswordCredentials credentials = super.getCredentials();
+ if (credentials == null)
+ {
+ credentials = delegate.getCredentials();
+ setCredentials(credentials);
+ }
+
+ return credentials;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java index 7d32063da9..f38b48e041 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java @@ -1,188 +1,188 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.security.SecureRandom; - -/** - * @author Eike Stepper - */ -public class Randomizer extends Lifecycle implements IRandomizer -{ - public static final String ALGORITHM_SHA1PRNG = "SHA1PRNG"; //$NON-NLS-1$ - - public static final String DEFAULT_ALGORITHM_NAME = ALGORITHM_SHA1PRNG; - - private String algorithmName = DEFAULT_ALGORITHM_NAME; - - private String providerName; - - @ExcludeFromDump - private byte[] seed; - - @ExcludeFromDump - private transient SecureRandom secureRandom; - - public Randomizer() - { - } - - public synchronized String getAlgorithmName() - { - return algorithmName; - } - - public synchronized void setAlgorithmName(String algorithmName) - { - this.algorithmName = algorithmName; - } - - public synchronized String getProviderName() - { - return providerName; - } - - public synchronized void setProviderName(String providerName) - { - this.providerName = providerName; - } - - public synchronized void setSeed(byte[] seed) - { - this.seed = seed; - if (isActive()) - { - setSeed(); - } - } - - public synchronized void setSeed(long seed) - { - setSeed(String.valueOf(seed).getBytes()); - } - - public synchronized boolean nextBoolean() - { - checkActive(); - return secureRandom.nextBoolean(); - } - - public synchronized double nextDouble() - { - checkActive(); - return secureRandom.nextDouble(); - } - - public synchronized float nextFloat() - { - checkActive(); - return secureRandom.nextFloat(); - } - - public synchronized double nextGaussian() - { - checkActive(); - return secureRandom.nextGaussian(); - } - - public synchronized int nextInt() - { - checkActive(); - return secureRandom.nextInt(); - } - - public synchronized int nextInt(int n) - { - checkActive(); - return secureRandom.nextInt(n); - } - - public synchronized long nextLong() - { - checkActive(); - return secureRandom.nextLong(); - } - - public synchronized byte[] generateSeed(int numBytes) - { - checkActive(); - return secureRandom.generateSeed(numBytes); - } - - public synchronized String getAlgorithm() - { - checkActive(); - return secureRandom.getAlgorithm(); - } - - public synchronized void nextBytes(byte[] bytes) - { - checkActive(); - secureRandom.nextBytes(bytes); - } - - public synchronized String nextString(int length, String alphabet) - { - checkActive(); - int n = alphabet.length(); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < length; i++) - { - int pos = nextInt(n); - char c = alphabet.charAt(pos); - builder.append(c); - } - - return builder.toString(); - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - checkState(algorithmName, "algorithmName"); //$NON-NLS-1$ - if (seed == null) - { - setSeed(System.currentTimeMillis()); - } - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - if (providerName == null) - { - secureRandom = SecureRandom.getInstance(algorithmName); - } - else - { - secureRandom = SecureRandom.getInstance(algorithmName, providerName); - } - - setSeed(); - } - - @Override - protected void doDeactivate() throws Exception - { - secureRandom = null; - super.doDeactivate(); - } - - private void setSeed() - { - secureRandom.setSeed(seed); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.security.SecureRandom;
+
+/**
+ * @author Eike Stepper
+ */
+public class Randomizer extends Lifecycle implements IRandomizer
+{
+ public static final String ALGORITHM_SHA1PRNG = "SHA1PRNG"; //$NON-NLS-1$
+
+ public static final String DEFAULT_ALGORITHM_NAME = ALGORITHM_SHA1PRNG;
+
+ private String algorithmName = DEFAULT_ALGORITHM_NAME;
+
+ private String providerName;
+
+ @ExcludeFromDump
+ private byte[] seed;
+
+ @ExcludeFromDump
+ private transient SecureRandom secureRandom;
+
+ public Randomizer()
+ {
+ }
+
+ public synchronized String getAlgorithmName()
+ {
+ return algorithmName;
+ }
+
+ public synchronized void setAlgorithmName(String algorithmName)
+ {
+ this.algorithmName = algorithmName;
+ }
+
+ public synchronized String getProviderName()
+ {
+ return providerName;
+ }
+
+ public synchronized void setProviderName(String providerName)
+ {
+ this.providerName = providerName;
+ }
+
+ public synchronized void setSeed(byte[] seed)
+ {
+ this.seed = seed;
+ if (isActive())
+ {
+ setSeed();
+ }
+ }
+
+ public synchronized void setSeed(long seed)
+ {
+ setSeed(String.valueOf(seed).getBytes());
+ }
+
+ public synchronized boolean nextBoolean()
+ {
+ checkActive();
+ return secureRandom.nextBoolean();
+ }
+
+ public synchronized double nextDouble()
+ {
+ checkActive();
+ return secureRandom.nextDouble();
+ }
+
+ public synchronized float nextFloat()
+ {
+ checkActive();
+ return secureRandom.nextFloat();
+ }
+
+ public synchronized double nextGaussian()
+ {
+ checkActive();
+ return secureRandom.nextGaussian();
+ }
+
+ public synchronized int nextInt()
+ {
+ checkActive();
+ return secureRandom.nextInt();
+ }
+
+ public synchronized int nextInt(int n)
+ {
+ checkActive();
+ return secureRandom.nextInt(n);
+ }
+
+ public synchronized long nextLong()
+ {
+ checkActive();
+ return secureRandom.nextLong();
+ }
+
+ public synchronized byte[] generateSeed(int numBytes)
+ {
+ checkActive();
+ return secureRandom.generateSeed(numBytes);
+ }
+
+ public synchronized String getAlgorithm()
+ {
+ checkActive();
+ return secureRandom.getAlgorithm();
+ }
+
+ public synchronized void nextBytes(byte[] bytes)
+ {
+ checkActive();
+ secureRandom.nextBytes(bytes);
+ }
+
+ public synchronized String nextString(int length, String alphabet)
+ {
+ checkActive();
+ int n = alphabet.length();
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < length; i++)
+ {
+ int pos = nextInt(n);
+ char c = alphabet.charAt(pos);
+ builder.append(c);
+ }
+
+ return builder.toString();
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ checkState(algorithmName, "algorithmName"); //$NON-NLS-1$
+ if (seed == null)
+ {
+ setSeed(System.currentTimeMillis());
+ }
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ if (providerName == null)
+ {
+ secureRandom = SecureRandom.getInstance(algorithmName);
+ }
+ else
+ {
+ secureRandom = SecureRandom.getInstance(algorithmName, providerName);
+ }
+
+ setSeed();
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ secureRandom = null;
+ super.doDeactivate();
+ }
+
+ private void setSeed()
+ {
+ secureRandom.setSeed(seed);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java index bb8a33a033..0e0b806264 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java @@ -1,40 +1,40 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.factory.Factory; -import org.eclipse.net4j.util.factory.ProductCreationException; - -/** - * @author Eike Stepper - */ -public class RandomizerFactory extends Factory -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.randomizers"; //$NON-NLS-1$ - - public static final String TYPE = "default"; //$NON-NLS-1$ - - public RandomizerFactory() - { - super(PRODUCT_GROUP, TYPE); - } - - public Randomizer create(String description) throws ProductCreationException - { - Randomizer randomizer = new Randomizer(); - if (description != null) - { - randomizer.setAlgorithmName(description); - } - - return randomizer; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.factory.Factory;
+import org.eclipse.net4j.util.factory.ProductCreationException;
+
+/**
+ * @author Eike Stepper
+ */
+public class RandomizerFactory extends Factory
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.randomizers"; //$NON-NLS-1$
+
+ public static final String TYPE = "default"; //$NON-NLS-1$
+
+ public RandomizerFactory()
+ {
+ super(PRODUCT_GROUP, TYPE);
+ }
+
+ public Randomizer create(String description) throws ProductCreationException
+ {
+ Randomizer randomizer = new Randomizer();
+ if (description != null)
+ {
+ randomizer.setAlgorithmName(description);
+ }
+
+ return randomizer;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java index 88f015fc3a..81eb488055 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java @@ -1,99 +1,99 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import java.nio.ByteBuffer; - -/** - * @author Eike Stepper - */ -public class ResponseNegotiator extends ChallengeResponseNegotiator -{ - private IPasswordCredentialsProvider credentialsProvider; - - public ResponseNegotiator() - { - super(false); - } - - public IPasswordCredentialsProvider getCredentialsProvider() - { - return credentialsProvider; - } - - public void setCredentialsProvider(IPasswordCredentialsProvider credentialsProvider) - { - this.credentialsProvider = credentialsProvider; - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (credentialsProvider == null) - { - throw new IllegalStateException("credentialsProvider == null"); //$NON-NLS-1$ - } - } - - @Override - protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response) - { - // Get random token from challenge - int size = challenge.getInt(); - byte[] randomToken = new byte[size]; - challenge.get(randomToken); - - // Get credentials and encrypt token - IPasswordCredentials credentials = credentialsProvider.getCredentials(); - String userID = credentials.getUserID(); - context.setUserID(userID); - - // Set userID into response - byte[] userIDBytes = userID.getBytes(); - response.putInt(userIDBytes.length); - response.put(userIDBytes); - - // Set crypted token into response - byte[] cryptedToken = encryptToken(credentials.getPassword(), randomToken); - response.putInt(cryptedToken.length); - response.put(cryptedToken); - } - - /** - * @since 2.0 - */ - @Override - protected void handleAcknowledgement(INegotiationContext context, boolean success) - { - if (!success) - { - throw new NegotiationException("Negotiation failed"); //$NON-NLS-1$ - } - } - - protected byte[] encryptToken(char[] password, byte[] token) - { - try - { - return SecurityUtil.encrypt(token, password, getEncryptionAlgorithmName(), getEncryptionSaltBytes(), - getEncryptionIterationCount()); - } - catch (RuntimeException ex) - { - throw ex; - } - catch (Exception ex) - { - throw new SecurityException(ex); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import java.nio.ByteBuffer;
+
+/**
+ * @author Eike Stepper
+ */
+public class ResponseNegotiator extends ChallengeResponseNegotiator
+{
+ private IPasswordCredentialsProvider credentialsProvider;
+
+ public ResponseNegotiator()
+ {
+ super(false);
+ }
+
+ public IPasswordCredentialsProvider getCredentialsProvider()
+ {
+ return credentialsProvider;
+ }
+
+ public void setCredentialsProvider(IPasswordCredentialsProvider credentialsProvider)
+ {
+ this.credentialsProvider = credentialsProvider;
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (credentialsProvider == null)
+ {
+ throw new IllegalStateException("credentialsProvider == null"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response)
+ {
+ // Get random token from challenge
+ int size = challenge.getInt();
+ byte[] randomToken = new byte[size];
+ challenge.get(randomToken);
+
+ // Get credentials and encrypt token
+ IPasswordCredentials credentials = credentialsProvider.getCredentials();
+ String userID = credentials.getUserID();
+ context.setUserID(userID);
+
+ // Set userID into response
+ byte[] userIDBytes = userID.getBytes();
+ response.putInt(userIDBytes.length);
+ response.put(userIDBytes);
+
+ // Set crypted token into response
+ byte[] cryptedToken = encryptToken(credentials.getPassword(), randomToken);
+ response.putInt(cryptedToken.length);
+ response.put(cryptedToken);
+ }
+
+ /**
+ * @since 2.0
+ */
+ @Override
+ protected void handleAcknowledgement(INegotiationContext context, boolean success)
+ {
+ if (!success)
+ {
+ throw new NegotiationException("Negotiation failed"); //$NON-NLS-1$
+ }
+ }
+
+ protected byte[] encryptToken(char[] password, byte[] token)
+ {
+ try
+ {
+ return SecurityUtil.encrypt(token, password, getEncryptionAlgorithmName(), getEncryptionSaltBytes(),
+ getEncryptionIterationCount());
+ }
+ catch (RuntimeException ex)
+ {
+ throw ex;
+ }
+ catch (Exception ex)
+ {
+ throw new SecurityException(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java index 5a8e73c861..21179215c2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -/** - * @author Eike Stepper - */ -public class ResponseNegotiatorFactory extends NegotiatorFactory -{ - public static final String TYPE = "response"; //$NON-NLS-1$ - - public ResponseNegotiatorFactory() - { - super(TYPE); - } - - public ResponseNegotiator create(String description) - { - return new ResponseNegotiator(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+/**
+ * @author Eike Stepper
+ */
+public class ResponseNegotiatorFactory extends NegotiatorFactory
+{
+ public static final String TYPE = "response"; //$NON-NLS-1$
+
+ public ResponseNegotiatorFactory()
+ {
+ super(TYPE);
+ }
+
+ public ResponseNegotiator create(String description)
+ {
+ return new ResponseNegotiator();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java index 046db3cf2a..163b4e9f0d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java @@ -1,57 +1,57 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.container.IElementProcessor; -import org.eclipse.net4j.util.container.IManagedContainer; - -/** - * @author Eike Stepper - * @since 2.0 - */ -public abstract class ResponseNegotiatorInjector implements IElementProcessor -{ - private INegotiator negotiator; - - public ResponseNegotiatorInjector(INegotiator negotiator) - { - this.negotiator = negotiator; - } - - public INegotiator getNegotiator() - { - return negotiator; - } - - public Object process(IManagedContainer container, String productGroup, String factoryType, String description, - Object element) - { - if (element instanceof INegotiatorAware) - { - INegotiatorAware negotiatorAware = (INegotiatorAware)element; - if (negotiatorAware.getNegotiator() == null) - { - if (filterElement(productGroup, factoryType, description, negotiatorAware)) - { - if (negotiator != null) - { - negotiatorAware.setNegotiator(negotiator); - } - } - } - } - - return element; - } - - protected abstract boolean filterElement(String productGroup, String factoryType, String description, - INegotiatorAware negotiatorAware); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.container.IElementProcessor;
+import org.eclipse.net4j.util.container.IManagedContainer;
+
+/**
+ * @author Eike Stepper
+ * @since 2.0
+ */
+public abstract class ResponseNegotiatorInjector implements IElementProcessor
+{
+ private INegotiator negotiator;
+
+ public ResponseNegotiatorInjector(INegotiator negotiator)
+ {
+ this.negotiator = negotiator;
+ }
+
+ public INegotiator getNegotiator()
+ {
+ return negotiator;
+ }
+
+ public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
+ Object element)
+ {
+ if (element instanceof INegotiatorAware)
+ {
+ INegotiatorAware negotiatorAware = (INegotiatorAware)element;
+ if (negotiatorAware.getNegotiator() == null)
+ {
+ if (filterElement(productGroup, factoryType, description, negotiatorAware))
+ {
+ if (negotiator != null)
+ {
+ negotiatorAware.setNegotiator(negotiator);
+ }
+ }
+ }
+ }
+
+ return element;
+ }
+
+ protected abstract boolean filterElement(String productGroup, String factoryType, String description,
+ INegotiatorAware negotiatorAware);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java index deade6bc65..cb9fdbf74e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java @@ -1,70 +1,70 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.PBEParameterSpec; - -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; - -/** - * @author Eike Stepper - */ -public final class SecurityUtil -{ - public static final String PBE_WITH_MD5_AND_DES = "PBEWithMD5AndDES"; //$NON-NLS-1$ - - /** - * @since 2.0 - */ - public static final byte[] DEFAULT_SALT = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, - (byte)0xee, (byte)0x99 }; - - /** - * @since 2.0 - */ - public static final int DEFAULT_ITERATION_COUNT = 20; - - private SecurityUtil() - { - } - - /** - * @since 2.0 - */ - public static byte[] encrypt(byte[] data, char[] password, String algorithmName, byte[] salt, int count) - throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, - InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException - { - // Create PBE parameter set - PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count); - PBEKeySpec pbeKeySpec = new PBEKeySpec(password); - SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithmName); - SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); - - // Create PBE Cipher - Cipher pbeCipher = Cipher.getInstance(algorithmName); - - // Initialize PBE Cipher with key and parameters - pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); - - return pbeCipher.doFinal(data); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.SecretKey;
+import javax.crypto.SecretKeyFactory;
+import javax.crypto.spec.PBEKeySpec;
+import javax.crypto.spec.PBEParameterSpec;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+
+/**
+ * @author Eike Stepper
+ */
+public final class SecurityUtil
+{
+ public static final String PBE_WITH_MD5_AND_DES = "PBEWithMD5AndDES"; //$NON-NLS-1$
+
+ /**
+ * @since 2.0
+ */
+ public static final byte[] DEFAULT_SALT = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8,
+ (byte)0xee, (byte)0x99 };
+
+ /**
+ * @since 2.0
+ */
+ public static final int DEFAULT_ITERATION_COUNT = 20;
+
+ private SecurityUtil()
+ {
+ }
+
+ /**
+ * @since 2.0
+ */
+ public static byte[] encrypt(byte[] data, char[] password, String algorithmName, byte[] salt, int count)
+ throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
+ InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
+ {
+ // Create PBE parameter set
+ PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
+ PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
+ SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithmName);
+ SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
+
+ // Create PBE Cipher
+ Cipher pbeCipher = Cipher.getInstance(algorithmName);
+
+ // Initialize PBE Cipher with key and parameters
+ pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
+
+ return pbeCipher.doFinal(data);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java index 7295605613..fe9b29e469 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java @@ -1,98 +1,98 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.io.IORuntimeException; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Eike Stepper - */ -public class UserManager extends Lifecycle implements IUserManager -{ - @ExcludeFromDump - protected transient Map<String, char[]> users = new HashMap<String, char[]>(); - - public UserManager() - { - } - - public synchronized void addUser(String userID, char[] password) - { - users.put(userID, password); - save(users); - } - - public synchronized void removeUser(String userID) - { - if (users.remove(userID) != null) - { - save(users); - } - } - - /** - * @since 2.0 - */ - public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count) - throws SecurityException - { - char[] password; - synchronized (this) - { - password = users.get(userID); - } - - if (password == null) - { - throw new SecurityException("No such user: " + userID); //$NON-NLS-1$ - } - - try - { - return SecurityUtil.encrypt(data, password, algorithmName, salt, count); - } - catch (RuntimeException ex) - { - throw ex; - } - catch (Exception ex) - { - throw new SecurityException(ex); - } - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - load(users); - } - - @Override - protected void doDeactivate() throws Exception - { - users.clear(); - super.doDeactivate(); - } - - protected void load(Map<String, char[]> users) throws IORuntimeException - { - } - - protected void save(Map<String, char[]> users) throws IORuntimeException - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.io.IORuntimeException;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author Eike Stepper
+ */
+public class UserManager extends Lifecycle implements IUserManager
+{
+ @ExcludeFromDump
+ protected transient Map<String, char[]> users = new HashMap<String, char[]>();
+
+ public UserManager()
+ {
+ }
+
+ public synchronized void addUser(String userID, char[] password)
+ {
+ users.put(userID, password);
+ save(users);
+ }
+
+ public synchronized void removeUser(String userID)
+ {
+ if (users.remove(userID) != null)
+ {
+ save(users);
+ }
+ }
+
+ /**
+ * @since 2.0
+ */
+ public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count)
+ throws SecurityException
+ {
+ char[] password;
+ synchronized (this)
+ {
+ password = users.get(userID);
+ }
+
+ if (password == null)
+ {
+ throw new SecurityException("No such user: " + userID); //$NON-NLS-1$
+ }
+
+ try
+ {
+ return SecurityUtil.encrypt(data, password, algorithmName, salt, count);
+ }
+ catch (RuntimeException ex)
+ {
+ throw ex;
+ }
+ catch (Exception ex)
+ {
+ throw new SecurityException(ex);
+ }
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ load(users);
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ users.clear();
+ super.doDeactivate();
+ }
+
+ protected void load(Map<String, char[]> users) throws IORuntimeException
+ {
+ }
+
+ protected void save(Map<String, char[]> users) throws IORuntimeException
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java index 0a9c4424d7..414d1ed3c6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.security; - -import org.eclipse.net4j.util.factory.Factory; - -/** - * @author Eike Stepper - */ -public abstract class UserManagerFactory extends Factory -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.userManagers"; //$NON-NLS-1$ - - public UserManagerFactory(String type) - { - super(PRODUCT_GROUP, type); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.security;
+
+import org.eclipse.net4j.util.factory.Factory;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class UserManagerFactory extends Factory
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.userManagers"; //$NON-NLS-1$
+
+ public UserManagerFactory(String type)
+ {
+ super(PRODUCT_GROUP, type);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java index dd7e440c3f..5a1ca1cf9f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java index 9bd6187e86..5b707b97d4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java @@ -1,27 +1,27 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.transaction; - -/** - * @author Eike Stepper - */ -public interface ITransaction<CONTEXT> -{ - public boolean isActive(); - - public CONTEXT getContext(); - - public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException; - - public void commit(); - - public void rollback(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.transaction;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ITransaction<CONTEXT>
+{
+ public boolean isActive();
+
+ public CONTEXT getContext();
+
+ public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException;
+
+ public void commit();
+
+ public void rollback();
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java index a4babb2276..229a8b53ed 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java @@ -1,23 +1,23 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.transaction; - -/** - * @author Eike Stepper - */ -public interface ITransactionalOperation<CONTEXT> -{ - public void phase1(CONTEXT context) throws Exception; - - public void phase2(CONTEXT context); - - public void undoPhase1(CONTEXT context); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.transaction;
+
+/**
+ * @author Eike Stepper
+ */
+public interface ITransactionalOperation<CONTEXT>
+{
+ public void phase1(CONTEXT context) throws Exception;
+
+ public void phase2(CONTEXT context);
+
+ public void undoPhase1(CONTEXT context);
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java index 0fcaa45037..cef3e57673 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java @@ -1,102 +1,102 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.transaction; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Eike Stepper - */ -public class Transaction<CONTEXT> implements ITransaction<CONTEXT> -{ - private List<ITransactionalOperation<CONTEXT>> operations = new ArrayList<ITransactionalOperation<CONTEXT>>(); - - private CONTEXT context; - - private boolean undoPhase1OnRollback; - - public Transaction(CONTEXT context, boolean undoPhase1OnRollback) - { - this.context = context; - this.undoPhase1OnRollback = undoPhase1OnRollback; - } - - public Transaction(CONTEXT context) - { - this(context, true); - } - - public boolean isUndoPhase1OnRollback() - { - return undoPhase1OnRollback; - } - - public boolean isActive() - { - return operations != null; - } - - public CONTEXT getContext() - { - return context; - } - - public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException - { - if (!isActive()) - { - throw new TransactionException("Transaction inactive"); //$NON-NLS-1$ - } - - try - { - operation.phase1(context); - operations.add(operation); - } - catch (RuntimeException ex) - { - rollback(); - throw ex; - } - catch (Exception ex) - { - rollback(); - throw new TransactionException(ex); - } - } - - public void commit() - { - for (ITransactionalOperation<CONTEXT> operation : end()) - { - operation.phase2(context); - } - } - - public void rollback() - { - if (undoPhase1OnRollback) - { - for (ITransactionalOperation<CONTEXT> operation : end()) - { - operation.undoPhase1(context); - } - } - } - - private List<ITransactionalOperation<CONTEXT>> end() - { - List<ITransactionalOperation<CONTEXT>> tmp = operations; - operations = null; - return tmp; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.transaction;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Eike Stepper
+ */
+public class Transaction<CONTEXT> implements ITransaction<CONTEXT>
+{
+ private List<ITransactionalOperation<CONTEXT>> operations = new ArrayList<ITransactionalOperation<CONTEXT>>();
+
+ private CONTEXT context;
+
+ private boolean undoPhase1OnRollback;
+
+ public Transaction(CONTEXT context, boolean undoPhase1OnRollback)
+ {
+ this.context = context;
+ this.undoPhase1OnRollback = undoPhase1OnRollback;
+ }
+
+ public Transaction(CONTEXT context)
+ {
+ this(context, true);
+ }
+
+ public boolean isUndoPhase1OnRollback()
+ {
+ return undoPhase1OnRollback;
+ }
+
+ public boolean isActive()
+ {
+ return operations != null;
+ }
+
+ public CONTEXT getContext()
+ {
+ return context;
+ }
+
+ public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException
+ {
+ if (!isActive())
+ {
+ throw new TransactionException("Transaction inactive"); //$NON-NLS-1$
+ }
+
+ try
+ {
+ operation.phase1(context);
+ operations.add(operation);
+ }
+ catch (RuntimeException ex)
+ {
+ rollback();
+ throw ex;
+ }
+ catch (Exception ex)
+ {
+ rollback();
+ throw new TransactionException(ex);
+ }
+ }
+
+ public void commit()
+ {
+ for (ITransactionalOperation<CONTEXT> operation : end())
+ {
+ operation.phase2(context);
+ }
+ }
+
+ public void rollback()
+ {
+ if (undoPhase1OnRollback)
+ {
+ for (ITransactionalOperation<CONTEXT> operation : end())
+ {
+ operation.undoPhase1(context);
+ }
+ }
+ }
+
+ private List<ITransactionalOperation<CONTEXT>> end()
+ {
+ List<ITransactionalOperation<CONTEXT>> tmp = operations;
+ operations = null;
+ return tmp;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java index aec6ca7413..b7cf022c97 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java @@ -1,39 +1,39 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.transaction; - -/** - * @author Eike Stepper - * @noextend This interface is not intended to be extended by clients. - */ -public class TransactionException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - public TransactionException() - { - } - - public TransactionException(String message) - { - super(message); - } - - public TransactionException(Throwable cause) - { - super(cause); - } - - public TransactionException(String message, Throwable cause) - { - super(message, cause); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.transaction;
+
+/**
+ * @author Eike Stepper
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public class TransactionException extends RuntimeException
+{
+ private static final long serialVersionUID = 1L;
+
+ public TransactionException()
+ {
+ }
+
+ public TransactionException(String message)
+ {
+ super(message);
+ }
+
+ public TransactionException(Throwable cause)
+ {
+ super(cause);
+ }
+
+ public TransactionException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java index 283fcf030f..49335c3401 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java @@ -1,26 +1,26 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) 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: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.util.transaction; - -/** - * @author Eike Stepper - */ -public final class TransactionUtil -{ - private TransactionUtil() - { - } - - public static <CONTEXT> ITransaction<CONTEXT> createTransaction(CONTEXT context) - { - return new Transaction<CONTEXT>(context); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.util.transaction;
+
+/**
+ * @author Eike Stepper
+ */
+public final class TransactionUtil
+{
+ private TransactionUtil()
+ {
+ }
+
+ public static <CONTEXT> ITransaction<CONTEXT> createTransaction(CONTEXT context)
+ {
+ return new Transaction<CONTEXT>(context);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java index a9b5fc0305..e9bedd31a0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java @@ -1,5 +1,5 @@ /*
- * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) 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
|