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.tcp | |
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.tcp')
39 files changed, 4310 insertions, 4301 deletions
diff --git a/plugins/org.eclipse.net4j.tcp/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.net4j.tcp/.settings/org.eclipse.jdt.ui.prefs index aaef0ccba1..6726e7034a 100644 --- a/plugins/org.eclipse.net4j.tcp/.settings/org.eclipse.jdt.ui.prefs +++ b/plugins/org.eclipse.net4j.tcp/.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.tcp/build.properties b/plugins/org.eclipse.net4j.tcp/build.properties index 538003a8c1..25621f0aa1 100644 --- a/plugins/org.eclipse.net4j.tcp/build.properties +++ b/plugins/org.eclipse.net4j.tcp/build.properties @@ -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 - -# NLS_MESSAGEFORMAT_VAR - -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - .options,\ - plugin.properties,\ - plugin.xml,\ - about.html,\ - copyright.txt -src.includes = about.html,\ - copyright.txt - -doc.project = org.eclipse.net4j.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,\
+ plugin.properties,\
+ plugin.xml,\
+ about.html,\
+ copyright.txt
+src.includes = about.html,\
+ copyright.txt
+
+doc.project = org.eclipse.net4j.doc
diff --git a/plugins/org.eclipse.net4j.tcp/copyright.txt b/plugins/org.eclipse.net4j.tcp/copyright.txt index e921242cf0..8f6328980e 100644 --- a/plugins/org.eclipse.net4j.tcp/copyright.txt +++ b/plugins/org.eclipse.net4j.tcp/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.tcp/plugin.properties b/plugins/org.eclipse.net4j.tcp/plugin.properties index 86110484b0..b51755eb8b 100644 --- a/plugins/org.eclipse.net4j.tcp/plugin.properties +++ b/plugins/org.eclipse.net4j.tcp/plugin.properties @@ -1,11 +1,11 @@ -# Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.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 Signalling Platform Transport TCP -providerName = Eclipse Modeling Project +# Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.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 Signalling Platform Transport TCP
+providerName = Eclipse Modeling Project
diff --git a/plugins/org.eclipse.net4j.tcp/plugin.xml b/plugins/org.eclipse.net4j.tcp/plugin.xml index 02994761eb..f10f977268 100644 --- a/plugins/org.eclipse.net4j.tcp/plugin.xml +++ b/plugins/org.eclipse.net4j.tcp/plugin.xml @@ -1,47 +1,47 @@ -<?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="org.eclipse.net4j.util.factories"> - <factory - class="org.eclipse.net4j.internal.tcp.ssl.SSLAcceptorFactory" - productGroup="org.eclipse.net4j.acceptors" - type="ssl"/> - <factory - class="org.eclipse.net4j.internal.tcp.ssl.SSLConnectorFactory" - productGroup="org.eclipse.net4j.connectors" - type="ssl"/> - <factory - class="org.eclipse.net4j.internal.tcp.TCPAcceptorFactory" - productGroup="org.eclipse.net4j.acceptors" - type="tcp"/> - <factory - class="org.eclipse.net4j.internal.tcp.TCPConnectorFactory" - productGroup="org.eclipse.net4j.connectors" - type="tcp"/> - <factory - class="org.eclipse.net4j.internal.tcp.TCPSelectorFactory" - productGroup="org.eclipse.net4j.selectors" - type="tcp"/> - </extension> - - <extension - point="org.eclipse.net4j.util.elementProcessors"> - <elementProcessor - class="org.eclipse.net4j.internal.tcp.TCPSelectorInjector"> - </elementProcessor> - </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="org.eclipse.net4j.util.factories">
+ <factory
+ class="org.eclipse.net4j.internal.tcp.ssl.SSLAcceptorFactory"
+ productGroup="org.eclipse.net4j.acceptors"
+ type="ssl"/>
+ <factory
+ class="org.eclipse.net4j.internal.tcp.ssl.SSLConnectorFactory"
+ productGroup="org.eclipse.net4j.connectors"
+ type="ssl"/>
+ <factory
+ class="org.eclipse.net4j.internal.tcp.TCPAcceptorFactory"
+ productGroup="org.eclipse.net4j.acceptors"
+ type="tcp"/>
+ <factory
+ class="org.eclipse.net4j.internal.tcp.TCPConnectorFactory"
+ productGroup="org.eclipse.net4j.connectors"
+ type="tcp"/>
+ <factory
+ class="org.eclipse.net4j.internal.tcp.TCPSelectorFactory"
+ productGroup="org.eclipse.net4j.selectors"
+ type="tcp"/>
+ </extension>
+
+ <extension
+ point="org.eclipse.net4j.util.elementProcessors">
+ <elementProcessor
+ class="org.eclipse.net4j.internal.tcp.TCPSelectorInjector">
+ </elementProcessor>
+ </extension>
+
+</plugin>
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ControlChannel.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ControlChannel.java index 907b09ce9c..d5fdf575ec 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ControlChannel.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ControlChannel.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.internal.tcp; - -import org.eclipse.net4j.buffer.IBuffer; -import org.eclipse.net4j.connector.ConnectorException; -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.internal.tcp.messages.Messages; -import org.eclipse.net4j.protocol.IProtocol; -import org.eclipse.net4j.util.ImplementationError; -import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; -import org.eclipse.net4j.util.concurrent.ISynchronizer; -import org.eclipse.net4j.util.concurrent.SynchronizingCorrelator; -import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; -import org.eclipse.net4j.util.om.trace.ContextTracer; -import org.eclipse.net4j.util.security.INegotiationContext; -import org.eclipse.net4j.util.security.INegotiationContext.Receiver; - -import org.eclipse.internal.net4j.buffer.BufferUtil; - -import org.eclipse.spi.net4j.Channel; -import org.eclipse.spi.net4j.InternalChannel; -import org.eclipse.spi.net4j.InternalChannelMultiplexer; - -import java.nio.ByteBuffer; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class ControlChannel extends Channel -{ - public static final short CONTROL_CHANNEL_INDEX = InternalChannelMultiplexer.RESERVED_CHANNEL; - - public static final byte OPCODE_NEGOTIATION = 1; - - public static final byte OPCODE_REGISTRATION = 2; - - public static final byte OPCODE_REGISTRATION_ACK = 3; - - public static final byte OPCODE_DEREGISTRATION = 4; - - public static final byte SUCCESS = 1; - - public static final byte FAILURE = 0; - - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ControlChannel.class); - - private SynchronizingCorrelator<Short, Boolean> acknowledgements = new SynchronizingCorrelator<Short, Boolean>(); - - public ControlChannel(TCPConnector connector) - { - setID(CONTROL_CHANNEL_INDEX); - setMultiplexer(connector); - setReceiveExecutor(connector.getConfig().getReceiveExecutor()); - setUserID(connector.getUserID()); - } - - public TCPConnector getConnector() - { - return (TCPConnector)getMultiplexer(); - } - - public boolean registerChannel(short channelID, long timeout, IProtocol<?> protocol) - { - if (TRACER.isEnabled()) - { - TRACER.format("Registering channel {0} with protocol {1}", channelID, protocol); //$NON-NLS-1$ - } - - assertValidChannelID(channelID); - ISynchronizer<Boolean> acknowledgement = acknowledgements.correlate(channelID); - - IBuffer buffer = provideBuffer(); - ByteBuffer byteBuffer = buffer.startPutting(CONTROL_CHANNEL_INDEX); - byteBuffer.put(OPCODE_REGISTRATION); - byteBuffer.putShort(channelID); - BufferUtil.putUTF8(byteBuffer, protocol == null ? null : protocol.getType()); - handleBuffer(buffer); - - Boolean acknowledged = acknowledgement.get(timeout); - if (acknowledged == null) - { - throw new TimeoutRuntimeException(MessageFormat.format(Messages.getString("ControlChannel_0"), timeout)); //$NON-NLS-1$ - } - - return acknowledged; - } - - public void deregisterChannel(short channelID) - { - if (TRACER.isEnabled()) - { - TRACER.format("Deregistering channel {0}", channelID); //$NON-NLS-1$ - } - - assertValidChannelID(channelID); - IBuffer buffer = provideBuffer(); - ByteBuffer byteBuffer = buffer.startPutting(CONTROL_CHANNEL_INDEX); - byteBuffer.put(OPCODE_DEREGISTRATION); - byteBuffer.putShort(channelID); - handleBuffer(buffer); - } - - @Override - public void handleBufferFromMultiplexer(IBuffer buffer) - { - try - { - ByteBuffer byteBuffer = buffer.getByteBuffer(); - byte opcode = byteBuffer.get(); - switch (opcode) - { - case OPCODE_NEGOTIATION: - { - assertNegotiating(); - INegotiationContext negotiationContext = getConnector().getNegotiationContext(); - while (negotiationContext == null) - { - ConcurrencyUtil.sleep(20); - negotiationContext = getConnector().getNegotiationContext(); - } - - Receiver receiver = negotiationContext.getReceiver(); - receiver.receiveBuffer(negotiationContext, byteBuffer); - break; - } - - case OPCODE_REGISTRATION: - { - assertConnected(); - short channelID = byteBuffer.getShort(); - assertValidChannelID(channelID); - boolean success = true; - - try - { - byte[] handlerFactoryUTF8 = BufferUtil.getByteArray(byteBuffer); - String protocolID = BufferUtil.fromUTF8(handlerFactoryUTF8); - InternalChannel channel = getConnector().inverseOpenChannel(channelID, protocolID); - if (channel == null) - { - throw new ConnectorException(Messages.getString("ControlChannel_4")); //$NON-NLS-1$ - } - } - catch (Exception ex) - { - OM.LOG.error(ex); - success = false; - } - - sendStatus(OPCODE_REGISTRATION_ACK, channelID, success); - break; - } - - case OPCODE_DEREGISTRATION: - { - assertConnected(); - short channelID = byteBuffer.getShort(); - if (channelID == CONTROL_CHANNEL_INDEX) - { - throw new ImplementationError(); - } - - try - { - getConnector().inverseCloseChannel(channelID); - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - - break; - } - - case OPCODE_REGISTRATION_ACK: - { - assertConnected(); - short channelID = byteBuffer.getShort(); - boolean success = byteBuffer.get() == SUCCESS; - acknowledgements.put(channelID, success); - break; - } - - default: - OM.LOG.error("Invalid opcode: " + opcode); //$NON-NLS-1$ - getConnector().deactivate(); - } - } - finally - { - buffer.release(); - } - } - - @Override - public String toString() - { - return MessageFormat.format("Channel[Control, {0}]", getLocation()); //$NON-NLS-1$ - } - - @Override - protected void unregisterFromMultiplexer() - { - // Do nothing - } - - private void sendStatus(byte opcode, short channelID, boolean status) - { - IBuffer buffer = provideBuffer(); - ByteBuffer byteBuffer = buffer.startPutting(CONTROL_CHANNEL_INDEX); - byteBuffer.put(opcode); - byteBuffer.putShort(channelID); - byteBuffer.put(status ? SUCCESS : FAILURE); - handleBuffer(buffer); - } - - private void assertNegotiating() - { - if (!getConnector().isNegotiating()) - { - getConnector().deactivate(); - throw new IllegalStateException("Connector is not negotiating"); //$NON-NLS-1$ - } - } - - private void assertConnected() - { - if (!getConnector().isConnected()) - { - throw new IllegalStateException("Connector is not connected"); //$NON-NLS-1$ - } - } - - private void assertValidChannelID(short channelID) - { - if (channelID == CONTROL_CHANNEL_INDEX) - { - throw new IllegalArgumentException("Bad channelID"); //$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.tcp;
+
+import org.eclipse.net4j.buffer.IBuffer;
+import org.eclipse.net4j.connector.ConnectorException;
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.internal.tcp.messages.Messages;
+import org.eclipse.net4j.protocol.IProtocol;
+import org.eclipse.net4j.util.ImplementationError;
+import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
+import org.eclipse.net4j.util.concurrent.ISynchronizer;
+import org.eclipse.net4j.util.concurrent.SynchronizingCorrelator;
+import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+import org.eclipse.net4j.util.security.INegotiationContext;
+import org.eclipse.net4j.util.security.INegotiationContext.Receiver;
+
+import org.eclipse.internal.net4j.buffer.BufferUtil;
+
+import org.eclipse.spi.net4j.Channel;
+import org.eclipse.spi.net4j.InternalChannel;
+import org.eclipse.spi.net4j.InternalChannelMultiplexer;
+
+import java.nio.ByteBuffer;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class ControlChannel extends Channel
+{
+ public static final short CONTROL_CHANNEL_INDEX = InternalChannelMultiplexer.RESERVED_CHANNEL;
+
+ public static final byte OPCODE_NEGOTIATION = 1;
+
+ public static final byte OPCODE_REGISTRATION = 2;
+
+ public static final byte OPCODE_REGISTRATION_ACK = 3;
+
+ public static final byte OPCODE_DEREGISTRATION = 4;
+
+ public static final byte SUCCESS = 1;
+
+ public static final byte FAILURE = 0;
+
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ControlChannel.class);
+
+ private SynchronizingCorrelator<Short, Boolean> acknowledgements = new SynchronizingCorrelator<Short, Boolean>();
+
+ public ControlChannel(TCPConnector connector)
+ {
+ setID(CONTROL_CHANNEL_INDEX);
+ setMultiplexer(connector);
+ setReceiveExecutor(connector.getConfig().getReceiveExecutor());
+ setUserID(connector.getUserID());
+ }
+
+ public TCPConnector getConnector()
+ {
+ return (TCPConnector)getMultiplexer();
+ }
+
+ public boolean registerChannel(short channelID, long timeout, IProtocol<?> protocol)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Registering channel {0} with protocol {1}", channelID, protocol); //$NON-NLS-1$
+ }
+
+ assertValidChannelID(channelID);
+ ISynchronizer<Boolean> acknowledgement = acknowledgements.correlate(channelID);
+
+ IBuffer buffer = provideBuffer();
+ ByteBuffer byteBuffer = buffer.startPutting(CONTROL_CHANNEL_INDEX);
+ byteBuffer.put(OPCODE_REGISTRATION);
+ byteBuffer.putShort(channelID);
+ BufferUtil.putUTF8(byteBuffer, protocol == null ? null : protocol.getType());
+ handleBuffer(buffer);
+
+ Boolean acknowledged = acknowledgement.get(timeout);
+ if (acknowledged == null)
+ {
+ throw new TimeoutRuntimeException(MessageFormat.format(Messages.getString("ControlChannel_0"), timeout)); //$NON-NLS-1$
+ }
+
+ return acknowledged;
+ }
+
+ public void deregisterChannel(short channelID)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Deregistering channel {0}", channelID); //$NON-NLS-1$
+ }
+
+ assertValidChannelID(channelID);
+ IBuffer buffer = provideBuffer();
+ ByteBuffer byteBuffer = buffer.startPutting(CONTROL_CHANNEL_INDEX);
+ byteBuffer.put(OPCODE_DEREGISTRATION);
+ byteBuffer.putShort(channelID);
+ handleBuffer(buffer);
+ }
+
+ @Override
+ public void handleBufferFromMultiplexer(IBuffer buffer)
+ {
+ try
+ {
+ ByteBuffer byteBuffer = buffer.getByteBuffer();
+ byte opcode = byteBuffer.get();
+ switch (opcode)
+ {
+ case OPCODE_NEGOTIATION:
+ {
+ assertNegotiating();
+ INegotiationContext negotiationContext = getConnector().getNegotiationContext();
+ while (negotiationContext == null)
+ {
+ ConcurrencyUtil.sleep(20);
+ negotiationContext = getConnector().getNegotiationContext();
+ }
+
+ Receiver receiver = negotiationContext.getReceiver();
+ receiver.receiveBuffer(negotiationContext, byteBuffer);
+ break;
+ }
+
+ case OPCODE_REGISTRATION:
+ {
+ assertConnected();
+ short channelID = byteBuffer.getShort();
+ assertValidChannelID(channelID);
+ boolean success = true;
+
+ try
+ {
+ byte[] handlerFactoryUTF8 = BufferUtil.getByteArray(byteBuffer);
+ String protocolID = BufferUtil.fromUTF8(handlerFactoryUTF8);
+ InternalChannel channel = getConnector().inverseOpenChannel(channelID, protocolID);
+ if (channel == null)
+ {
+ throw new ConnectorException(Messages.getString("ControlChannel_4")); //$NON-NLS-1$
+ }
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ success = false;
+ }
+
+ sendStatus(OPCODE_REGISTRATION_ACK, channelID, success);
+ break;
+ }
+
+ case OPCODE_DEREGISTRATION:
+ {
+ assertConnected();
+ short channelID = byteBuffer.getShort();
+ if (channelID == CONTROL_CHANNEL_INDEX)
+ {
+ throw new ImplementationError();
+ }
+
+ try
+ {
+ getConnector().inverseCloseChannel(channelID);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+
+ break;
+ }
+
+ case OPCODE_REGISTRATION_ACK:
+ {
+ assertConnected();
+ short channelID = byteBuffer.getShort();
+ boolean success = byteBuffer.get() == SUCCESS;
+ acknowledgements.put(channelID, success);
+ break;
+ }
+
+ default:
+ OM.LOG.error("Invalid opcode: " + opcode); //$NON-NLS-1$
+ getConnector().deactivate();
+ }
+ }
+ finally
+ {
+ buffer.release();
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("Channel[Control, {0}]", getLocation()); //$NON-NLS-1$
+ }
+
+ @Override
+ protected void unregisterFromMultiplexer()
+ {
+ // Do nothing
+ }
+
+ private void sendStatus(byte opcode, short channelID, boolean status)
+ {
+ IBuffer buffer = provideBuffer();
+ ByteBuffer byteBuffer = buffer.startPutting(CONTROL_CHANNEL_INDEX);
+ byteBuffer.put(opcode);
+ byteBuffer.putShort(channelID);
+ byteBuffer.put(status ? SUCCESS : FAILURE);
+ handleBuffer(buffer);
+ }
+
+ private void assertNegotiating()
+ {
+ if (!getConnector().isNegotiating())
+ {
+ getConnector().deactivate();
+ throw new IllegalStateException("Connector is not negotiating"); //$NON-NLS-1$
+ }
+ }
+
+ private void assertConnected()
+ {
+ if (!getConnector().isConnected())
+ {
+ throw new IllegalStateException("Connector is not connected"); //$NON-NLS-1$
+ }
+ }
+
+ private void assertValidChannelID(short channelID)
+ {
+ if (channelID == CONTROL_CHANNEL_INDEX)
+ {
+ throw new IllegalArgumentException("Bad channelID"); //$NON-NLS-1$
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/SelectorUtil.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/SelectorUtil.java index 191101217f..33290f11e8 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/SelectorUtil.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/SelectorUtil.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.internal.tcp; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.nio.channels.CancelledKeyException; -import java.nio.channels.SelectionKey; - -/** - * @author Eike Stepper - */ -public final class SelectorUtil -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, SelectorUtil.class); - - private SelectorUtil() - { - } - - public static String formatInterestOps(int newOps) - { - StringBuilder builder = new StringBuilder(); - if ((newOps & SelectionKey.OP_ACCEPT) != 0) - { - addInterestOp(builder, "ACCEPT"); //$NON-NLS-1$ - } - - if ((newOps & SelectionKey.OP_CONNECT) != 0) - { - addInterestOp(builder, "CONNECT"); //$NON-NLS-1$ - } - - if ((newOps & SelectionKey.OP_READ) != 0) - { - addInterestOp(builder, "READ"); //$NON-NLS-1$ - } - - if ((newOps & SelectionKey.OP_WRITE) != 0) - { - addInterestOp(builder, "WRITE"); //$NON-NLS-1$ - } - - return builder.toString(); - } - - public static void setInterest(SelectionKey selectionKey, int operation, boolean interested) - { - if (selectionKey == null || !selectionKey.isValid()) - { - return; - } - - try - { - int newOps; - int oldOps = selectionKey.interestOps(); - if (interested) - { - newOps = oldOps | operation; - } - else - { - newOps = oldOps & ~operation; - } - - if (oldOps != newOps) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Setting interest " //$NON-NLS-1$ - + formatInterestOps(newOps) - + (oldOps == 0 ? "" : " (was " + formatInterestOps(oldOps).toLowerCase() + ")")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - selectionKey.interestOps(newOps); - } - } - catch (CancelledKeyException ignore) - { - } - } - - public static void setAcceptInterest(SelectionKey selectionKey, boolean interested) - { - setInterest(selectionKey, SelectionKey.OP_ACCEPT, interested); - } - - public static void setConnectInterest(SelectionKey selectionKey, boolean interested) - { - setInterest(selectionKey, SelectionKey.OP_CONNECT, interested); - } - - public static void setReadInterest(SelectionKey selectionKey, boolean interested) - { - setInterest(selectionKey, SelectionKey.OP_READ, interested); - } - - public static void setWriteInterest(SelectionKey selectionKey, boolean interested) - { - setInterest(selectionKey, SelectionKey.OP_WRITE, interested); - } - - private static void addInterestOp(StringBuilder builder, String op) - { - if (builder.length() != 0) - { - builder.append("|"); //$NON-NLS-1$ - } - - builder.append(op); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this 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.tcp;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.nio.channels.CancelledKeyException;
+import java.nio.channels.SelectionKey;
+
+/**
+ * @author Eike Stepper
+ */
+public final class SelectorUtil
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, SelectorUtil.class);
+
+ private SelectorUtil()
+ {
+ }
+
+ public static String formatInterestOps(int newOps)
+ {
+ StringBuilder builder = new StringBuilder();
+ if ((newOps & SelectionKey.OP_ACCEPT) != 0)
+ {
+ addInterestOp(builder, "ACCEPT"); //$NON-NLS-1$
+ }
+
+ if ((newOps & SelectionKey.OP_CONNECT) != 0)
+ {
+ addInterestOp(builder, "CONNECT"); //$NON-NLS-1$
+ }
+
+ if ((newOps & SelectionKey.OP_READ) != 0)
+ {
+ addInterestOp(builder, "READ"); //$NON-NLS-1$
+ }
+
+ if ((newOps & SelectionKey.OP_WRITE) != 0)
+ {
+ addInterestOp(builder, "WRITE"); //$NON-NLS-1$
+ }
+
+ return builder.toString();
+ }
+
+ public static void setInterest(SelectionKey selectionKey, int operation, boolean interested)
+ {
+ if (selectionKey == null || !selectionKey.isValid())
+ {
+ return;
+ }
+
+ try
+ {
+ int newOps;
+ int oldOps = selectionKey.interestOps();
+ if (interested)
+ {
+ newOps = oldOps | operation;
+ }
+ else
+ {
+ newOps = oldOps & ~operation;
+ }
+
+ if (oldOps != newOps)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Setting interest " //$NON-NLS-1$
+ + formatInterestOps(newOps)
+ + (oldOps == 0 ? "" : " (was " + formatInterestOps(oldOps).toLowerCase() + ")")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ selectionKey.interestOps(newOps);
+ }
+ }
+ catch (CancelledKeyException ignore)
+ {
+ }
+ }
+
+ public static void setAcceptInterest(SelectionKey selectionKey, boolean interested)
+ {
+ setInterest(selectionKey, SelectionKey.OP_ACCEPT, interested);
+ }
+
+ public static void setConnectInterest(SelectionKey selectionKey, boolean interested)
+ {
+ setInterest(selectionKey, SelectionKey.OP_CONNECT, interested);
+ }
+
+ public static void setReadInterest(SelectionKey selectionKey, boolean interested)
+ {
+ setInterest(selectionKey, SelectionKey.OP_READ, interested);
+ }
+
+ public static void setWriteInterest(SelectionKey selectionKey, boolean interested)
+ {
+ setInterest(selectionKey, SelectionKey.OP_WRITE, interested);
+ }
+
+ private static void addInterestOp(StringBuilder builder, String op)
+ {
+ if (builder.length() != 0)
+ {
+ builder.append("|"); //$NON-NLS-1$
+ }
+
+ builder.append(op);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptor.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptor.java index 02c84dc9a2..1236e0ba04 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptor.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptor.java @@ -1,287 +1,287 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Eike Stepper - initial API and implementation - * Caspar De Groot - maintenance - */ -package org.eclipse.net4j.internal.tcp; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPAcceptor; -import org.eclipse.net4j.tcp.ITCPPassiveSelectorListener; -import org.eclipse.net4j.tcp.ITCPSelector; -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.concurrent.Worker; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import org.eclipse.spi.net4j.Acceptor; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.text.MessageFormat; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * @author Eike Stepper - */ -public class TCPAcceptor extends Acceptor implements ITCPAcceptor, ITCPPassiveSelectorListener -{ - public static final boolean DEFAULT_START_SYNCHRONOUSLY = true; - - public static final long DEFAULT_SYNCHRONOUS_START_TIMEOUT = 2 * Worker.DEFAULT_TIMEOUT; - - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, TCPAcceptor.class); - - private TCPSelector selector; - - @ExcludeFromDump - private SelectionKey selectionKey; - - private boolean startSynchronously = DEFAULT_START_SYNCHRONOUSLY; - - private long synchronousStartTimeout = DEFAULT_SYNCHRONOUS_START_TIMEOUT; - - @ExcludeFromDump - private CountDownLatch startLatch; - - private ServerSocketChannel serverSocketChannel; - - private String address = DEFAULT_ADDRESS; - - private int port = DEFAULT_PORT; - - public TCPAcceptor() - { - } - - public String getAddress() - { - return address; - } - - public void setAddress(String address) - { - this.address = address; - } - - public int getPort() - { - return port; - } - - public void setPort(int port) - { - this.port = port; - } - - public TCPSelector getSelector() - { - return selector; - } - - public void setSelector(TCPSelector selector) - { - this.selector = selector; - } - - public boolean isStartSynchronously() - { - return startSynchronously; - } - - public void setStartSynchronously(boolean startSynchronously) - { - this.startSynchronously = startSynchronously; - } - - public SelectionKey getSelectionKey() - { - return selectionKey; - } - - public long getSynchronousStartTimeout() - { - return synchronousStartTimeout; - } - - public void setSynchronousStartTimeout(long synchronousStartTimeout) - { - this.synchronousStartTimeout = synchronousStartTimeout; - } - - public void handleRegistration(ITCPSelector selector, ServerSocketChannel serverSocketChannel) - { - try - { - InetSocketAddress addr = null; - if (address != null) - { - addr = new InetSocketAddress(InetAddress.getByName(address), port); - } - - ServerSocket socket = serverSocketChannel.socket(); - socket.bind(addr); - - if (addr == null) - { - address = socket.getInetAddress().toString(); - if (address.startsWith("/")) //$NON-NLS-1$ - { - address = address.substring(1); - } - - int colon = address.indexOf(':'); - if (colon != -1) - { - port = Integer.parseInt(address.substring(colon + 1)); - address = address.substring(0, colon); - } - } - - // [MACOSX] Must occur AFTER binding! - selectionKey = serverSocketChannel.register(selector.getSocketSelector(), SelectionKey.OP_ACCEPT, this); - } - catch (Exception ex) - { - OM.LOG.error(ex); - deactivateAsync(); - } - finally - { - if (startLatch != null) - { - startLatch.countDown(); - } - } - } - - public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel) - { - try - { - SocketChannel socketChannel = serverSocketChannel.accept(); - if (socketChannel != null) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Accepted socketChannel " + socketChannel); //$NON-NLS-1$ - } - - // socketChannel.socket().setReuseAddress(true); - // socketChannel.socket().setKeepAlive(true); - socketChannel.configureBlocking(false); - - TCPConnector connector = createConnector(); - prepareConnector(connector); - connector.setSocketChannel(socketChannel); - connector.setSelector(selector); - connector.activate(); - } - } - catch (ClosedChannelException ex) - { - deactivateAsync(); - } - catch (Exception ex) - { - if (isActive()) - { - OM.LOG.error(ex); - } - - deactivateAsync(); - } - } - - @Override - public String toString() - { - return MessageFormat.format("TCPAcceptor[{0}:{1}]", address, port); //$NON-NLS-1$ - } - - protected TCPConnector createConnector() - { - return new TCPServerConnector(this); - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (selector == null) - { - throw new IllegalStateException("selector == null"); //$NON-NLS-1$ - } - - if (startSynchronously) - { - startLatch = new CountDownLatch(1); - } - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - serverSocketChannel = ServerSocketChannel.open(); - serverSocketChannel.configureBlocking(false); - selector.orderRegistration(serverSocketChannel, this); - - if (startLatch != null) - { - if (!startLatch.await(synchronousStartTimeout, TimeUnit.MILLISECONDS)) - { - startLatch = null; - IOUtil.closeSilent(serverSocketChannel); - throw new IOException("Registration with selector timed out after " + synchronousStartTimeout + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - - @Override - protected void doDeactivate() throws Exception - { - cancelSelectionKey(); - - IOUtil.closeSilent(serverSocketChannel); - serverSocketChannel = null; - super.doDeactivate(); - } - - protected void deactivateAsync() - { - // Cancel the selection immediately - cancelSelectionKey(); - - // Do the rest of the deactivation asynchronously - getConfig().getReceiveExecutor().execute(new Runnable() - { - public void run() - { - deactivate(); - } - }); - } - - private void cancelSelectionKey() - { - if (selectionKey != null) - { - selectionKey.cancel(); - selectionKey = 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
+ * Caspar De Groot - maintenance
+ */
+package org.eclipse.net4j.internal.tcp;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPAcceptor;
+import org.eclipse.net4j.tcp.ITCPPassiveSelectorListener;
+import org.eclipse.net4j.tcp.ITCPSelector;
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.concurrent.Worker;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import org.eclipse.spi.net4j.Acceptor;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.text.MessageFormat;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPAcceptor extends Acceptor implements ITCPAcceptor, ITCPPassiveSelectorListener
+{
+ public static final boolean DEFAULT_START_SYNCHRONOUSLY = true;
+
+ public static final long DEFAULT_SYNCHRONOUS_START_TIMEOUT = 2 * Worker.DEFAULT_TIMEOUT;
+
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, TCPAcceptor.class);
+
+ private TCPSelector selector;
+
+ @ExcludeFromDump
+ private SelectionKey selectionKey;
+
+ private boolean startSynchronously = DEFAULT_START_SYNCHRONOUSLY;
+
+ private long synchronousStartTimeout = DEFAULT_SYNCHRONOUS_START_TIMEOUT;
+
+ @ExcludeFromDump
+ private CountDownLatch startLatch;
+
+ private ServerSocketChannel serverSocketChannel;
+
+ private String address = DEFAULT_ADDRESS;
+
+ private int port = DEFAULT_PORT;
+
+ public TCPAcceptor()
+ {
+ }
+
+ public String getAddress()
+ {
+ return address;
+ }
+
+ public void setAddress(String address)
+ {
+ this.address = address;
+ }
+
+ public int getPort()
+ {
+ return port;
+ }
+
+ public void setPort(int port)
+ {
+ this.port = port;
+ }
+
+ public TCPSelector getSelector()
+ {
+ return selector;
+ }
+
+ public void setSelector(TCPSelector selector)
+ {
+ this.selector = selector;
+ }
+
+ public boolean isStartSynchronously()
+ {
+ return startSynchronously;
+ }
+
+ public void setStartSynchronously(boolean startSynchronously)
+ {
+ this.startSynchronously = startSynchronously;
+ }
+
+ public SelectionKey getSelectionKey()
+ {
+ return selectionKey;
+ }
+
+ public long getSynchronousStartTimeout()
+ {
+ return synchronousStartTimeout;
+ }
+
+ public void setSynchronousStartTimeout(long synchronousStartTimeout)
+ {
+ this.synchronousStartTimeout = synchronousStartTimeout;
+ }
+
+ public void handleRegistration(ITCPSelector selector, ServerSocketChannel serverSocketChannel)
+ {
+ try
+ {
+ InetSocketAddress addr = null;
+ if (address != null)
+ {
+ addr = new InetSocketAddress(InetAddress.getByName(address), port);
+ }
+
+ ServerSocket socket = serverSocketChannel.socket();
+ socket.bind(addr);
+
+ if (addr == null)
+ {
+ address = socket.getInetAddress().toString();
+ if (address.startsWith("/")) //$NON-NLS-1$
+ {
+ address = address.substring(1);
+ }
+
+ int colon = address.indexOf(':');
+ if (colon != -1)
+ {
+ port = Integer.parseInt(address.substring(colon + 1));
+ address = address.substring(0, colon);
+ }
+ }
+
+ // [MACOSX] Must occur AFTER binding!
+ selectionKey = serverSocketChannel.register(selector.getSocketSelector(), SelectionKey.OP_ACCEPT, this);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ finally
+ {
+ if (startLatch != null)
+ {
+ startLatch.countDown();
+ }
+ }
+ }
+
+ public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel)
+ {
+ try
+ {
+ SocketChannel socketChannel = serverSocketChannel.accept();
+ if (socketChannel != null)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Accepted socketChannel " + socketChannel); //$NON-NLS-1$
+ }
+
+ // socketChannel.socket().setReuseAddress(true);
+ // socketChannel.socket().setKeepAlive(true);
+ socketChannel.configureBlocking(false);
+
+ TCPConnector connector = createConnector();
+ prepareConnector(connector);
+ connector.setSocketChannel(socketChannel);
+ connector.setSelector(selector);
+ connector.activate();
+ }
+ }
+ catch (ClosedChannelException ex)
+ {
+ deactivateAsync();
+ }
+ catch (Exception ex)
+ {
+ if (isActive())
+ {
+ OM.LOG.error(ex);
+ }
+
+ deactivateAsync();
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("TCPAcceptor[{0}:{1}]", address, port); //$NON-NLS-1$
+ }
+
+ protected TCPConnector createConnector()
+ {
+ return new TCPServerConnector(this);
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (selector == null)
+ {
+ throw new IllegalStateException("selector == null"); //$NON-NLS-1$
+ }
+
+ if (startSynchronously)
+ {
+ startLatch = new CountDownLatch(1);
+ }
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ serverSocketChannel = ServerSocketChannel.open();
+ serverSocketChannel.configureBlocking(false);
+ selector.orderRegistration(serverSocketChannel, this);
+
+ if (startLatch != null)
+ {
+ if (!startLatch.await(synchronousStartTimeout, TimeUnit.MILLISECONDS))
+ {
+ startLatch = null;
+ IOUtil.closeSilent(serverSocketChannel);
+ throw new IOException("Registration with selector timed out after " + synchronousStartTimeout + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ }
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ cancelSelectionKey();
+
+ IOUtil.closeSilent(serverSocketChannel);
+ serverSocketChannel = null;
+ super.doDeactivate();
+ }
+
+ protected void deactivateAsync()
+ {
+ // Cancel the selection immediately
+ cancelSelectionKey();
+
+ // Do the rest of the deactivation asynchronously
+ getConfig().getReceiveExecutor().execute(new Runnable()
+ {
+ public void run()
+ {
+ deactivate();
+ }
+ });
+ }
+
+ private void cancelSelectionKey()
+ {
+ if (selectionKey != null)
+ {
+ selectionKey.cancel();
+ selectionKey = null;
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptorFactory.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptorFactory.java index f04ab8a30f..5597190a3d 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptorFactory.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPAcceptorFactory.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 - * Caspar De Groot - maintenance - */ -package org.eclipse.net4j.internal.tcp; - -import org.eclipse.net4j.tcp.ITCPAcceptor; -import org.eclipse.net4j.util.StringUtil; - -import org.eclipse.spi.net4j.AcceptorFactory; - -/** - * @author Eike Stepper - */ -public class TCPAcceptorFactory extends AcceptorFactory -{ - public static final String TYPE = "tcp"; //$NON-NLS-1$ - - private static final String SEPARATOR = ":"; //$NON-NLS-1$ - - public TCPAcceptorFactory() - { - super(TYPE); - } - - /** - * Allows derived classes to override the TYPE identifier - */ - protected TCPAcceptorFactory(String type) - { - super(type); - } - - public TCPAcceptor create(String description) - { - String address = ITCPAcceptor.DEFAULT_ADDRESS; - int port = ITCPAcceptor.DEFAULT_PORT; - - if (!StringUtil.isEmpty(description)) - { - String[] tokens = description.split(SEPARATOR); - if (!StringUtil.isEmpty(tokens[0])) - { - address = tokens[0]; - } - - if (tokens.length > 1 && !StringUtil.isEmpty(tokens[1])) - { - port = Integer.parseInt(tokens[1]); - } - } - - TCPAcceptor acceptor = createAcceptor(); - acceptor.setAddress(address); - acceptor.setPort(port); - return acceptor; - } - - protected TCPAcceptor createAcceptor() - { - return new TCPAcceptor(); - } - - @Override - public String getDescriptionFor(Object object) - { - if (object instanceof TCPAcceptor) - { - TCPAcceptor acceptor = (TCPAcceptor)object; - return acceptor.getAddress() + SEPARATOR + acceptor.getPort(); - } - - 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
+ * Caspar De Groot - maintenance
+ */
+package org.eclipse.net4j.internal.tcp;
+
+import org.eclipse.net4j.tcp.ITCPAcceptor;
+import org.eclipse.net4j.util.StringUtil;
+
+import org.eclipse.spi.net4j.AcceptorFactory;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPAcceptorFactory extends AcceptorFactory
+{
+ public static final String TYPE = "tcp"; //$NON-NLS-1$
+
+ private static final String SEPARATOR = ":"; //$NON-NLS-1$
+
+ public TCPAcceptorFactory()
+ {
+ super(TYPE);
+ }
+
+ /**
+ * Allows derived classes to override the TYPE identifier
+ */
+ protected TCPAcceptorFactory(String type)
+ {
+ super(type);
+ }
+
+ public TCPAcceptor create(String description)
+ {
+ String address = ITCPAcceptor.DEFAULT_ADDRESS;
+ int port = ITCPAcceptor.DEFAULT_PORT;
+
+ if (!StringUtil.isEmpty(description))
+ {
+ String[] tokens = description.split(SEPARATOR);
+ if (!StringUtil.isEmpty(tokens[0]))
+ {
+ address = tokens[0];
+ }
+
+ if (tokens.length > 1 && !StringUtil.isEmpty(tokens[1]))
+ {
+ port = Integer.parseInt(tokens[1]);
+ }
+ }
+
+ TCPAcceptor acceptor = createAcceptor();
+ acceptor.setAddress(address);
+ acceptor.setPort(port);
+ return acceptor;
+ }
+
+ protected TCPAcceptor createAcceptor()
+ {
+ return new TCPAcceptor();
+ }
+
+ @Override
+ public String getDescriptionFor(Object object)
+ {
+ if (object instanceof TCPAcceptor)
+ {
+ TCPAcceptor acceptor = (TCPAcceptor)object;
+ return acceptor.getAddress() + SEPARATOR + acceptor.getPort();
+ }
+
+ return null;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPClientConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPClientConnector.java index 98d9609c29..dea6d2bd86 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPClientConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPClientConnector.java @@ -1,93 +1,93 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Eike Stepper - initial API and implementation - * Caspar De Groot - maintenance - */ -package org.eclipse.net4j.internal.tcp; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPSelector; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.nio.channels.SocketChannel; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class TCPClientConnector extends TCPConnector -{ - public TCPClientConnector() - { - try - { - SocketChannel socketChannel = SocketChannel.open(); - // socketChannel.socket().setReuseAddress(true); - // socketChannel.socket().setKeepAlive(true); - socketChannel.configureBlocking(false); - setSocketChannel(socketChannel); - } - catch (IOException ex) - { - OM.LOG.error(ex); - } - } - - @Override - public Location getLocation() - { - return Location.CLIENT; - } - - @Override - public String toString() - { - if (getUserID() == null) - { - return MessageFormat.format("TCPClientConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$ - } - - return MessageFormat.format("TCPClientConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$ - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (getHost() == null) - { - throw new IllegalStateException("host == null"); //$NON-NLS-1$ - } - - if (getPort() == 0) - { - throw new IllegalStateException("port == 0"); //$NON-NLS-1$ - } - } - - @Override - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel) - { - super.handleRegistration(selector, socketChannel); - - try - { - InetAddress addr = InetAddress.getByName(getHost()); - InetSocketAddress sAddr = new InetSocketAddress(addr, getPort()); - getSocketChannel().connect(sAddr); - } - catch (Exception ex) - { - OM.LOG.error(ex); - deactivateAsync(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ * Caspar De Groot - maintenance
+ */
+package org.eclipse.net4j.internal.tcp;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPSelector;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.channels.SocketChannel;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPClientConnector extends TCPConnector
+{
+ public TCPClientConnector()
+ {
+ try
+ {
+ SocketChannel socketChannel = SocketChannel.open();
+ // socketChannel.socket().setReuseAddress(true);
+ // socketChannel.socket().setKeepAlive(true);
+ socketChannel.configureBlocking(false);
+ setSocketChannel(socketChannel);
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error(ex);
+ }
+ }
+
+ @Override
+ public Location getLocation()
+ {
+ return Location.CLIENT;
+ }
+
+ @Override
+ public String toString()
+ {
+ if (getUserID() == null)
+ {
+ return MessageFormat.format("TCPClientConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$
+ }
+
+ return MessageFormat.format("TCPClientConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (getHost() == null)
+ {
+ throw new IllegalStateException("host == null"); //$NON-NLS-1$
+ }
+
+ if (getPort() == 0)
+ {
+ throw new IllegalStateException("port == 0"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ super.handleRegistration(selector, socketChannel);
+
+ try
+ {
+ InetAddress addr = InetAddress.getByName(getHost());
+ InetSocketAddress sAddr = new InetSocketAddress(addr, getPort());
+ getSocketChannel().connect(sAddr);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnector.java index 28c0d994a2..9b8c58e75a 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnector.java @@ -1,518 +1,518 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Eike Stepper - initial API and implementation - * Caspar De Groot - maintenance - */ -package org.eclipse.net4j.internal.tcp; - -import org.eclipse.net4j.buffer.IBuffer; -import org.eclipse.net4j.channel.ChannelException; -import org.eclipse.net4j.channel.IChannel; -import org.eclipse.net4j.connector.ConnectorException; -import org.eclipse.net4j.connector.ConnectorState; -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.internal.tcp.messages.Messages; -import org.eclipse.net4j.protocol.IProtocol; -import org.eclipse.net4j.tcp.ITCPActiveSelectorListener; -import org.eclipse.net4j.tcp.ITCPConnector; -import org.eclipse.net4j.tcp.ITCPNegotiationContext; -import org.eclipse.net4j.tcp.ITCPSelector; -import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.collection.RoundRobinBlockingQueue; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.lifecycle.LifecycleUtil; -import org.eclipse.net4j.util.om.trace.ContextTracer; -import org.eclipse.net4j.util.security.INegotiationContext; -import org.eclipse.net4j.util.security.NegotiationContext; -import org.eclipse.net4j.util.security.NegotiationException; - -import org.eclipse.spi.net4j.Connector; -import org.eclipse.spi.net4j.InternalChannel; - -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.util.Queue; -import java.util.concurrent.BlockingQueue; - -/** - * @author Eike Stepper - */ -public abstract class TCPConnector extends Connector implements ITCPConnector, ITCPActiveSelectorListener -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, TCPConnector.class); - - private SocketChannel socketChannel; - - private ITCPSelector selector; - - @ExcludeFromDump - private SelectionKey selectionKey; - - private BlockingQueue<InternalChannel> writeQueue = new RoundRobinBlockingQueue<InternalChannel>(); - - private IBuffer inputBuffer; - - private ControlChannel controlChannel; - - private String host; - - private int port; - - public TCPConnector() - { - } - - public String getHost() - { - return host; - } - - public void setHost(String host) - { - this.host = host; - } - - public int getPort() - { - return port; - } - - public void setPort(int port) - { - this.port = port; - } - - public ITCPSelector getSelector() - { - return selector; - } - - public void setSelector(ITCPSelector selector) - { - this.selector = selector; - } - - public SocketChannel getSocketChannel() - { - return socketChannel; - } - - /** - * SocketChannel must already be non-blocking! - */ - public void setSocketChannel(SocketChannel socketChannel) - { - this.socketChannel = socketChannel; - } - - public SelectionKey getSelectionKey() - { - return selectionKey; - } - - public void setSelectionKey(SelectionKey selectionKey) - { - this.selectionKey = selectionKey; - } - - public BlockingQueue<InternalChannel> getWriteQueue() - { - return writeQueue; - } - - public void setWriteQueue(BlockingQueue<InternalChannel> writeQueue) - { - this.writeQueue = writeQueue; - } - - public IBuffer getInputBuffer() - { - return inputBuffer; - } - - public void setInputBuffer(IBuffer inputBuffer) - { - this.inputBuffer = inputBuffer; - } - - public ControlChannel getControlChannel() - { - return controlChannel; - } - - public void setControlChannel(ControlChannel controlChannel) - { - this.controlChannel = controlChannel; - } - - @Override - public String getURL() - { - StringBuilder builder = new StringBuilder(); - builder.append(getProtocolString()); - builder.append(host); - if (port != DEFAULT_PORT) - { - builder.append(":"); - builder.append(port); - } - - return builder.toString(); - } - - public String getProtocolString() - { - return "tcp://"; - } - - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel) - { - try - { - int interest = isClient() ? SelectionKey.OP_CONNECT : SelectionKey.OP_READ; - selectionKey = socketChannel.register(selector.getSocketSelector(), interest, this); - if (isServer()) - { - leaveConnecting(); - } - } - catch (Exception ex) - { - deferredActivate(false); - } - } - - public void handleConnect(ITCPSelector selector, SocketChannel channel) - { - try - { - if (channel.finishConnect()) - { - selector.orderConnectInterest(selectionKey, true, false); - selector.orderReadInterest(selectionKey, true, true); - leaveConnecting(); - } - } - catch (Exception ex) - { - deferredActivate(false); - } - } - - public void handleRead(ITCPSelector selector, SocketChannel socketChannel) - { - try - { - if (inputBuffer == null) - { - inputBuffer = getConfig().getBufferProvider().provideBuffer(); - } - - ByteBuffer byteBuffer = inputBuffer.startGetting(socketChannel); - if (byteBuffer != null) - { - short channelID = inputBuffer.getChannelID(); - InternalChannel channel = channelID == ControlChannel.CONTROL_CHANNEL_INDEX ? controlChannel - : getChannel(channelID); - if (channel != null) - { - channel.handleBufferFromMultiplexer(inputBuffer); - } - else - { - if (TRACER.isEnabled()) - { - TRACER.trace("Discarding buffer from unknown channel"); //$NON-NLS-1$ - } - - inputBuffer.release(); - } - - inputBuffer = null; - } - } - catch (NegotiationException ex) - { - OM.LOG.error(ex); - setNegotiationException(ex); - deactivateAsync(); - } - catch (ClosedChannelException ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Socket channel closed: " + socketChannel); //$NON-NLS-1$ - } - - deactivateAsync(); - } - catch (Exception ex) - { - if (isActive()) - { - OM.LOG.error(ex); - deactivateAsync(); - } - } - } - - /** - * Called by an {@link IChannel} each time a new buffer is available for multiplexing. This or another buffer can be - * dequeued from the outputQueue of the {@link IChannel}. - */ - public void multiplexChannel(InternalChannel channel) - { - synchronized (writeQueue) - { - boolean firstChannel = writeQueue.isEmpty(); - - try - { - writeQueue.put(channel); - } - catch (InterruptedException ex) - { - throw WrappedException.wrap(ex); - } - - if (firstChannel) - { - if (selectionKey != null) - { - doOrderWriteInterest(true); - } - } - } - } - - public void handleWrite(ITCPSelector selector, SocketChannel socketChannel) - { - try - { - synchronized (writeQueue) - { - InternalChannel channel = writeQueue.peek(); - if (channel != null) - { - Queue<IBuffer> bufferQueue = channel.getSendQueue(); - if (bufferQueue != null) - { - IBuffer buffer = bufferQueue.peek(); - if (buffer != null) - { - if (buffer.write(socketChannel)) - { - writeQueue.poll(); - bufferQueue.poll(); - buffer.release(); - } - } - } - } - - if (writeQueue.isEmpty()) - { - if (selectionKey != null) - { - doOrderWriteInterest(false); - } - } - } - } - catch (NullPointerException ignore) - { - } - catch (ClosedChannelException ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Socket channel closed: " + socketChannel); //$NON-NLS-1$ - } - - deactivateAsync(); - } - catch (Exception ex) - { - if (isActive()) - { - OM.LOG.error(ex); - deactivateAsync(); - } - } - } - - protected void doOrderWriteInterest(boolean on) - { - selector.orderWriteInterest(selectionKey, isClient(), on); - } - - @Override - protected void registerChannelWithPeer(short channelID, long timeout, IProtocol<?> protocol) throws ChannelException - { - try - { - if (!controlChannel.registerChannel(channelID, timeout, protocol)) - { - throw new ChannelException("Failed to register channel with peer"); //$NON-NLS-1$ - } - } - catch (RuntimeException ex) - { - throw ex; - } - catch (Exception ex) - { - throw new ConnectorException(ex); - } - } - - @Override - protected void deregisterChannelFromPeer(InternalChannel channel) throws ChannelException - { - if (channel != null && channel.getClass() != ControlChannel.class) - { - if (controlChannel != null && isConnected()) - { - controlChannel.deregisterChannel(channel.getID()); - } - } - } - - @Override - protected INegotiationContext createNegotiationContext() - { - return new TCPNegotiationContext(); - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (socketChannel == null) - { - throw new IllegalStateException("socketChannel == null"); //$NON-NLS-1$ - } - - if (selector == null) - { - throw new IllegalStateException("selector == null"); //$NON-NLS-1$ - } - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - controlChannel = new ControlChannel(this); - controlChannel.activate(); - selector.orderRegistration(socketChannel, isClient(), this); - } - - @Override - protected void doDeactivate() throws Exception - { - cancelSelectionKey(); - - LifecycleUtil.deactivate(controlChannel); - controlChannel = null; - - IOUtil.closeSilent(socketChannel); - socketChannel = null; - super.doDeactivate(); - } - - protected void deactivateAsync() - { - // Cancel the selection immediately - cancelSelectionKey(); - - // Do the rest of the deactivation asynchronously - getConfig().getReceiveExecutor().execute(new Runnable() - { - public void run() - { - deactivate(); - } - }); - } - - private void cancelSelectionKey() - { - if (selectionKey != null) - { - selectionKey.cancel(); - selectionKey = null; - } - } - - /** - * @author Eike Stepper - */ - private final class TCPNegotiationContext extends NegotiationContext implements ITCPNegotiationContext - { - private IBuffer buffer; - - private boolean failed; - - public TCPNegotiationContext() - { - } - - public TCPConnector getConnector() - { - return TCPConnector.this; - } - - public void setUserID(String userID) - { - TCPConnector.this.setUserID(userID); - } - - public ByteBuffer getBuffer() - { - buffer = getConfig().getBufferProvider().provideBuffer(); - ByteBuffer byteBuffer = buffer.startPutting(ControlChannel.CONTROL_CHANNEL_INDEX); - byteBuffer.put(ControlChannel.OPCODE_NEGOTIATION); - return byteBuffer; - } - - public void transmitBuffer(ByteBuffer byteBuffer) - { - if (buffer.getByteBuffer() != byteBuffer) - { - throw new IllegalArgumentException("The passed buffer is not the last that was produced"); //$NON-NLS-1$ - } - - controlChannel.sendBuffer(buffer); - if (failed) - { - deactivate(); - } - } - - @Override - public void setFinished(boolean success) - { - if (success) - { - TCPConnector.this.setState(ConnectorState.CONNECTED); - } - else - { - OM.LOG.error(Messages.getString("TCPConnector.6") + TCPConnector.this); //$NON-NLS-1$ - failed = true; - } - - super.setFinished(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
+ * Caspar De Groot - maintenance
+ */
+package org.eclipse.net4j.internal.tcp;
+
+import org.eclipse.net4j.buffer.IBuffer;
+import org.eclipse.net4j.channel.ChannelException;
+import org.eclipse.net4j.channel.IChannel;
+import org.eclipse.net4j.connector.ConnectorException;
+import org.eclipse.net4j.connector.ConnectorState;
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.internal.tcp.messages.Messages;
+import org.eclipse.net4j.protocol.IProtocol;
+import org.eclipse.net4j.tcp.ITCPActiveSelectorListener;
+import org.eclipse.net4j.tcp.ITCPConnector;
+import org.eclipse.net4j.tcp.ITCPNegotiationContext;
+import org.eclipse.net4j.tcp.ITCPSelector;
+import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.collection.RoundRobinBlockingQueue;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+import org.eclipse.net4j.util.security.INegotiationContext;
+import org.eclipse.net4j.util.security.NegotiationContext;
+import org.eclipse.net4j.util.security.NegotiationException;
+
+import org.eclipse.spi.net4j.Connector;
+import org.eclipse.spi.net4j.InternalChannel;
+
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.SocketChannel;
+import java.util.Queue;
+import java.util.concurrent.BlockingQueue;
+
+/**
+ * @author Eike Stepper
+ */
+public abstract class TCPConnector extends Connector implements ITCPConnector, ITCPActiveSelectorListener
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, TCPConnector.class);
+
+ private SocketChannel socketChannel;
+
+ private ITCPSelector selector;
+
+ @ExcludeFromDump
+ private SelectionKey selectionKey;
+
+ private BlockingQueue<InternalChannel> writeQueue = new RoundRobinBlockingQueue<InternalChannel>();
+
+ private IBuffer inputBuffer;
+
+ private ControlChannel controlChannel;
+
+ private String host;
+
+ private int port;
+
+ public TCPConnector()
+ {
+ }
+
+ public String getHost()
+ {
+ return host;
+ }
+
+ public void setHost(String host)
+ {
+ this.host = host;
+ }
+
+ public int getPort()
+ {
+ return port;
+ }
+
+ public void setPort(int port)
+ {
+ this.port = port;
+ }
+
+ public ITCPSelector getSelector()
+ {
+ return selector;
+ }
+
+ public void setSelector(ITCPSelector selector)
+ {
+ this.selector = selector;
+ }
+
+ public SocketChannel getSocketChannel()
+ {
+ return socketChannel;
+ }
+
+ /**
+ * SocketChannel must already be non-blocking!
+ */
+ public void setSocketChannel(SocketChannel socketChannel)
+ {
+ this.socketChannel = socketChannel;
+ }
+
+ public SelectionKey getSelectionKey()
+ {
+ return selectionKey;
+ }
+
+ public void setSelectionKey(SelectionKey selectionKey)
+ {
+ this.selectionKey = selectionKey;
+ }
+
+ public BlockingQueue<InternalChannel> getWriteQueue()
+ {
+ return writeQueue;
+ }
+
+ public void setWriteQueue(BlockingQueue<InternalChannel> writeQueue)
+ {
+ this.writeQueue = writeQueue;
+ }
+
+ public IBuffer getInputBuffer()
+ {
+ return inputBuffer;
+ }
+
+ public void setInputBuffer(IBuffer inputBuffer)
+ {
+ this.inputBuffer = inputBuffer;
+ }
+
+ public ControlChannel getControlChannel()
+ {
+ return controlChannel;
+ }
+
+ public void setControlChannel(ControlChannel controlChannel)
+ {
+ this.controlChannel = controlChannel;
+ }
+
+ @Override
+ public String getURL()
+ {
+ StringBuilder builder = new StringBuilder();
+ builder.append(getProtocolString());
+ builder.append(host);
+ if (port != DEFAULT_PORT)
+ {
+ builder.append(":");
+ builder.append(port);
+ }
+
+ return builder.toString();
+ }
+
+ public String getProtocolString()
+ {
+ return "tcp://";
+ }
+
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ try
+ {
+ int interest = isClient() ? SelectionKey.OP_CONNECT : SelectionKey.OP_READ;
+ selectionKey = socketChannel.register(selector.getSocketSelector(), interest, this);
+ if (isServer())
+ {
+ leaveConnecting();
+ }
+ }
+ catch (Exception ex)
+ {
+ deferredActivate(false);
+ }
+ }
+
+ public void handleConnect(ITCPSelector selector, SocketChannel channel)
+ {
+ try
+ {
+ if (channel.finishConnect())
+ {
+ selector.orderConnectInterest(selectionKey, true, false);
+ selector.orderReadInterest(selectionKey, true, true);
+ leaveConnecting();
+ }
+ }
+ catch (Exception ex)
+ {
+ deferredActivate(false);
+ }
+ }
+
+ public void handleRead(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ try
+ {
+ if (inputBuffer == null)
+ {
+ inputBuffer = getConfig().getBufferProvider().provideBuffer();
+ }
+
+ ByteBuffer byteBuffer = inputBuffer.startGetting(socketChannel);
+ if (byteBuffer != null)
+ {
+ short channelID = inputBuffer.getChannelID();
+ InternalChannel channel = channelID == ControlChannel.CONTROL_CHANNEL_INDEX ? controlChannel
+ : getChannel(channelID);
+ if (channel != null)
+ {
+ channel.handleBufferFromMultiplexer(inputBuffer);
+ }
+ else
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Discarding buffer from unknown channel"); //$NON-NLS-1$
+ }
+
+ inputBuffer.release();
+ }
+
+ inputBuffer = null;
+ }
+ }
+ catch (NegotiationException ex)
+ {
+ OM.LOG.error(ex);
+ setNegotiationException(ex);
+ deactivateAsync();
+ }
+ catch (ClosedChannelException ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Socket channel closed: " + socketChannel); //$NON-NLS-1$
+ }
+
+ deactivateAsync();
+ }
+ catch (Exception ex)
+ {
+ if (isActive())
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ }
+ }
+
+ /**
+ * Called by an {@link IChannel} each time a new buffer is available for multiplexing. This or another buffer can be
+ * dequeued from the outputQueue of the {@link IChannel}.
+ */
+ public void multiplexChannel(InternalChannel channel)
+ {
+ synchronized (writeQueue)
+ {
+ boolean firstChannel = writeQueue.isEmpty();
+
+ try
+ {
+ writeQueue.put(channel);
+ }
+ catch (InterruptedException ex)
+ {
+ throw WrappedException.wrap(ex);
+ }
+
+ if (firstChannel)
+ {
+ if (selectionKey != null)
+ {
+ doOrderWriteInterest(true);
+ }
+ }
+ }
+ }
+
+ public void handleWrite(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ try
+ {
+ synchronized (writeQueue)
+ {
+ InternalChannel channel = writeQueue.peek();
+ if (channel != null)
+ {
+ Queue<IBuffer> bufferQueue = channel.getSendQueue();
+ if (bufferQueue != null)
+ {
+ IBuffer buffer = bufferQueue.peek();
+ if (buffer != null)
+ {
+ if (buffer.write(socketChannel))
+ {
+ writeQueue.poll();
+ bufferQueue.poll();
+ buffer.release();
+ }
+ }
+ }
+ }
+
+ if (writeQueue.isEmpty())
+ {
+ if (selectionKey != null)
+ {
+ doOrderWriteInterest(false);
+ }
+ }
+ }
+ }
+ catch (NullPointerException ignore)
+ {
+ }
+ catch (ClosedChannelException ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Socket channel closed: " + socketChannel); //$NON-NLS-1$
+ }
+
+ deactivateAsync();
+ }
+ catch (Exception ex)
+ {
+ if (isActive())
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ }
+ }
+
+ protected void doOrderWriteInterest(boolean on)
+ {
+ selector.orderWriteInterest(selectionKey, isClient(), on);
+ }
+
+ @Override
+ protected void registerChannelWithPeer(short channelID, long timeout, IProtocol<?> protocol) throws ChannelException
+ {
+ try
+ {
+ if (!controlChannel.registerChannel(channelID, timeout, protocol))
+ {
+ throw new ChannelException("Failed to register channel with peer"); //$NON-NLS-1$
+ }
+ }
+ catch (RuntimeException ex)
+ {
+ throw ex;
+ }
+ catch (Exception ex)
+ {
+ throw new ConnectorException(ex);
+ }
+ }
+
+ @Override
+ protected void deregisterChannelFromPeer(InternalChannel channel) throws ChannelException
+ {
+ if (channel != null && channel.getClass() != ControlChannel.class)
+ {
+ if (controlChannel != null && isConnected())
+ {
+ controlChannel.deregisterChannel(channel.getID());
+ }
+ }
+ }
+
+ @Override
+ protected INegotiationContext createNegotiationContext()
+ {
+ return new TCPNegotiationContext();
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (socketChannel == null)
+ {
+ throw new IllegalStateException("socketChannel == null"); //$NON-NLS-1$
+ }
+
+ if (selector == null)
+ {
+ throw new IllegalStateException("selector == null"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ controlChannel = new ControlChannel(this);
+ controlChannel.activate();
+ selector.orderRegistration(socketChannel, isClient(), this);
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ cancelSelectionKey();
+
+ LifecycleUtil.deactivate(controlChannel);
+ controlChannel = null;
+
+ IOUtil.closeSilent(socketChannel);
+ socketChannel = null;
+ super.doDeactivate();
+ }
+
+ protected void deactivateAsync()
+ {
+ // Cancel the selection immediately
+ cancelSelectionKey();
+
+ // Do the rest of the deactivation asynchronously
+ getConfig().getReceiveExecutor().execute(new Runnable()
+ {
+ public void run()
+ {
+ deactivate();
+ }
+ });
+ }
+
+ private void cancelSelectionKey()
+ {
+ if (selectionKey != null)
+ {
+ selectionKey.cancel();
+ selectionKey = null;
+ }
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ private final class TCPNegotiationContext extends NegotiationContext implements ITCPNegotiationContext
+ {
+ private IBuffer buffer;
+
+ private boolean failed;
+
+ public TCPNegotiationContext()
+ {
+ }
+
+ public TCPConnector getConnector()
+ {
+ return TCPConnector.this;
+ }
+
+ public void setUserID(String userID)
+ {
+ TCPConnector.this.setUserID(userID);
+ }
+
+ public ByteBuffer getBuffer()
+ {
+ buffer = getConfig().getBufferProvider().provideBuffer();
+ ByteBuffer byteBuffer = buffer.startPutting(ControlChannel.CONTROL_CHANNEL_INDEX);
+ byteBuffer.put(ControlChannel.OPCODE_NEGOTIATION);
+ return byteBuffer;
+ }
+
+ public void transmitBuffer(ByteBuffer byteBuffer)
+ {
+ if (buffer.getByteBuffer() != byteBuffer)
+ {
+ throw new IllegalArgumentException("The passed buffer is not the last that was produced"); //$NON-NLS-1$
+ }
+
+ controlChannel.sendBuffer(buffer);
+ if (failed)
+ {
+ deactivate();
+ }
+ }
+
+ @Override
+ public void setFinished(boolean success)
+ {
+ if (success)
+ {
+ TCPConnector.this.setState(ConnectorState.CONNECTED);
+ }
+ else
+ {
+ OM.LOG.error(Messages.getString("TCPConnector.6") + TCPConnector.this); //$NON-NLS-1$
+ failed = true;
+ }
+
+ super.setFinished(success);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnectorFactory.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnectorFactory.java index 5b9a5e0825..f7281a5dae 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnectorFactory.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPConnectorFactory.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 - * Caspar De Groot - maintenance - */ -package org.eclipse.net4j.internal.tcp; - -import org.eclipse.net4j.tcp.ITCPConnector; -import org.eclipse.net4j.util.StringUtil; -import org.eclipse.net4j.util.factory.ProductCreationException; - -import org.eclipse.spi.net4j.ConnectorFactory; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * @author Eike Stepper - */ -public class TCPConnectorFactory extends ConnectorFactory -{ - public static final String TYPE = "tcp"; //$NON-NLS-1$ - - private static final String URL_SCHEME = "http://"; //$NON-NLS-1$ - - public TCPConnectorFactory() - { - super(TYPE); - } - - /** - * Allows derived classes to override the TYPE identifier - */ - protected TCPConnectorFactory(String type) - { - super(type); - } - - public TCPConnector create(String description) - { - try - { - // TODO Don't use URL - // Scheme "tcp://" would be rejected! - URL url = new URL(URL_SCHEME + description); - String userID = url.getUserInfo(); - String host = url.getHost(); - int port = url.getPort(); - if (port == -1) - { - port = ITCPConnector.DEFAULT_PORT; - } - - TCPConnector connector = createConnector(); - connector.setUserID(userID); - connector.setHost(host); - connector.setPort(port); - return connector; - } - catch (MalformedURLException ex) - { - throw new ProductCreationException(ex); - } - } - - protected TCPConnector createConnector() - { - return new TCPClientConnector(); - } - - @Override - public String getDescriptionFor(Object object) - { - if (object instanceof TCPConnector) - { - TCPConnector connector = (TCPConnector)object; - String description = connector.getHost(); - String userID = connector.getUserID(); - if (!StringUtil.isEmpty(userID)) - { - description = userID + "@" + description; //$NON-NLS-1$ - } - - int port = connector.getPort(); - if (port != ITCPConnector.DEFAULT_PORT) - { - description = description + ":" + port; //$NON-NLS-1$ - } - - return description; - } - - 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
+ * Caspar De Groot - maintenance
+ */
+package org.eclipse.net4j.internal.tcp;
+
+import org.eclipse.net4j.tcp.ITCPConnector;
+import org.eclipse.net4j.util.StringUtil;
+import org.eclipse.net4j.util.factory.ProductCreationException;
+
+import org.eclipse.spi.net4j.ConnectorFactory;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPConnectorFactory extends ConnectorFactory
+{
+ public static final String TYPE = "tcp"; //$NON-NLS-1$
+
+ private static final String URL_SCHEME = "http://"; //$NON-NLS-1$
+
+ public TCPConnectorFactory()
+ {
+ super(TYPE);
+ }
+
+ /**
+ * Allows derived classes to override the TYPE identifier
+ */
+ protected TCPConnectorFactory(String type)
+ {
+ super(type);
+ }
+
+ public TCPConnector create(String description)
+ {
+ try
+ {
+ // TODO Don't use URL
+ // Scheme "tcp://" would be rejected!
+ URL url = new URL(URL_SCHEME + description);
+ String userID = url.getUserInfo();
+ String host = url.getHost();
+ int port = url.getPort();
+ if (port == -1)
+ {
+ port = ITCPConnector.DEFAULT_PORT;
+ }
+
+ TCPConnector connector = createConnector();
+ connector.setUserID(userID);
+ connector.setHost(host);
+ connector.setPort(port);
+ return connector;
+ }
+ catch (MalformedURLException ex)
+ {
+ throw new ProductCreationException(ex);
+ }
+ }
+
+ protected TCPConnector createConnector()
+ {
+ return new TCPClientConnector();
+ }
+
+ @Override
+ public String getDescriptionFor(Object object)
+ {
+ if (object instanceof TCPConnector)
+ {
+ TCPConnector connector = (TCPConnector)object;
+ String description = connector.getHost();
+ String userID = connector.getUserID();
+ if (!StringUtil.isEmpty(userID))
+ {
+ description = userID + "@" + description; //$NON-NLS-1$
+ }
+
+ int port = connector.getPort();
+ if (port != ITCPConnector.DEFAULT_PORT)
+ {
+ description = description + ":" + port; //$NON-NLS-1$
+ }
+
+ return description;
+ }
+
+ return null;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelector.java index df01a9e0c4..5c6fc77070 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelector.java @@ -1,414 +1,414 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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.tcp; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPActiveSelectorListener; -import org.eclipse.net4j.tcp.ITCPPassiveSelectorListener; -import org.eclipse.net4j.tcp.ITCPSelector; -import org.eclipse.net4j.util.lifecycle.Lifecycle; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.io.IOException; -import java.nio.channels.CancelledKeyException; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -/** - * @author Eike Stepper - */ -public class TCPSelector extends Lifecycle implements ITCPSelector, Runnable -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, TCPSelector.class); - - private Selector selector; - - /** - * Always processed <b>after</b> {@link #serverOperations}. - */ - private transient Queue<Runnable> clientOperations = new ConcurrentLinkedQueue<Runnable>(); - - /** - * Always processed <b>before</b> {@link #clientOperations}. - */ - private transient Queue<Runnable> serverOperations = new ConcurrentLinkedQueue<Runnable>(); - - private transient Thread thread; - - private transient boolean running; - - public TCPSelector() - { - } - - public Selector getSocketSelector() - { - return selector; - } - - public void orderRegistration(final ServerSocketChannel channel, final ITCPPassiveSelectorListener listener) - { - assertValidListener(listener); - order(false, new Runnable() - { - public void run() - { - executeRegistration(channel, listener); - } - - @Override - public String toString() - { - return "REGISTER " + channel; //$NON-NLS-1$ - } - }); - } - - public void orderRegistration(final SocketChannel channel, final boolean client, - final ITCPActiveSelectorListener listener) - { - assertValidListener(listener); - order(client, new Runnable() - { - public void run() - { - executeRegistration(channel, listener, client); - } - - @Override - public String toString() - { - return "REGISTER " + channel; //$NON-NLS-1$ - } - }); - } - - public void orderConnectInterest(final SelectionKey selectionKey, boolean client, final boolean on) - { - order(client, new Runnable() - { - public void run() - { - SelectorUtil.setConnectInterest(selectionKey, on); - } - - @Override - public String toString() - { - return "INTEREST CONNECT " + selectionKey.channel() + " = " + on; //$NON-NLS-1$ //$NON-NLS-2$ - } - }); - } - - public void orderReadInterest(final SelectionKey selectionKey, boolean client, final boolean on) - { - order(client, new Runnable() - { - public void run() - { - SelectorUtil.setReadInterest(selectionKey, on); - } - - @Override - public String toString() - { - return "INTEREST READ " + selectionKey.channel() + " = " + on; //$NON-NLS-1$ //$NON-NLS-2$ - } - }); - } - - public void orderWriteInterest(final SelectionKey selectionKey, boolean client, final boolean on) - { - order(client, new Runnable() - { - public void run() - { - SelectorUtil.setWriteInterest(selectionKey, on); - } - - @Override - public String toString() - { - return "INTEREST WRITE " + selectionKey.channel() + " = " + on; //$NON-NLS-1$ //$NON-NLS-2$ - } - }); - } - - public void run() - { - while (running && !Thread.interrupted()) - { - try - { - processOperations(false); - processOperations(true); - if (selector != null && selector.select() > 0) - { - Iterator<SelectionKey> it = selector.selectedKeys().iterator(); - while (it.hasNext()) - { - SelectionKey selKey = it.next(); - it.remove(); - - try - { - handleSelection(selKey); - } - catch (CancelledKeyException ignore) - { - // Do nothing - } - catch (NullPointerException ignore) - { - // Do nothing - } - catch (Exception ex) - { - OM.LOG.info(ex.getMessage()); - selKey.cancel(); - } - } - } - } - catch (NullPointerException ex) - { - break; - } - catch (ClosedSelectorException ex) - { - break; - } - catch (Exception ex) - { - OM.LOG.error(ex); - break; - } - } - - deactivate(); - } - - @Override - public String toString() - { - return "TCPSelector"; //$NON-NLS-1$ - } - - protected void handleSelection(SelectionKey selKey) throws IOException - { - SelectableChannel channel = selKey.channel(); - if (channel instanceof ServerSocketChannel) - { - ServerSocketChannel ssChannel = (ServerSocketChannel)selKey.channel(); - if (ssChannel.isOpen()) - { - ITCPPassiveSelectorListener listener = (ITCPPassiveSelectorListener)selKey.attachment(); - - if (selKey.isAcceptable()) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Accepting " + ssChannel); //$NON-NLS-1$ - } - - listener.handleAccept(this, ssChannel); - } - } - } - else if (channel instanceof SocketChannel) - { - SocketChannel sChannel = (SocketChannel)channel; - ITCPActiveSelectorListener listener = (ITCPActiveSelectorListener)selKey.attachment(); - - if (selKey.isConnectable()) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Connecting " + sChannel); //$NON-NLS-1$ - } - - listener.handleConnect(this, sChannel); - } - - if (selKey.isReadable()) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Reading " + sChannel); //$NON-NLS-1$ - } - - listener.handleRead(this, sChannel); - } - - if (selKey.isWritable()) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Writing " + sChannel); //$NON-NLS-1$ - } - - listener.handleWrite(this, sChannel); - } - } - } - - protected Selector openSelector() throws IOException - { - return Selector.open(); - } - - protected void closeSelector() throws IOException - { - selector.close(); - } - - @Override - protected void doActivate() throws Exception - { - super.doActivate(); - running = true; - selector = openSelector(); - - thread = new Thread(this, "TCPSelector"); //$NON-NLS-1$ - thread.setDaemon(true); - thread.start(); - } - - @Override - protected void doDeactivate() throws Exception - { - running = false; - selector.wakeup(); - Exception exception = null; - - try - { - thread.join(200); - } - catch (RuntimeException ex) - { - exception = ex; - } - finally - { - thread = null; - } - - try - { - closeSelector(); - } - catch (Exception ex) - { - if (exception == null) - { - exception = ex; - } - } - finally - { - selector = null; - } - - super.doDeactivate(); - if (exception != null) - { - throw exception; - } - } - - private void assertValidListener(Object listener) - { - if (listener == null) - { - throw new IllegalArgumentException("listener == null"); //$NON-NLS-1$ - } - } - - private void order(boolean client, Runnable operation) - { - if (TRACER.isEnabled()) - { - TRACER.format("Ordering {0} operation {1}", client ? "client" : "server", operation); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - if (client) - { - clientOperations.add(operation); - } - else - { - serverOperations.add(operation); - } - - if (selector != null) - { - selector.wakeup(); - } - } - - private void processOperations(boolean client) - { - Runnable operation; - Queue<Runnable> operations = client ? clientOperations : serverOperations; - while ((operation = operations.poll()) != null) - { - if (TRACER.isEnabled()) - { - TRACER.format("Executing {0} operation {1}", client ? "client" : "server", operation); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - } - - operation.run(); - } - } - - private void executeRegistration(final ServerSocketChannel channel, final ITCPPassiveSelectorListener listener) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Registering " + channel); //$NON-NLS-1$ - } - - try - { - listener.handleRegistration(this, channel); - } - catch (Exception ex) - { - OM.LOG.debug(ex); - } - } - - private void executeRegistration(final SocketChannel channel, final ITCPActiveSelectorListener listener, - boolean client) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Registering " + channel); //$NON-NLS-1$ - } - - try - { - listener.handleRegistration(this, channel); - } - catch (Exception ex) - { - OM.LOG.debug(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.internal.tcp;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPActiveSelectorListener;
+import org.eclipse.net4j.tcp.ITCPPassiveSelectorListener;
+import org.eclipse.net4j.tcp.ITCPSelector;
+import org.eclipse.net4j.util.lifecycle.Lifecycle;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.io.IOException;
+import java.nio.channels.CancelledKeyException;
+import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.Iterator;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPSelector extends Lifecycle implements ITCPSelector, Runnable
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, TCPSelector.class);
+
+ private Selector selector;
+
+ /**
+ * Always processed <b>after</b> {@link #serverOperations}.
+ */
+ private transient Queue<Runnable> clientOperations = new ConcurrentLinkedQueue<Runnable>();
+
+ /**
+ * Always processed <b>before</b> {@link #clientOperations}.
+ */
+ private transient Queue<Runnable> serverOperations = new ConcurrentLinkedQueue<Runnable>();
+
+ private transient Thread thread;
+
+ private transient boolean running;
+
+ public TCPSelector()
+ {
+ }
+
+ public Selector getSocketSelector()
+ {
+ return selector;
+ }
+
+ public void orderRegistration(final ServerSocketChannel channel, final ITCPPassiveSelectorListener listener)
+ {
+ assertValidListener(listener);
+ order(false, new Runnable()
+ {
+ public void run()
+ {
+ executeRegistration(channel, listener);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "REGISTER " + channel; //$NON-NLS-1$
+ }
+ });
+ }
+
+ public void orderRegistration(final SocketChannel channel, final boolean client,
+ final ITCPActiveSelectorListener listener)
+ {
+ assertValidListener(listener);
+ order(client, new Runnable()
+ {
+ public void run()
+ {
+ executeRegistration(channel, listener, client);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "REGISTER " + channel; //$NON-NLS-1$
+ }
+ });
+ }
+
+ public void orderConnectInterest(final SelectionKey selectionKey, boolean client, final boolean on)
+ {
+ order(client, new Runnable()
+ {
+ public void run()
+ {
+ SelectorUtil.setConnectInterest(selectionKey, on);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "INTEREST CONNECT " + selectionKey.channel() + " = " + on; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ }
+
+ public void orderReadInterest(final SelectionKey selectionKey, boolean client, final boolean on)
+ {
+ order(client, new Runnable()
+ {
+ public void run()
+ {
+ SelectorUtil.setReadInterest(selectionKey, on);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "INTEREST READ " + selectionKey.channel() + " = " + on; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ }
+
+ public void orderWriteInterest(final SelectionKey selectionKey, boolean client, final boolean on)
+ {
+ order(client, new Runnable()
+ {
+ public void run()
+ {
+ SelectorUtil.setWriteInterest(selectionKey, on);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "INTEREST WRITE " + selectionKey.channel() + " = " + on; //$NON-NLS-1$ //$NON-NLS-2$
+ }
+ });
+ }
+
+ public void run()
+ {
+ while (running && !Thread.interrupted())
+ {
+ try
+ {
+ processOperations(false);
+ processOperations(true);
+ if (selector != null && selector.select() > 0)
+ {
+ Iterator<SelectionKey> it = selector.selectedKeys().iterator();
+ while (it.hasNext())
+ {
+ SelectionKey selKey = it.next();
+ it.remove();
+
+ try
+ {
+ handleSelection(selKey);
+ }
+ catch (CancelledKeyException ignore)
+ {
+ // Do nothing
+ }
+ catch (NullPointerException ignore)
+ {
+ // Do nothing
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.info(ex.getMessage());
+ selKey.cancel();
+ }
+ }
+ }
+ }
+ catch (NullPointerException ex)
+ {
+ break;
+ }
+ catch (ClosedSelectorException ex)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ break;
+ }
+ }
+
+ deactivate();
+ }
+
+ @Override
+ public String toString()
+ {
+ return "TCPSelector"; //$NON-NLS-1$
+ }
+
+ protected void handleSelection(SelectionKey selKey) throws IOException
+ {
+ SelectableChannel channel = selKey.channel();
+ if (channel instanceof ServerSocketChannel)
+ {
+ ServerSocketChannel ssChannel = (ServerSocketChannel)selKey.channel();
+ if (ssChannel.isOpen())
+ {
+ ITCPPassiveSelectorListener listener = (ITCPPassiveSelectorListener)selKey.attachment();
+
+ if (selKey.isAcceptable())
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Accepting " + ssChannel); //$NON-NLS-1$
+ }
+
+ listener.handleAccept(this, ssChannel);
+ }
+ }
+ }
+ else if (channel instanceof SocketChannel)
+ {
+ SocketChannel sChannel = (SocketChannel)channel;
+ ITCPActiveSelectorListener listener = (ITCPActiveSelectorListener)selKey.attachment();
+
+ if (selKey.isConnectable())
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Connecting " + sChannel); //$NON-NLS-1$
+ }
+
+ listener.handleConnect(this, sChannel);
+ }
+
+ if (selKey.isReadable())
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Reading " + sChannel); //$NON-NLS-1$
+ }
+
+ listener.handleRead(this, sChannel);
+ }
+
+ if (selKey.isWritable())
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Writing " + sChannel); //$NON-NLS-1$
+ }
+
+ listener.handleWrite(this, sChannel);
+ }
+ }
+ }
+
+ protected Selector openSelector() throws IOException
+ {
+ return Selector.open();
+ }
+
+ protected void closeSelector() throws IOException
+ {
+ selector.close();
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ super.doActivate();
+ running = true;
+ selector = openSelector();
+
+ thread = new Thread(this, "TCPSelector"); //$NON-NLS-1$
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ running = false;
+ selector.wakeup();
+ Exception exception = null;
+
+ try
+ {
+ thread.join(200);
+ }
+ catch (RuntimeException ex)
+ {
+ exception = ex;
+ }
+ finally
+ {
+ thread = null;
+ }
+
+ try
+ {
+ closeSelector();
+ }
+ catch (Exception ex)
+ {
+ if (exception == null)
+ {
+ exception = ex;
+ }
+ }
+ finally
+ {
+ selector = null;
+ }
+
+ super.doDeactivate();
+ if (exception != null)
+ {
+ throw exception;
+ }
+ }
+
+ private void assertValidListener(Object listener)
+ {
+ if (listener == null)
+ {
+ throw new IllegalArgumentException("listener == null"); //$NON-NLS-1$
+ }
+ }
+
+ private void order(boolean client, Runnable operation)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Ordering {0} operation {1}", client ? "client" : "server", operation); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ if (client)
+ {
+ clientOperations.add(operation);
+ }
+ else
+ {
+ serverOperations.add(operation);
+ }
+
+ if (selector != null)
+ {
+ selector.wakeup();
+ }
+ }
+
+ private void processOperations(boolean client)
+ {
+ Runnable operation;
+ Queue<Runnable> operations = client ? clientOperations : serverOperations;
+ while ((operation = operations.poll()) != null)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.format("Executing {0} operation {1}", client ? "client" : "server", operation); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ }
+
+ operation.run();
+ }
+ }
+
+ private void executeRegistration(final ServerSocketChannel channel, final ITCPPassiveSelectorListener listener)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Registering " + channel); //$NON-NLS-1$
+ }
+
+ try
+ {
+ listener.handleRegistration(this, channel);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.debug(ex);
+ }
+ }
+
+ private void executeRegistration(final SocketChannel channel, final ITCPActiveSelectorListener listener,
+ boolean client)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Registering " + channel); //$NON-NLS-1$
+ }
+
+ try
+ {
+ listener.handleRegistration(this, channel);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.debug(ex);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorFactory.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorFactory.java index 14b03fb38b..6975a1d628 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorFactory.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorFactory.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.tcp; - -import org.eclipse.net4j.util.container.IManagedContainer; -import org.eclipse.net4j.util.factory.Factory; - -/** - * @author Eike Stepper - */ -public class TCPSelectorFactory extends Factory -{ - public static final String PRODUCT_GROUP = "org.eclipse.net4j.selectors"; //$NON-NLS-1$ - - public static final String TYPE = "tcp"; //$NON-NLS-1$ - - public TCPSelectorFactory() - { - super(PRODUCT_GROUP, TYPE); - } - - public TCPSelector create(String description) - { - return new TCPSelector(); - } - - public static TCPSelector get(IManagedContainer container, String description) - { - return (TCPSelector)container.getElement(PRODUCT_GROUP, TYPE, 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.internal.tcp;
+
+import org.eclipse.net4j.util.container.IManagedContainer;
+import org.eclipse.net4j.util.factory.Factory;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPSelectorFactory extends Factory
+{
+ public static final String PRODUCT_GROUP = "org.eclipse.net4j.selectors"; //$NON-NLS-1$
+
+ public static final String TYPE = "tcp"; //$NON-NLS-1$
+
+ public TCPSelectorFactory()
+ {
+ super(PRODUCT_GROUP, TYPE);
+ }
+
+ public TCPSelector create(String description)
+ {
+ return new TCPSelector();
+ }
+
+ public static TCPSelector get(IManagedContainer container, String description)
+ {
+ return (TCPSelector)container.getElement(PRODUCT_GROUP, TYPE, description);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorInjector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorInjector.java index 6a38b08c9d..ab7fa1ae16 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorInjector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPSelectorInjector.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.internal.tcp; - -import org.eclipse.net4j.util.container.IElementProcessor; -import org.eclipse.net4j.util.container.IManagedContainer; - -/** - * @author Eike Stepper - */ -public class TCPSelectorInjector implements IElementProcessor -{ - public static final String TYPE = null; - - public TCPSelectorInjector() - { - } - - public Object process(IManagedContainer container, String productGroup, String factoryType, String description, - Object element) - { - if (element instanceof TCPAcceptor) - { - TCPAcceptor acceptor = (TCPAcceptor)element; - if (acceptor.getSelector() == null) - { - acceptor.setSelector(getSelector(container)); - } - } - else if (element instanceof TCPConnector) - { - TCPConnector connector = (TCPConnector)element; - if (connector.getSelector() == null) - { - connector.setSelector(getSelector(container)); - } - } - - return element; - } - - protected TCPSelector getSelector(IManagedContainer container) - { - return TCPSelectorFactory.get(container, 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.tcp;
+
+import org.eclipse.net4j.util.container.IElementProcessor;
+import org.eclipse.net4j.util.container.IManagedContainer;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPSelectorInjector implements IElementProcessor
+{
+ public static final String TYPE = null;
+
+ public TCPSelectorInjector()
+ {
+ }
+
+ public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
+ Object element)
+ {
+ if (element instanceof TCPAcceptor)
+ {
+ TCPAcceptor acceptor = (TCPAcceptor)element;
+ if (acceptor.getSelector() == null)
+ {
+ acceptor.setSelector(getSelector(container));
+ }
+ }
+ else if (element instanceof TCPConnector)
+ {
+ TCPConnector connector = (TCPConnector)element;
+ if (connector.getSelector() == null)
+ {
+ connector.setSelector(getSelector(container));
+ }
+ }
+
+ return element;
+ }
+
+ protected TCPSelector getSelector(IManagedContainer container)
+ {
+ return TCPSelectorFactory.get(container, null);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPServerConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPServerConnector.java index ad57314411..0da83e6dbb 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPServerConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/TCPServerConnector.java @@ -1,94 +1,94 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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.tcp; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPSelector; - -import java.nio.channels.SocketChannel; -import java.text.MessageFormat; - -/** - * @author Eike Stepper - */ -public class TCPServerConnector extends TCPConnector -{ - private TCPAcceptor acceptor; - - public TCPServerConnector(TCPAcceptor acceptor) - { - this.acceptor = acceptor; - } - - public TCPAcceptor getAcceptor() - { - return acceptor; - } - - @Override - public Location getLocation() - { - return Location.SERVER; - } - - @Override - public String getHost() - { - try - { - return getSocketChannel().socket().getInetAddress().getHostAddress(); - } - catch (RuntimeException ex) - { - return null; - } - } - - @Override - public int getPort() - { - try - { - return getSocketChannel().socket().getPort(); - } - catch (RuntimeException ex) - { - return 0; - } - } - - @Override - public String toString() - { - if (getUserID() == null) - { - return MessageFormat.format("TCPServerConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$ - } - - return MessageFormat.format("TCPServerConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$ - } - - @Override - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel) - { - super.handleRegistration(selector, socketChannel); - - try - { - acceptor.addConnector(this); - } - catch (Exception ex) - { - OM.LOG.error(ex); - deactivateAsync(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this 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.tcp;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPSelector;
+
+import java.nio.channels.SocketChannel;
+import java.text.MessageFormat;
+
+/**
+ * @author Eike Stepper
+ */
+public class TCPServerConnector extends TCPConnector
+{
+ private TCPAcceptor acceptor;
+
+ public TCPServerConnector(TCPAcceptor acceptor)
+ {
+ this.acceptor = acceptor;
+ }
+
+ public TCPAcceptor getAcceptor()
+ {
+ return acceptor;
+ }
+
+ @Override
+ public Location getLocation()
+ {
+ return Location.SERVER;
+ }
+
+ @Override
+ public String getHost()
+ {
+ try
+ {
+ return getSocketChannel().socket().getInetAddress().getHostAddress();
+ }
+ catch (RuntimeException ex)
+ {
+ return null;
+ }
+ }
+
+ @Override
+ public int getPort()
+ {
+ try
+ {
+ return getSocketChannel().socket().getPort();
+ }
+ catch (RuntimeException ex)
+ {
+ return 0;
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ if (getUserID() == null)
+ {
+ return MessageFormat.format("TCPServerConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$
+ }
+
+ return MessageFormat.format("TCPServerConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$
+ }
+
+ @Override
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ super.handleRegistration(selector, socketChannel);
+
+ try
+ {
+ acceptor.addConnector(this);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/bundle/OM.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/bundle/OM.java index a832b6380d..2ec61bc236 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/bundle/OM.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/bundle/OM.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.internal.tcp.bundle; - -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.OMLogger; -import org.eclipse.net4j.util.om.trace.OMTracer; - -/** - * 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.tcp"; //$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_SSLBUFFER = DEBUG.tracer("sslbuffer"); //$NON-NLS-1$ - - public static final OMLogger LOG = BUNDLE.logger(); - - /** - * @since 3.1 - */ - public static final String DEFAULT_PORT_PROPERTY = BUNDLE_ID + ".port"; - - /** - * @since 3.1 - */ - public static final int DEFAULT_PORT = 2036; - - public static int getDefaultPort() - { - try - { - String property = BUNDLE.getPlatform().getProperty(DEFAULT_PORT_PROPERTY); - if (property != null) - { - return Integer.valueOf(property); - } - } - catch (Exception ex) - { - OM.LOG.error(ex); - } - - return DEFAULT_PORT; - } - - /** - * @author Eike Stepper - */ - public static final class Activator extends OSGiActivator - { - public Activator() - { - super(BUNDLE); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this 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.tcp.bundle;
+
+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.OMLogger;
+import org.eclipse.net4j.util.om.trace.OMTracer;
+
+/**
+ * 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.tcp"; //$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_SSLBUFFER = DEBUG.tracer("sslbuffer"); //$NON-NLS-1$
+
+ public static final OMLogger LOG = BUNDLE.logger();
+
+ /**
+ * @since 3.1
+ */
+ public static final String DEFAULT_PORT_PROPERTY = BUNDLE_ID + ".port";
+
+ /**
+ * @since 3.1
+ */
+ public static final int DEFAULT_PORT = 2036;
+
+ public static int getDefaultPort()
+ {
+ try
+ {
+ String property = BUNDLE.getPlatform().getProperty(DEFAULT_PORT_PROPERTY);
+ if (property != null)
+ {
+ return Integer.valueOf(property);
+ }
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ }
+
+ return DEFAULT_PORT;
+ }
+
+ /**
+ * @author Eike Stepper
+ */
+ public static final class Activator extends OSGiActivator
+ {
+ public Activator()
+ {
+ super(BUNDLE);
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/Messages.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/Messages.java index f3380d04f4..793289a98a 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/Messages.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/Messages.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.internal.tcp.messages; - -import java.util.MissingResourceException; -import java.util.ResourceBundle; - -/** - * @author Eike Stepper - */ -public class Messages -{ - private static final String BUNDLE_NAME = "org.eclipse.net4j.internal.tcp.messages.messages"; //$NON-NLS-1$ - - private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); - - private Messages() - { - } - - public static String getString(String key) - { - try - { - return RESOURCE_BUNDLE.getString(key); - } - catch (MissingResourceException e) - { - return '!' + key + '!'; - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this 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.tcp.messages;
+
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+/**
+ * @author Eike Stepper
+ */
+public class Messages
+{
+ private static final String BUNDLE_NAME = "org.eclipse.net4j.internal.tcp.messages.messages"; //$NON-NLS-1$
+
+ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
+
+ private Messages()
+ {
+ }
+
+ public static String getString(String key)
+ {
+ try
+ {
+ return RESOURCE_BUNDLE.getString(key);
+ }
+ catch (MissingResourceException e)
+ {
+ return '!' + key + '!';
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/messages.properties b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/messages.properties index 8814d3ae7f..32f58248ce 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/messages.properties +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/messages/messages.properties @@ -1,3 +1,12 @@ -ControlChannel_0=Registration timeout after {0} milliseconds -ControlChannel_4=Could not open channel -TCPConnector.6=Connector negotiation failed: +# Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+# All rights reserved. This program and the accompanying materials
+# are made available under the terms of the Eclipse Public License v1.0
+# which accompanies this distribution, and is available at
+# http://www.eclipse.org/legal/epl-v10.html
+#
+# Contributors:
+# Eike Stepper - initial API and implementation
+
+ControlChannel_0=Registration timeout after {0} milliseconds
+ControlChannel_4=Could not open channel
+TCPConnector.6=Connector negotiation failed:
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptor.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptor.java index 22f4fe9e0f..5eaf96acc3 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptor.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptor.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: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.TCPAcceptor; -import org.eclipse.net4j.internal.tcp.TCPConnector; - -import java.text.MessageFormat; - -/** - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLAcceptor extends TCPAcceptor -{ - @Override - public String toString() - { - return MessageFormat.format("SSLAcceptor[{0}:{1}]", getAddress(), getPort()); //$NON-NLS-1$ - } - - @Override - protected TCPConnector createConnector() - { - return new SSLServerConnector(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:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.TCPAcceptor;
+import org.eclipse.net4j.internal.tcp.TCPConnector;
+
+import java.text.MessageFormat;
+
+/**
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLAcceptor extends TCPAcceptor
+{
+ @Override
+ public String toString()
+ {
+ return MessageFormat.format("SSLAcceptor[{0}:{1}]", getAddress(), getPort()); //$NON-NLS-1$
+ }
+
+ @Override
+ protected TCPConnector createConnector()
+ {
+ return new SSLServerConnector(this);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptorFactory.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptorFactory.java index de33ad16cc..38b1259445 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptorFactory.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLAcceptorFactory.java @@ -1,36 +1,36 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.TCPAcceptor; -import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory; - -/** - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLAcceptorFactory extends TCPAcceptorFactory -{ - public static final String TYPE = "ssl"; //$NON-NLS-1$ - - public SSLAcceptorFactory() - { - super(TYPE); - } - - @Override - protected TCPAcceptor createAcceptor() - { - return new SSLAcceptor(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.TCPAcceptor;
+import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory;
+
+/**
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLAcceptorFactory extends TCPAcceptorFactory
+{
+ public static final String TYPE = "ssl"; //$NON-NLS-1$
+
+ public SSLAcceptorFactory()
+ {
+ super(TYPE);
+ }
+
+ @Override
+ protected TCPAcceptor createAcceptor()
+ {
+ return new SSLAcceptor();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBuffer.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBuffer.java index 62a88c4288..bb85bbb6d4 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBuffer.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBuffer.java @@ -1,206 +1,206 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.buffer.BufferState; -import org.eclipse.net4j.buffer.IBuffer; -import org.eclipse.net4j.buffer.IBufferProvider; -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.util.StringUtil; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import org.eclipse.internal.net4j.buffer.Buffer; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SocketChannel; - -/** - * All source code same as org.eclipse.internal.net4j.buffer.Buffer except adding SSLEngineManager to constructor and - * overriding startGetting and write method in order to attach the SSL functional. - * - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLBuffer extends Buffer -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_SSLBUFFER, SSLBuffer.class); - - private SSLEngineManager sslEngineManager; - - public SSLBuffer(IBufferProvider provider, short capacity, SSLEngineManager sslEngineManager) - { - super(provider, capacity); - this.sslEngineManager = sslEngineManager; - } - - @Override - public ByteBuffer startGetting(SocketChannel socketChannel) throws IOException - { - BufferState state = getState(); - if (state != BufferState.INITIAL && state != BufferState.READING_HEADER && state != BufferState.READING_BODY) - { - throw new IllegalStateException(toString()); - } - - int readSize = 0; - - if (sslEngineManager.getAppRecvBuf().position() > 0) - { - readSize = sslEngineManager.getAppRecvBuf().position(); - } - else - { - readSize = sslEngineManager.read(socketChannel); - } - - if (readSize > 0) - { - ByteBuffer buf = sslEngineManager.getAppRecvBuf(); - buf.flip(); - - int limit = buf.limit(); - ByteBuffer byteBuffer = getByteBuffer(); - - int capacity = byteBuffer.capacity(); - limit = limit > capacity ? capacity : limit; - - byteBuffer.put(buf.array(), 0, limit); - buf.position(limit); - buf.compact(); - byteBuffer.flip(); - - setChannelID(byteBuffer.getShort()); - short payloadSize = byteBuffer.getShort(); - - if (payloadSize < 0) - { - setEOS(true); - payloadSize = (short)-payloadSize; - } - - payloadSize -= EOS_OFFSET; - - byteBuffer.position(IBuffer.HEADER_SIZE); - setState(BufferState.READING_HEADER); - - byteBuffer.compact(); - byteBuffer.limit(payloadSize); - setState(BufferState.READING_BODY); - - byteBuffer.flip(); - setState(BufferState.GETTING); - - return byteBuffer; - } - else if (readSize < 0) - { - throw new ClosedChannelException(); - } - - return null; - } - - /** - * @return <code>true</code> if the buffer has been completely written, <code>false</code> otherwise. - */ - @Override - public boolean write(SocketChannel socketChannel) throws IOException - { - try - { - - if (sslEngineManager.getPacketSendBuf().position() > 0) - { - sslEngineManager.handleWrite(socketChannel); - - if (sslEngineManager.getPacketSendBuf().position() > 0) - { - clear(); - return false; - } - - clear(); - return true; - } - - BufferState state = getState(); - if (state != BufferState.PUTTING && state != BufferState.WRITING) - { - throw new IllegalStateException(toString()); - } - - ByteBuffer byteBuffer = getByteBuffer(); - if (state == BufferState.PUTTING) - { - if (getChannelID() == NO_CHANNEL) - { - throw new IllegalStateException("channelID == NO_CHANNEL"); //$NON-NLS-1$ - } - - int payloadSize = byteBuffer.position() - IBuffer.HEADER_SIZE + EOS_OFFSET; - if (isEOS()) - { - payloadSize = -payloadSize; - } - - if (TRACER.isEnabled()) - { - TRACER.trace("Writing " + (Math.abs(payloadSize) - 1) + " bytes" //$NON-NLS-1$ //$NON-NLS-2$ - + (isEOS() ? " (EOS)" : "") + StringUtil.NL + formatContent(false)); //$NON-NLS-1$ //$NON-NLS-2$ - } - - byteBuffer.flip(); - byteBuffer.putShort(getChannelID()); - byteBuffer.putShort((short)payloadSize); - byteBuffer.position(0); - setState(BufferState.WRITING); - } - - sslEngineManager.getAppSendBuf().put(byteBuffer); - sslEngineManager.write(socketChannel); - - if (sslEngineManager.getPacketSendBuf().position() > 0) - { - clear(); - return false; - } - - clear(); - return true; - } - catch (IOException ex) - { - handleError(ex); - throw ex; - } - catch (RuntimeException ex) - { - handleError(ex); - throw ex; - } - catch (Error ex) - { - handleError(ex); - throw ex; - } - } - - @Override - public void dispose() - { - sslEngineManager = null; - super.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:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.buffer.BufferState;
+import org.eclipse.net4j.buffer.IBuffer;
+import org.eclipse.net4j.buffer.IBufferProvider;
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.util.StringUtil;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import org.eclipse.internal.net4j.buffer.Buffer;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SocketChannel;
+
+/**
+ * All source code same as org.eclipse.internal.net4j.buffer.Buffer except adding SSLEngineManager to constructor and
+ * overriding startGetting and write method in order to attach the SSL functional.
+ *
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLBuffer extends Buffer
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_SSLBUFFER, SSLBuffer.class);
+
+ private SSLEngineManager sslEngineManager;
+
+ public SSLBuffer(IBufferProvider provider, short capacity, SSLEngineManager sslEngineManager)
+ {
+ super(provider, capacity);
+ this.sslEngineManager = sslEngineManager;
+ }
+
+ @Override
+ public ByteBuffer startGetting(SocketChannel socketChannel) throws IOException
+ {
+ BufferState state = getState();
+ if (state != BufferState.INITIAL && state != BufferState.READING_HEADER && state != BufferState.READING_BODY)
+ {
+ throw new IllegalStateException(toString());
+ }
+
+ int readSize = 0;
+
+ if (sslEngineManager.getAppRecvBuf().position() > 0)
+ {
+ readSize = sslEngineManager.getAppRecvBuf().position();
+ }
+ else
+ {
+ readSize = sslEngineManager.read(socketChannel);
+ }
+
+ if (readSize > 0)
+ {
+ ByteBuffer buf = sslEngineManager.getAppRecvBuf();
+ buf.flip();
+
+ int limit = buf.limit();
+ ByteBuffer byteBuffer = getByteBuffer();
+
+ int capacity = byteBuffer.capacity();
+ limit = limit > capacity ? capacity : limit;
+
+ byteBuffer.put(buf.array(), 0, limit);
+ buf.position(limit);
+ buf.compact();
+ byteBuffer.flip();
+
+ setChannelID(byteBuffer.getShort());
+ short payloadSize = byteBuffer.getShort();
+
+ if (payloadSize < 0)
+ {
+ setEOS(true);
+ payloadSize = (short)-payloadSize;
+ }
+
+ payloadSize -= EOS_OFFSET;
+
+ byteBuffer.position(IBuffer.HEADER_SIZE);
+ setState(BufferState.READING_HEADER);
+
+ byteBuffer.compact();
+ byteBuffer.limit(payloadSize);
+ setState(BufferState.READING_BODY);
+
+ byteBuffer.flip();
+ setState(BufferState.GETTING);
+
+ return byteBuffer;
+ }
+ else if (readSize < 0)
+ {
+ throw new ClosedChannelException();
+ }
+
+ return null;
+ }
+
+ /**
+ * @return <code>true</code> if the buffer has been completely written, <code>false</code> otherwise.
+ */
+ @Override
+ public boolean write(SocketChannel socketChannel) throws IOException
+ {
+ try
+ {
+
+ if (sslEngineManager.getPacketSendBuf().position() > 0)
+ {
+ sslEngineManager.handleWrite(socketChannel);
+
+ if (sslEngineManager.getPacketSendBuf().position() > 0)
+ {
+ clear();
+ return false;
+ }
+
+ clear();
+ return true;
+ }
+
+ BufferState state = getState();
+ if (state != BufferState.PUTTING && state != BufferState.WRITING)
+ {
+ throw new IllegalStateException(toString());
+ }
+
+ ByteBuffer byteBuffer = getByteBuffer();
+ if (state == BufferState.PUTTING)
+ {
+ if (getChannelID() == NO_CHANNEL)
+ {
+ throw new IllegalStateException("channelID == NO_CHANNEL"); //$NON-NLS-1$
+ }
+
+ int payloadSize = byteBuffer.position() - IBuffer.HEADER_SIZE + EOS_OFFSET;
+ if (isEOS())
+ {
+ payloadSize = -payloadSize;
+ }
+
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Writing " + (Math.abs(payloadSize) - 1) + " bytes" //$NON-NLS-1$ //$NON-NLS-2$
+ + (isEOS() ? " (EOS)" : "") + StringUtil.NL + formatContent(false)); //$NON-NLS-1$ //$NON-NLS-2$
+ }
+
+ byteBuffer.flip();
+ byteBuffer.putShort(getChannelID());
+ byteBuffer.putShort((short)payloadSize);
+ byteBuffer.position(0);
+ setState(BufferState.WRITING);
+ }
+
+ sslEngineManager.getAppSendBuf().put(byteBuffer);
+ sslEngineManager.write(socketChannel);
+
+ if (sslEngineManager.getPacketSendBuf().position() > 0)
+ {
+ clear();
+ return false;
+ }
+
+ clear();
+ return true;
+ }
+ catch (IOException ex)
+ {
+ handleError(ex);
+ throw ex;
+ }
+ catch (RuntimeException ex)
+ {
+ handleError(ex);
+ throw ex;
+ }
+ catch (Error ex)
+ {
+ handleError(ex);
+ throw ex;
+ }
+ }
+
+ @Override
+ public void dispose()
+ {
+ sslEngineManager = null;
+ super.dispose();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBufferFactory.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBufferFactory.java index 402c13a606..8e66b212a3 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBufferFactory.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLBufferFactory.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: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.Net4jUtil; -import org.eclipse.net4j.buffer.IBuffer; - -import org.eclipse.internal.net4j.buffer.BufferFactory; - -/** - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLBufferFactory extends BufferFactory -{ - private SSLEngineManager sslEngineManager; - - public SSLBufferFactory(short bufferCapacity) - { - super(bufferCapacity); - } - - public SSLBufferFactory(SSLEngineManager sslEngineManager) - { - this(Net4jUtil.DEFAULT_BUFFER_CAPACITY); - this.sslEngineManager = sslEngineManager; - } - - @Override - protected IBuffer doProvideBuffer() - { - return new SSLBuffer(this, getBufferCapacity(), sslEngineManager); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.Net4jUtil;
+import org.eclipse.net4j.buffer.IBuffer;
+
+import org.eclipse.internal.net4j.buffer.BufferFactory;
+
+/**
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLBufferFactory extends BufferFactory
+{
+ private SSLEngineManager sslEngineManager;
+
+ public SSLBufferFactory(short bufferCapacity)
+ {
+ super(bufferCapacity);
+ }
+
+ public SSLBufferFactory(SSLEngineManager sslEngineManager)
+ {
+ this(Net4jUtil.DEFAULT_BUFFER_CAPACITY);
+ this.sslEngineManager = sslEngineManager;
+ }
+
+ @Override
+ protected IBuffer doProvideBuffer()
+ {
+ return new SSLBuffer(this, getBufferCapacity(), sslEngineManager);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLClientConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLClientConnector.java index 9d0bf9c316..d4ea540087 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLClientConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLClientConnector.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: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPSelector; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.nio.channels.SocketChannel; -import java.text.MessageFormat; - -/** - * SSLClientConnector responses to be connector on client side and it handles about connecting to the server connector. - * - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLClientConnector extends SSLConnector -{ - public SSLClientConnector() - { - try - { - SocketChannel socketChannel = SocketChannel.open(); - socketChannel.socket().setReuseAddress(true); - // socketChannel.socket().setKeepAlive(true); - socketChannel.configureBlocking(false); - setSocketChannel(socketChannel); - } - catch (IOException ex) - { - OM.LOG.error(ex); - } - } - - @Override - public Location getLocation() - { - return Location.CLIENT; - } - - @Override - public String toString() - { - if (getUserID() == null) - { - return MessageFormat.format("SSLClientConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$ - } - - return MessageFormat.format("SSLClientConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$ - } - - @Override - protected void doBeforeActivate() throws Exception - { - super.doBeforeActivate(); - if (getHost() == null) - { - throw new IllegalStateException("host == null"); //$NON-NLS-1$ - } - - if (getPort() == 0) - { - throw new IllegalStateException("port == 0"); //$NON-NLS-1$ - } - } - - @Override - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel) - { - super.handleRegistration(selector, socketChannel); - - try - { - InetAddress addr = InetAddress.getByName(getHost()); - InetSocketAddress sAddr = new InetSocketAddress(addr, getPort()); - getSocketChannel().connect(sAddr); - } - catch (Exception ex) - { - OM.LOG.error(ex); - deactivateAsync(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPSelector;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.channels.SocketChannel;
+import java.text.MessageFormat;
+
+/**
+ * SSLClientConnector responses to be connector on client side and it handles about connecting to the server connector.
+ *
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLClientConnector extends SSLConnector
+{
+ public SSLClientConnector()
+ {
+ try
+ {
+ SocketChannel socketChannel = SocketChannel.open();
+ socketChannel.socket().setReuseAddress(true);
+ // socketChannel.socket().setKeepAlive(true);
+ socketChannel.configureBlocking(false);
+ setSocketChannel(socketChannel);
+ }
+ catch (IOException ex)
+ {
+ OM.LOG.error(ex);
+ }
+ }
+
+ @Override
+ public Location getLocation()
+ {
+ return Location.CLIENT;
+ }
+
+ @Override
+ public String toString()
+ {
+ if (getUserID() == null)
+ {
+ return MessageFormat.format("SSLClientConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$
+ }
+
+ return MessageFormat.format("SSLClientConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$
+ }
+
+ @Override
+ protected void doBeforeActivate() throws Exception
+ {
+ super.doBeforeActivate();
+ if (getHost() == null)
+ {
+ throw new IllegalStateException("host == null"); //$NON-NLS-1$
+ }
+
+ if (getPort() == 0)
+ {
+ throw new IllegalStateException("port == 0"); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ super.handleRegistration(selector, socketChannel);
+
+ try
+ {
+ InetAddress addr = InetAddress.getByName(getHost());
+ InetSocketAddress sAddr = new InetSocketAddress(addr, getPort());
+ getSocketChannel().connect(sAddr);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnector.java index db89d2a89a..f7fa38e7a8 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnector.java @@ -1,235 +1,235 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.TCPConnector; -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPSelector; -import org.eclipse.net4j.tcp.ssl.SSLUtil; -import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; - -/** - * SSLConnector responses to perform tasks same as TCPConnector but it attached the SSL functionality into read and - * write method. - * - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLConnector extends TCPConnector -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, SSLConnector.class); - - private SSLEngineManager sslEngineManager; - - @Override - public String getProtocolString() - { - return "ssl://"; - } - - @Override - public void handleConnect(ITCPSelector selector, SocketChannel channel) - { - super.handleConnect(selector, channel); - - if (!sslEngineManager.isHandshakeComplete() && isClient()) - { - getConfig().getReceiveExecutor().execute(createHandShakeTask(channel)); - } - } - - @Override - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel) - { - super.handleRegistration(selector, socketChannel); - - if (!sslEngineManager.isHandshakeComplete() && isServer()) - { - getConfig().getReceiveExecutor().execute(createHandShakeTask(socketChannel)); - } - } - - @Override - public void handleRead(ITCPSelector selector, SocketChannel socketChannel) - { - waitForHandShakeFinish(); - super.handleRead(selector, socketChannel); - checkRehandShake(socketChannel); - - // Handle the left data from reading multiple data at once time. - while (sslEngineManager.getPacketRecvBuf().position() > 0) - { - super.handleRead(selector, socketChannel); - checkRehandShake(socketChannel); - } - } - - @Override - public void handleWrite(ITCPSelector selector, SocketChannel socketChannel) - { - waitForHandShakeFinish(); - super.handleWrite(selector, socketChannel); - checkRehandShake(socketChannel); - } - - @Override - protected void doActivate() throws Exception - { - try - { - boolean isClient = isClient(); - - String host = getHost(); - int port = getPort(); - sslEngineManager = new SSLEngineManager(isClient, host, port, getConfig().getReceiveExecutor()); - - // Set the buffer provider of the config instance in order to replace - // BufferFactory instance with SSLBufferFactory instance. - getConfig().setBufferProvider(new SSLBufferFactory(sslEngineManager)); - } - catch (Exception ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Cannot activate the ssl engine.", ex); //$NON-NLS-1$ - } - - throw ex; - } - - super.doActivate(); - } - - @Override - protected void doDeactivate() throws Exception - { - try - { - sslEngineManager.close(); - } - catch (Exception ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace("Cannot deactivate the ssl engine.", ex); //$NON-NLS-1$ - } - } - finally - { - super.doDeactivate(); - } - } - - /** - * Toggles between OP_READ and OP_WRITE - * <p> - * (Having both OP_READ and OP_WRITE interests on a socketChannel is not a good idea when the channel is used for - * TLS/SSL communications.) - */ - @Override - protected void doOrderWriteInterest(boolean on) - { - ITCPSelector selector = getSelector(); - SelectionKey selectionKey = getSelectionKey(); - - if (on) - { - selector.orderReadInterest(selectionKey, isClient(), false); - selector.orderWriteInterest(selectionKey, isClient(), true); - } - else - { - // Note: order is different from above! - selector.orderWriteInterest(selectionKey, isClient(), false); - selector.orderReadInterest(selectionKey, isClient(), true); - } - } - - private void checkRehandShake(SocketChannel socketChannel) - { - if (!isClosed()) - { - try - { - sslEngineManager.checkRehandShake(socketChannel); - } - catch (Exception ex) - { - deactivateAsync(); - } - } - } - - private void waitForHandShakeFinish() - { - // Wait until handshake finished. If handshake finish it will not enter this loop. - while (!sslEngineManager.isHandshakeComplete()) - { - if (isNegotiating()) - { - ConcurrencyUtil.sleep(SSLUtil.getHandShakeWaitTime()); - } - else if (!isNegotiating() && !isActive()) - { - // Prevent sleeping and reading forever. - break; - } - else - { - Thread.yield(); - } - } - - if (!isNegotiating() && !isActive()) - { - try - { - deactivateAsync(); - } - catch (Exception ex) - { - OM.LOG.warn(ex); - } - } - } - - private Runnable createHandShakeTask(SocketChannel channel) - { - final SocketChannel socket = channel; - Runnable task = new Runnable() - { - public void run() - { - try - { - sslEngineManager.checkInitialHandshake(socket); - } - catch (Exception ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace("ssl cannot handshake.", ex); //$NON-NLS-1$ - } - - deferredActivate(false); - } - } - }; - - return task; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.TCPConnector;
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPSelector;
+import org.eclipse.net4j.tcp.ssl.SSLUtil;
+import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import java.nio.channels.SelectionKey;
+import java.nio.channels.SocketChannel;
+
+/**
+ * SSLConnector responses to perform tasks same as TCPConnector but it attached the SSL functionality into read and
+ * write method.
+ *
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLConnector extends TCPConnector
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, SSLConnector.class);
+
+ private SSLEngineManager sslEngineManager;
+
+ @Override
+ public String getProtocolString()
+ {
+ return "ssl://";
+ }
+
+ @Override
+ public void handleConnect(ITCPSelector selector, SocketChannel channel)
+ {
+ super.handleConnect(selector, channel);
+
+ if (!sslEngineManager.isHandshakeComplete() && isClient())
+ {
+ getConfig().getReceiveExecutor().execute(createHandShakeTask(channel));
+ }
+ }
+
+ @Override
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ super.handleRegistration(selector, socketChannel);
+
+ if (!sslEngineManager.isHandshakeComplete() && isServer())
+ {
+ getConfig().getReceiveExecutor().execute(createHandShakeTask(socketChannel));
+ }
+ }
+
+ @Override
+ public void handleRead(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ waitForHandShakeFinish();
+ super.handleRead(selector, socketChannel);
+ checkRehandShake(socketChannel);
+
+ // Handle the left data from reading multiple data at once time.
+ while (sslEngineManager.getPacketRecvBuf().position() > 0)
+ {
+ super.handleRead(selector, socketChannel);
+ checkRehandShake(socketChannel);
+ }
+ }
+
+ @Override
+ public void handleWrite(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ waitForHandShakeFinish();
+ super.handleWrite(selector, socketChannel);
+ checkRehandShake(socketChannel);
+ }
+
+ @Override
+ protected void doActivate() throws Exception
+ {
+ try
+ {
+ boolean isClient = isClient();
+
+ String host = getHost();
+ int port = getPort();
+ sslEngineManager = new SSLEngineManager(isClient, host, port, getConfig().getReceiveExecutor());
+
+ // Set the buffer provider of the config instance in order to replace
+ // BufferFactory instance with SSLBufferFactory instance.
+ getConfig().setBufferProvider(new SSLBufferFactory(sslEngineManager));
+ }
+ catch (Exception ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Cannot activate the ssl engine.", ex); //$NON-NLS-1$
+ }
+
+ throw ex;
+ }
+
+ super.doActivate();
+ }
+
+ @Override
+ protected void doDeactivate() throws Exception
+ {
+ try
+ {
+ sslEngineManager.close();
+ }
+ catch (Exception ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Cannot deactivate the ssl engine.", ex); //$NON-NLS-1$
+ }
+ }
+ finally
+ {
+ super.doDeactivate();
+ }
+ }
+
+ /**
+ * Toggles between OP_READ and OP_WRITE
+ * <p>
+ * (Having both OP_READ and OP_WRITE interests on a socketChannel is not a good idea when the channel is used for
+ * TLS/SSL communications.)
+ */
+ @Override
+ protected void doOrderWriteInterest(boolean on)
+ {
+ ITCPSelector selector = getSelector();
+ SelectionKey selectionKey = getSelectionKey();
+
+ if (on)
+ {
+ selector.orderReadInterest(selectionKey, isClient(), false);
+ selector.orderWriteInterest(selectionKey, isClient(), true);
+ }
+ else
+ {
+ // Note: order is different from above!
+ selector.orderWriteInterest(selectionKey, isClient(), false);
+ selector.orderReadInterest(selectionKey, isClient(), true);
+ }
+ }
+
+ private void checkRehandShake(SocketChannel socketChannel)
+ {
+ if (!isClosed())
+ {
+ try
+ {
+ sslEngineManager.checkRehandShake(socketChannel);
+ }
+ catch (Exception ex)
+ {
+ deactivateAsync();
+ }
+ }
+ }
+
+ private void waitForHandShakeFinish()
+ {
+ // Wait until handshake finished. If handshake finish it will not enter this loop.
+ while (!sslEngineManager.isHandshakeComplete())
+ {
+ if (isNegotiating())
+ {
+ ConcurrencyUtil.sleep(SSLUtil.getHandShakeWaitTime());
+ }
+ else if (!isNegotiating() && !isActive())
+ {
+ // Prevent sleeping and reading forever.
+ break;
+ }
+ else
+ {
+ Thread.yield();
+ }
+ }
+
+ if (!isNegotiating() && !isActive())
+ {
+ try
+ {
+ deactivateAsync();
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.warn(ex);
+ }
+ }
+ }
+
+ private Runnable createHandShakeTask(SocketChannel channel)
+ {
+ final SocketChannel socket = channel;
+ Runnable task = new Runnable()
+ {
+ public void run()
+ {
+ try
+ {
+ sslEngineManager.checkInitialHandshake(socket);
+ }
+ catch (Exception ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("ssl cannot handshake.", ex); //$NON-NLS-1$
+ }
+
+ deferredActivate(false);
+ }
+ }
+ };
+
+ return task;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnectorFactory.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnectorFactory.java index 48286ccb43..26ac8e9d64 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnectorFactory.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLConnectorFactory.java @@ -1,36 +1,36 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.TCPConnector; -import org.eclipse.net4j.internal.tcp.TCPConnectorFactory; - -/** - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLConnectorFactory extends TCPConnectorFactory -{ - public static final String TYPE = SSLAcceptorFactory.TYPE; - - public SSLConnectorFactory() - { - super(TYPE); - } - - @Override - protected TCPConnector createConnector() - { - return new SSLClientConnector(); - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.TCPConnector;
+import org.eclipse.net4j.internal.tcp.TCPConnectorFactory;
+
+/**
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLConnectorFactory extends TCPConnectorFactory
+{
+ public static final String TYPE = SSLAcceptorFactory.TYPE;
+
+ public SSLConnectorFactory()
+ {
+ super(TYPE);
+ }
+
+ @Override
+ protected TCPConnector createConnector()
+ {
+ return new SSLClientConnector();
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLEngineManager.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLEngineManager.java index c91f39d017..4f5f0977a8 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLEngineManager.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLEngineManager.java @@ -1,487 +1,487 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ssl.SSLUtil; -import org.eclipse.net4j.util.om.trace.ContextTracer; - -import javax.net.ssl.SSLEngine; -import javax.net.ssl.SSLEngineResult; -import javax.net.ssl.SSLEngineResult.HandshakeStatus; -import javax.net.ssl.SSLEngineResult.Status; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SocketChannel; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; -import java.util.concurrent.Executor; - -/** - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLEngineManager -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, SSLEngineManager.class); - - /** - * An optional executor to be used this class. - */ - private Executor executor; - - private SSLEngine sslEngine; - - private boolean handshakeComplete; - - private boolean needRehandShake; - - private ByteBuffer appSendBuf; - - private ByteBuffer appRecvBuf; - - private ByteBuffer packetSendBuf; - - private ByteBuffer packetRecvBuf; - - private SSLEngineResult engineResult; - - private SSLEngineResult.HandshakeStatus handshakeStatus; - - private Object readLock = new ReadLock(); - - private Object writeLock = new WriteLock(); - - public SSLEngineManager(boolean client, String host, int port, Executor executor) throws NoSuchAlgorithmException, - KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException - { - this.executor = executor; - - sslEngine = SSLUtil.createSSLEngine(client, host, port); - sslEngine.beginHandshake(); - - SSLSession session = sslEngine.getSession(); - - int applicationBufferSize = session.getApplicationBufferSize(); - appSendBuf = ByteBuffer.allocate(applicationBufferSize); - appRecvBuf = ByteBuffer.allocate(applicationBufferSize); - - int packetBufferSize = session.getPacketBufferSize(); - packetSendBuf = ByteBuffer.allocate(packetBufferSize); - packetRecvBuf = ByteBuffer.allocate(packetBufferSize); - } - - public Executor getExecutor() - { - return executor; - } - - public ByteBuffer getAppSendBuf() - { - return appSendBuf; - } - - public void setAppSendBuf(ByteBuffer appSendBuf) - { - this.appSendBuf = appSendBuf; - } - - public ByteBuffer getAppRecvBuf() - { - return appRecvBuf; - } - - public void setAppRecvBuf(ByteBuffer appRecvBuf) - { - this.appRecvBuf = appRecvBuf; - } - - public ByteBuffer getPacketSendBuf() - { - return packetSendBuf; - } - - public void setPacketSendBuf(ByteBuffer packetSendBuf) - { - this.packetSendBuf = packetSendBuf; - } - - public ByteBuffer getPacketRecvBuf() - { - return packetRecvBuf; - } - - public void setPacketRecvBuf(ByteBuffer packetRecvBuf) - { - this.packetRecvBuf = packetRecvBuf; - } - - public synchronized void checkInitialHandshake(SocketChannel socketChannel) throws Exception - { - if (!handshakeComplete) - { - try - { - int counter = 0; - while (!isHandshakeFinished() && counter <= SSLUtil.getHandShakeTimeOut()) - { - performHandshake(socketChannel, needRehandShake); - counter = handshakeStatus == HandshakeStatus.NEED_UNWRAP ? counter++ : 0; - } - - if (!isHandshakeFinished() && counter == SSLUtil.getHandShakeTimeOut()) - { - throw new SSLException("SSL handshake timeout"); - } - } - catch (Exception ex) - { - if (TRACER.isEnabled()) - { - TRACER.trace("SSL handshake incomplete.", ex); //$NON-NLS-1$ - } - - try - { - // Clean the SSLEngine. - close(); - } - catch (IOException ioex) - { - OM.LOG.warn(ioex); - } - - throw ex; - } - - handshakeComplete = true; - } - } - - public int read(SocketChannel socketChannel) throws IOException - { - if (!handshakeComplete) - { - throw new SSLException("Handshake still not completed"); - } - - synchronized (readLock) - { - int readTextCount = appRecvBuf.position(); - - do - { - if (sslEngine.isInboundDone()) - { - return readTextCount > 0 ? readTextCount : -1; - } - - int count = handleRead(socketChannel); - if (count <= 0 && packetRecvBuf.position() == 0) - { - return count; - } - - packetRecvBuf.flip(); - engineResult = sslEngine.unwrap(packetRecvBuf, appRecvBuf); - packetRecvBuf.compact(); - - switch (engineResult.getStatus()) - { - case BUFFER_UNDERFLOW: - continue; - - case BUFFER_OVERFLOW: - if (TRACER.isEnabled()) - { - TRACER.trace("Buffer overflow on read method."); //$NON-NLS-1$ - } - - return 0; - - case CLOSED: - throw new ClosedChannelException(); - - default: - // OK - } - - readTextCount = appRecvBuf.position(); - } while (engineResult.getStatus() != Status.OK); - - if (sslEngine.isInboundDone()) - { - return -1; - } - - return readTextCount; - } - } - - public int write(SocketChannel socketChannel) throws IOException - { - if (!handshakeComplete) - { - throw new SSLException("Handshake still not completed"); - } - - synchronized (writeLock) - { - int writeCount = 0; - int count = 0; - int appSendBufSize = appSendBuf.position(); - - do - { - appSendBuf.flip(); - engineResult = sslEngine.wrap(appSendBuf, packetSendBuf); - appSendBuf.compact(); - switch (engineResult.getStatus()) - { - case BUFFER_UNDERFLOW: - if (TRACER.isEnabled()) - { - TRACER.trace("Buffer Underflow happen on write method"); //$NON-NLS-1$ - } - - return -1; - - case BUFFER_OVERFLOW: - count = handleWrite(socketChannel); - writeCount += count; - continue; - - case CLOSED: - throw new ClosedChannelException(); - - case OK: - int bytesComsumed = engineResult.bytesConsumed(); - appSendBufSize = appSendBufSize - bytesComsumed; - count = handleWrite(socketChannel); - writeCount += count; - break; - } - } while (engineResult.getStatus() != Status.OK); - - return writeCount; - } - } - - /** - * Write the contents of {@link #packetSendBuf} to the given {@link SocketChannel} - * - * @return the number of bytes actually written - */ - public int handleWrite(SocketChannel socketChannel) throws IOException - { - try - { - packetSendBuf.flip(); - int count = socketChannel.write(packetSendBuf); - packetSendBuf.compact(); - - if (count == -1) - { - throw new ClosedChannelException(); - } - - return count; - } - catch (ClosedChannelException ex) - { - throw ex; - } - catch (IOException ex) - { - throw new ClosedChannelException(); - } - } - - /** - * Read the contents from the given {@link SocketChannel} to {@link #packetSendBuf} - * - * @return the number of bytes actually read - */ - public int handleRead(SocketChannel socketChannel) throws IOException - { - try - { - int count = socketChannel.read(packetRecvBuf); - if (count == -1) - { - throw new ClosedChannelException(); - } - - return count; - } - catch (ClosedChannelException ex) - { - throw ex; - } - catch (IOException ex) - { - throw new ClosedChannelException(); - } - } - - public void close() throws IOException - { - if (sslEngine != null) - { - sslEngine.closeOutbound(); - } - } - - public void checkRehandShake(SocketChannel socket) throws Exception - { - handshakeStatus = engineResult.getHandshakeStatus(); - needRehandShake = handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_TASK - || handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP - || handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP; - - if (needRehandShake) - { - handshakeComplete = false; - } - - checkInitialHandshake(socket); - return; - } - - public boolean isHandshakeComplete() - { - return handshakeComplete; - } - - private boolean isHandshakeFinished() - { - return handshakeStatus != null && handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED; - } - - private boolean performHandshake(SocketChannel socketChannel, boolean rehandShake) throws IOException - { - int nBytes = 0; - if (!rehandShake) - { - handshakeStatus = sslEngine.getHandshakeStatus(); - } - - switch (handshakeStatus) - { - case NEED_WRAP: - appSendBuf.flip(); - engineResult = sslEngine.wrap(appSendBuf, packetSendBuf); - handshakeStatus = engineResult.getHandshakeStatus(); - appSendBuf.compact(); - - switch (engineResult.getStatus()) - { - case BUFFER_OVERFLOW: - nBytes = handleWrite(socketChannel); - break; - - case OK: - while (packetSendBuf.position() > 0) - { - nBytes = handleWrite(socketChannel); - if (nBytes == 0) - { - // Prevent spinning if the channel refused the write - break; - } - } - - break; - - default: - if (TRACER.isEnabled()) - { - TRACER.trace("Need Wrap Operation: cannot handle ssl result status [" + engineResult.getStatus() + "]"); //$NON-NLS-1$ - } - } - - return true; - - case NEED_UNWRAP: - nBytes = handleRead(socketChannel); - - packetRecvBuf.flip(); - engineResult = sslEngine.unwrap(packetRecvBuf, appRecvBuf); - handshakeStatus = engineResult.getHandshakeStatus(); - packetRecvBuf.compact(); - - if (engineResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW && sslEngine.isInboundDone()) - { - return false; - } - - return engineResult.getStatus() != SSLEngineResult.Status.BUFFER_OVERFLOW; - - case NEED_TASK: - executeTasks(); - return true; - - case NOT_HANDSHAKING: - if (TRACER.isEnabled()) - { - TRACER.trace("Not handshaking status occurs."); //$NON-NLS-1$ - } - - throw new ClosedChannelException(); - - case FINISHED: - return false; - } - - return true; - } - - private void executeTasks() - { - Runnable task; - while ((task = sslEngine.getDelegatedTask()) != null) - { - executor.execute(task); - - if (TRACER.isEnabled()) - { - TRACER.trace("Scheduled task: " + task); //$NON-NLS-1$ - } - } - } - - /** - * A separate class for better monitor debugging. - * - * @author Eike Stepper - */ - private static final class ReadLock - { - } - - /** - * A separate class for better monitor debugging. - * - * @author Eike Stepper - */ - private static final class WriteLock - { - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ssl.SSLUtil;
+import org.eclipse.net4j.util.om.trace.ContextTracer;
+
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLEngineResult;
+import javax.net.ssl.SSLEngineResult.HandshakeStatus;
+import javax.net.ssl.SSLEngineResult.Status;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLSession;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SocketChannel;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.util.concurrent.Executor;
+
+/**
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLEngineManager
+{
+ private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, SSLEngineManager.class);
+
+ /**
+ * An optional executor to be used this class.
+ */
+ private Executor executor;
+
+ private SSLEngine sslEngine;
+
+ private boolean handshakeComplete;
+
+ private boolean needRehandShake;
+
+ private ByteBuffer appSendBuf;
+
+ private ByteBuffer appRecvBuf;
+
+ private ByteBuffer packetSendBuf;
+
+ private ByteBuffer packetRecvBuf;
+
+ private SSLEngineResult engineResult;
+
+ private SSLEngineResult.HandshakeStatus handshakeStatus;
+
+ private Object readLock = new ReadLock();
+
+ private Object writeLock = new WriteLock();
+
+ public SSLEngineManager(boolean client, String host, int port, Executor executor) throws NoSuchAlgorithmException,
+ KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException
+ {
+ this.executor = executor;
+
+ sslEngine = SSLUtil.createSSLEngine(client, host, port);
+ sslEngine.beginHandshake();
+
+ SSLSession session = sslEngine.getSession();
+
+ int applicationBufferSize = session.getApplicationBufferSize();
+ appSendBuf = ByteBuffer.allocate(applicationBufferSize);
+ appRecvBuf = ByteBuffer.allocate(applicationBufferSize);
+
+ int packetBufferSize = session.getPacketBufferSize();
+ packetSendBuf = ByteBuffer.allocate(packetBufferSize);
+ packetRecvBuf = ByteBuffer.allocate(packetBufferSize);
+ }
+
+ public Executor getExecutor()
+ {
+ return executor;
+ }
+
+ public ByteBuffer getAppSendBuf()
+ {
+ return appSendBuf;
+ }
+
+ public void setAppSendBuf(ByteBuffer appSendBuf)
+ {
+ this.appSendBuf = appSendBuf;
+ }
+
+ public ByteBuffer getAppRecvBuf()
+ {
+ return appRecvBuf;
+ }
+
+ public void setAppRecvBuf(ByteBuffer appRecvBuf)
+ {
+ this.appRecvBuf = appRecvBuf;
+ }
+
+ public ByteBuffer getPacketSendBuf()
+ {
+ return packetSendBuf;
+ }
+
+ public void setPacketSendBuf(ByteBuffer packetSendBuf)
+ {
+ this.packetSendBuf = packetSendBuf;
+ }
+
+ public ByteBuffer getPacketRecvBuf()
+ {
+ return packetRecvBuf;
+ }
+
+ public void setPacketRecvBuf(ByteBuffer packetRecvBuf)
+ {
+ this.packetRecvBuf = packetRecvBuf;
+ }
+
+ public synchronized void checkInitialHandshake(SocketChannel socketChannel) throws Exception
+ {
+ if (!handshakeComplete)
+ {
+ try
+ {
+ int counter = 0;
+ while (!isHandshakeFinished() && counter <= SSLUtil.getHandShakeTimeOut())
+ {
+ performHandshake(socketChannel, needRehandShake);
+ counter = handshakeStatus == HandshakeStatus.NEED_UNWRAP ? counter++ : 0;
+ }
+
+ if (!isHandshakeFinished() && counter == SSLUtil.getHandShakeTimeOut())
+ {
+ throw new SSLException("SSL handshake timeout");
+ }
+ }
+ catch (Exception ex)
+ {
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("SSL handshake incomplete.", ex); //$NON-NLS-1$
+ }
+
+ try
+ {
+ // Clean the SSLEngine.
+ close();
+ }
+ catch (IOException ioex)
+ {
+ OM.LOG.warn(ioex);
+ }
+
+ throw ex;
+ }
+
+ handshakeComplete = true;
+ }
+ }
+
+ public int read(SocketChannel socketChannel) throws IOException
+ {
+ if (!handshakeComplete)
+ {
+ throw new SSLException("Handshake still not completed");
+ }
+
+ synchronized (readLock)
+ {
+ int readTextCount = appRecvBuf.position();
+
+ do
+ {
+ if (sslEngine.isInboundDone())
+ {
+ return readTextCount > 0 ? readTextCount : -1;
+ }
+
+ int count = handleRead(socketChannel);
+ if (count <= 0 && packetRecvBuf.position() == 0)
+ {
+ return count;
+ }
+
+ packetRecvBuf.flip();
+ engineResult = sslEngine.unwrap(packetRecvBuf, appRecvBuf);
+ packetRecvBuf.compact();
+
+ switch (engineResult.getStatus())
+ {
+ case BUFFER_UNDERFLOW:
+ continue;
+
+ case BUFFER_OVERFLOW:
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Buffer overflow on read method."); //$NON-NLS-1$
+ }
+
+ return 0;
+
+ case CLOSED:
+ throw new ClosedChannelException();
+
+ default:
+ // OK
+ }
+
+ readTextCount = appRecvBuf.position();
+ } while (engineResult.getStatus() != Status.OK);
+
+ if (sslEngine.isInboundDone())
+ {
+ return -1;
+ }
+
+ return readTextCount;
+ }
+ }
+
+ public int write(SocketChannel socketChannel) throws IOException
+ {
+ if (!handshakeComplete)
+ {
+ throw new SSLException("Handshake still not completed");
+ }
+
+ synchronized (writeLock)
+ {
+ int writeCount = 0;
+ int count = 0;
+ int appSendBufSize = appSendBuf.position();
+
+ do
+ {
+ appSendBuf.flip();
+ engineResult = sslEngine.wrap(appSendBuf, packetSendBuf);
+ appSendBuf.compact();
+ switch (engineResult.getStatus())
+ {
+ case BUFFER_UNDERFLOW:
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Buffer Underflow happen on write method"); //$NON-NLS-1$
+ }
+
+ return -1;
+
+ case BUFFER_OVERFLOW:
+ count = handleWrite(socketChannel);
+ writeCount += count;
+ continue;
+
+ case CLOSED:
+ throw new ClosedChannelException();
+
+ case OK:
+ int bytesComsumed = engineResult.bytesConsumed();
+ appSendBufSize = appSendBufSize - bytesComsumed;
+ count = handleWrite(socketChannel);
+ writeCount += count;
+ break;
+ }
+ } while (engineResult.getStatus() != Status.OK);
+
+ return writeCount;
+ }
+ }
+
+ /**
+ * Write the contents of {@link #packetSendBuf} to the given {@link SocketChannel}
+ *
+ * @return the number of bytes actually written
+ */
+ public int handleWrite(SocketChannel socketChannel) throws IOException
+ {
+ try
+ {
+ packetSendBuf.flip();
+ int count = socketChannel.write(packetSendBuf);
+ packetSendBuf.compact();
+
+ if (count == -1)
+ {
+ throw new ClosedChannelException();
+ }
+
+ return count;
+ }
+ catch (ClosedChannelException ex)
+ {
+ throw ex;
+ }
+ catch (IOException ex)
+ {
+ throw new ClosedChannelException();
+ }
+ }
+
+ /**
+ * Read the contents from the given {@link SocketChannel} to {@link #packetSendBuf}
+ *
+ * @return the number of bytes actually read
+ */
+ public int handleRead(SocketChannel socketChannel) throws IOException
+ {
+ try
+ {
+ int count = socketChannel.read(packetRecvBuf);
+ if (count == -1)
+ {
+ throw new ClosedChannelException();
+ }
+
+ return count;
+ }
+ catch (ClosedChannelException ex)
+ {
+ throw ex;
+ }
+ catch (IOException ex)
+ {
+ throw new ClosedChannelException();
+ }
+ }
+
+ public void close() throws IOException
+ {
+ if (sslEngine != null)
+ {
+ sslEngine.closeOutbound();
+ }
+ }
+
+ public void checkRehandShake(SocketChannel socket) throws Exception
+ {
+ handshakeStatus = engineResult.getHandshakeStatus();
+ needRehandShake = handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_TASK
+ || handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP
+ || handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP;
+
+ if (needRehandShake)
+ {
+ handshakeComplete = false;
+ }
+
+ checkInitialHandshake(socket);
+ return;
+ }
+
+ public boolean isHandshakeComplete()
+ {
+ return handshakeComplete;
+ }
+
+ private boolean isHandshakeFinished()
+ {
+ return handshakeStatus != null && handshakeStatus == SSLEngineResult.HandshakeStatus.FINISHED;
+ }
+
+ private boolean performHandshake(SocketChannel socketChannel, boolean rehandShake) throws IOException
+ {
+ int nBytes = 0;
+ if (!rehandShake)
+ {
+ handshakeStatus = sslEngine.getHandshakeStatus();
+ }
+
+ switch (handshakeStatus)
+ {
+ case NEED_WRAP:
+ appSendBuf.flip();
+ engineResult = sslEngine.wrap(appSendBuf, packetSendBuf);
+ handshakeStatus = engineResult.getHandshakeStatus();
+ appSendBuf.compact();
+
+ switch (engineResult.getStatus())
+ {
+ case BUFFER_OVERFLOW:
+ nBytes = handleWrite(socketChannel);
+ break;
+
+ case OK:
+ while (packetSendBuf.position() > 0)
+ {
+ nBytes = handleWrite(socketChannel);
+ if (nBytes == 0)
+ {
+ // Prevent spinning if the channel refused the write
+ break;
+ }
+ }
+
+ break;
+
+ default:
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Need Wrap Operation: cannot handle ssl result status [" + engineResult.getStatus() + "]"); //$NON-NLS-1$
+ }
+ }
+
+ return true;
+
+ case NEED_UNWRAP:
+ nBytes = handleRead(socketChannel);
+
+ packetRecvBuf.flip();
+ engineResult = sslEngine.unwrap(packetRecvBuf, appRecvBuf);
+ handshakeStatus = engineResult.getHandshakeStatus();
+ packetRecvBuf.compact();
+
+ if (engineResult.getStatus() == SSLEngineResult.Status.BUFFER_UNDERFLOW && sslEngine.isInboundDone())
+ {
+ return false;
+ }
+
+ return engineResult.getStatus() != SSLEngineResult.Status.BUFFER_OVERFLOW;
+
+ case NEED_TASK:
+ executeTasks();
+ return true;
+
+ case NOT_HANDSHAKING:
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Not handshaking status occurs."); //$NON-NLS-1$
+ }
+
+ throw new ClosedChannelException();
+
+ case FINISHED:
+ return false;
+ }
+
+ return true;
+ }
+
+ private void executeTasks()
+ {
+ Runnable task;
+ while ((task = sslEngine.getDelegatedTask()) != null)
+ {
+ executor.execute(task);
+
+ if (TRACER.isEnabled())
+ {
+ TRACER.trace("Scheduled task: " + task); //$NON-NLS-1$
+ }
+ }
+ }
+
+ /**
+ * A separate class for better monitor debugging.
+ *
+ * @author Eike Stepper
+ */
+ private static final class ReadLock
+ {
+ }
+
+ /**
+ * A separate class for better monitor debugging.
+ *
+ * @author Eike Stepper
+ */
+ private static final class WriteLock
+ {
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLProperties.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLProperties.java index a2d0a4ea82..1df8f125e2 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLProperties.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLProperties.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: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.util.WrappedException; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.om.OMPlatform; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Properties; - -/** - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLProperties -{ - public static final String KEY_PATH = "org.eclipse.net4j.tcp.ssl.key"; - - public static final String TRUST_PATH = "org.eclipse.net4j.tcp.ssl.trust"; - - public static final String PASS_PHRASE = "org.eclipse.net4j.tcp.ssl.passphrase"; - - public static final String HANDSHAKE_TIMEOUT = "org.eclipse.net4j.tcp.ssl.handshake.timeout"; - - public static final String HANDSHAKE_WAITTIME = "org.eclipse.net4j.tcp.ssl.handshake.waittime"; - - private Properties localProperties; - - public SSLProperties() - { - } - - public void load(String localConfigPath) throws IOException - { - // Loading SSL config from local property is optional. - localProperties = new Properties(); - - InputStream in = null; - - try - { - in = new URL(localConfigPath).openStream(); - localProperties.load(in); - } - catch (IOException ex) - { - throw ex; - } - catch (Exception ex) - { - throw WrappedException.wrap(ex, "SSL config cannot be loaded"); - } - finally - { - IOUtil.close(in); - } - } - - public String getKeyPath() - { - String keyPath = OMPlatform.INSTANCE.getProperty(KEY_PATH); - if (keyPath == null && localProperties != null) - { - keyPath = localProperties.getProperty(KEY_PATH); - } - - return keyPath; - } - - public String getTrustPath() - { - String trustPath = OMPlatform.INSTANCE.getProperty(TRUST_PATH); - if (trustPath == null && localProperties != null) - { - trustPath = localProperties.getProperty(TRUST_PATH); - } - - return trustPath; - } - - public String getPassPhrase() - { - String passPhrase = OMPlatform.INSTANCE.getProperty(PASS_PHRASE); - if (passPhrase == null && localProperties != null) - { - passPhrase = localProperties.getProperty(PASS_PHRASE); - } - - return passPhrase; - } - - public String getHandShakeTimeOut() - { - String hsTimeOut = OMPlatform.INSTANCE.getProperty(HANDSHAKE_TIMEOUT); - if (hsTimeOut == null && localProperties != null) - { - hsTimeOut = localProperties.getProperty(HANDSHAKE_TIMEOUT); - } - - return hsTimeOut; - } - - public String getHandShakeWaitTime() - { - String waitTime = OMPlatform.INSTANCE.getProperty(HANDSHAKE_WAITTIME); - if (waitTime == null && localProperties != null) - { - waitTime = localProperties.getProperty(HANDSHAKE_WAITTIME); - } - - return waitTime; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.util.WrappedException;
+import org.eclipse.net4j.util.io.IOUtil;
+import org.eclipse.net4j.util.om.OMPlatform;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Properties;
+
+/**
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLProperties
+{
+ public static final String KEY_PATH = "org.eclipse.net4j.tcp.ssl.key";
+
+ public static final String TRUST_PATH = "org.eclipse.net4j.tcp.ssl.trust";
+
+ public static final String PASS_PHRASE = "org.eclipse.net4j.tcp.ssl.passphrase";
+
+ public static final String HANDSHAKE_TIMEOUT = "org.eclipse.net4j.tcp.ssl.handshake.timeout";
+
+ public static final String HANDSHAKE_WAITTIME = "org.eclipse.net4j.tcp.ssl.handshake.waittime";
+
+ private Properties localProperties;
+
+ public SSLProperties()
+ {
+ }
+
+ public void load(String localConfigPath) throws IOException
+ {
+ // Loading SSL config from local property is optional.
+ localProperties = new Properties();
+
+ InputStream in = null;
+
+ try
+ {
+ in = new URL(localConfigPath).openStream();
+ localProperties.load(in);
+ }
+ catch (IOException ex)
+ {
+ throw ex;
+ }
+ catch (Exception ex)
+ {
+ throw WrappedException.wrap(ex, "SSL config cannot be loaded");
+ }
+ finally
+ {
+ IOUtil.close(in);
+ }
+ }
+
+ public String getKeyPath()
+ {
+ String keyPath = OMPlatform.INSTANCE.getProperty(KEY_PATH);
+ if (keyPath == null && localProperties != null)
+ {
+ keyPath = localProperties.getProperty(KEY_PATH);
+ }
+
+ return keyPath;
+ }
+
+ public String getTrustPath()
+ {
+ String trustPath = OMPlatform.INSTANCE.getProperty(TRUST_PATH);
+ if (trustPath == null && localProperties != null)
+ {
+ trustPath = localProperties.getProperty(TRUST_PATH);
+ }
+
+ return trustPath;
+ }
+
+ public String getPassPhrase()
+ {
+ String passPhrase = OMPlatform.INSTANCE.getProperty(PASS_PHRASE);
+ if (passPhrase == null && localProperties != null)
+ {
+ passPhrase = localProperties.getProperty(PASS_PHRASE);
+ }
+
+ return passPhrase;
+ }
+
+ public String getHandShakeTimeOut()
+ {
+ String hsTimeOut = OMPlatform.INSTANCE.getProperty(HANDSHAKE_TIMEOUT);
+ if (hsTimeOut == null && localProperties != null)
+ {
+ hsTimeOut = localProperties.getProperty(HANDSHAKE_TIMEOUT);
+ }
+
+ return hsTimeOut;
+ }
+
+ public String getHandShakeWaitTime()
+ {
+ String waitTime = OMPlatform.INSTANCE.getProperty(HANDSHAKE_WAITTIME);
+ if (waitTime == null && localProperties != null)
+ {
+ waitTime = localProperties.getProperty(HANDSHAKE_WAITTIME);
+ }
+
+ return waitTime;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLServerConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLServerConnector.java index 1a6f672930..94cb1b47d1 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLServerConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/internal/tcp/ssl/SSLServerConnector.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: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.internal.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ITCPSelector; - -import java.nio.channels.SocketChannel; -import java.text.MessageFormat; - -/** - * SSLServerConnector responses to be connector on server side and it handles about registration from the - * SSLClientConnector. - * - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLServerConnector extends SSLConnector -{ - private SSLAcceptor acceptor; - - public SSLServerConnector(SSLAcceptor acceptor) - { - this.acceptor = acceptor; - } - - public SSLAcceptor getAcceptor() - { - return acceptor; - } - - @Override - public Location getLocation() - { - return Location.SERVER; - } - - @Override - public String getHost() - { - try - { - return getSocketChannel().socket().getInetAddress().getHostAddress(); - } - catch (RuntimeException ex) - { - return null; - } - } - - @Override - public int getPort() - { - try - { - return getSocketChannel().socket().getPort(); - } - catch (RuntimeException ex) - { - return 0; - } - } - - @Override - public String toString() - { - if (getUserID() == null) - { - return MessageFormat.format("SSLServerConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$ - } - - return MessageFormat.format("SSLServerConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$ - } - - @Override - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel) - { - super.handleRegistration(selector, socketChannel); - - try - { - acceptor.addConnector(this); - } - catch (Exception ex) - { - OM.LOG.error(ex); - deactivateAsync(); - } - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.internal.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ITCPSelector;
+
+import java.nio.channels.SocketChannel;
+import java.text.MessageFormat;
+
+/**
+ * SSLServerConnector responses to be connector on server side and it handles about registration from the
+ * SSLClientConnector.
+ *
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLServerConnector extends SSLConnector
+{
+ private SSLAcceptor acceptor;
+
+ public SSLServerConnector(SSLAcceptor acceptor)
+ {
+ this.acceptor = acceptor;
+ }
+
+ public SSLAcceptor getAcceptor()
+ {
+ return acceptor;
+ }
+
+ @Override
+ public Location getLocation()
+ {
+ return Location.SERVER;
+ }
+
+ @Override
+ public String getHost()
+ {
+ try
+ {
+ return getSocketChannel().socket().getInetAddress().getHostAddress();
+ }
+ catch (RuntimeException ex)
+ {
+ return null;
+ }
+ }
+
+ @Override
+ public int getPort()
+ {
+ try
+ {
+ return getSocketChannel().socket().getPort();
+ }
+ catch (RuntimeException ex)
+ {
+ return 0;
+ }
+ }
+
+ @Override
+ public String toString()
+ {
+ if (getUserID() == null)
+ {
+ return MessageFormat.format("SSLServerConnector[{0}:{1}]", getHost(), getPort()); //$NON-NLS-1$
+ }
+
+ return MessageFormat.format("SSLServerConnector[{2}@{0}:{1}]", getHost(), getPort(), getUserID()); //$NON-NLS-1$
+ }
+
+ @Override
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel)
+ {
+ super.handleRegistration(selector, socketChannel);
+
+ try
+ {
+ acceptor.addConnector(this);
+ }
+ catch (Exception ex)
+ {
+ OM.LOG.error(ex);
+ deactivateAsync();
+ }
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPAcceptor.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPAcceptor.java index 37c670d715..f0e832801a 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPAcceptor.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPAcceptor.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.tcp; - -import org.eclipse.net4j.acceptor.IAcceptor; -import org.eclipse.net4j.internal.tcp.bundle.OM; -import org.eclipse.net4j.tcp.ssl.SSLUtil; - -/** - * An {@link IAcceptor acceptor} that implements non-blocking multiplexed TCP transport, optionally with {@link SSLUtil - * SSL}. - * - * @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 ITCPAcceptor extends IAcceptor -{ - public static final String DEFAULT_ADDRESS = "0.0.0.0"; //$NON-NLS-1$ - - /** - * The value of the <i>org.eclipse.net4j.tcp.port</i> bundle/system property if defined, the value <i>2036</i> - * otherwise. - */ - public static final int DEFAULT_PORT = OM.getDefaultPort(); - - /** - * @since 4.0 - */ - public ITCPSelector getSelector(); - - public String getAddress(); - - public int getPort(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.tcp;
+
+import org.eclipse.net4j.acceptor.IAcceptor;
+import org.eclipse.net4j.internal.tcp.bundle.OM;
+import org.eclipse.net4j.tcp.ssl.SSLUtil;
+
+/**
+ * An {@link IAcceptor acceptor} that implements non-blocking multiplexed TCP transport, optionally with {@link SSLUtil
+ * SSL}.
+ *
+ * @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 ITCPAcceptor extends IAcceptor
+{
+ public static final String DEFAULT_ADDRESS = "0.0.0.0"; //$NON-NLS-1$
+
+ /**
+ * The value of the <i>org.eclipse.net4j.tcp.port</i> bundle/system property if defined, the value <i>2036</i>
+ * otherwise.
+ */
+ public static final int DEFAULT_PORT = OM.getDefaultPort();
+
+ /**
+ * @since 4.0
+ */
+ public ITCPSelector getSelector();
+
+ public String getAddress();
+
+ public int getPort();
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPActiveSelectorListener.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPActiveSelectorListener.java index f71ddc28fe..a6f34e595b 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPActiveSelectorListener.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPActiveSelectorListener.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.tcp; - -import org.eclipse.net4j.connector.IConnector; - -import java.nio.channels.SocketChannel; - -/** - * Call-back that handles the possible calls from a {@link ITCPSelector selector} to an active consumer, usually a - * {@link IConnector connector}. - * - * @author Eike Stepper - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ITCPActiveSelectorListener -{ - public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel); - - public void handleConnect(ITCPSelector selector, SocketChannel socketChannel); - - public void handleRead(ITCPSelector selector, SocketChannel socketChannel); - - public void handleWrite(ITCPSelector selector, SocketChannel socketChannel); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.tcp;
+
+import org.eclipse.net4j.connector.IConnector;
+
+import java.nio.channels.SocketChannel;
+
+/**
+ * Call-back that handles the possible calls from a {@link ITCPSelector selector} to an active consumer, usually a
+ * {@link IConnector connector}.
+ *
+ * @author Eike Stepper
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public interface ITCPActiveSelectorListener
+{
+ public void handleRegistration(ITCPSelector selector, SocketChannel socketChannel);
+
+ public void handleConnect(ITCPSelector selector, SocketChannel socketChannel);
+
+ public void handleRead(ITCPSelector selector, SocketChannel socketChannel);
+
+ public void handleWrite(ITCPSelector selector, SocketChannel socketChannel);
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPConnector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPConnector.java index b70765e0d6..ae10686666 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPConnector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPConnector.java @@ -1,36 +1,36 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Eike Stepper - initial API and implementation - */ -package org.eclipse.net4j.tcp; - -import org.eclipse.net4j.connector.IConnector; -import org.eclipse.net4j.tcp.ssl.SSLUtil; - -/** - * A {@link IConnector connector} that implements non-blocking multiplexed TCP transport, optionally with - * {@link SSLUtil SSL}. - * - * @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 ITCPConnector extends IConnector -{ - public static final int DEFAULT_PORT = ITCPAcceptor.DEFAULT_PORT; - - /** - * @since 4.0 - */ - public ITCPSelector getSelector(); - - public String getHost(); - - public int getPort(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.tcp;
+
+import org.eclipse.net4j.connector.IConnector;
+import org.eclipse.net4j.tcp.ssl.SSLUtil;
+
+/**
+ * A {@link IConnector connector} that implements non-blocking multiplexed TCP transport, optionally with
+ * {@link SSLUtil SSL}.
+ *
+ * @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 ITCPConnector extends IConnector
+{
+ public static final int DEFAULT_PORT = ITCPAcceptor.DEFAULT_PORT;
+
+ /**
+ * @since 4.0
+ */
+ public ITCPSelector getSelector();
+
+ public String getHost();
+
+ public int getPort();
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPNegotiationContext.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPNegotiationContext.java index 074b556bb5..7f42928722 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPNegotiationContext.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPNegotiationContext.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.tcp; - -import org.eclipse.net4j.util.security.INegotiationContext; - -/** - * A {@link INegotiationContext negotiation context} that is used in TCP transport. - * - * @author Eike Stepper - * @since 2.0 - * @noextend This interface is not intended to be extended by clients. - * @noimplement This interface is not intended to be implemented by clients. - */ -public interface ITCPNegotiationContext extends INegotiationContext -{ - public ITCPConnector getConnector(); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.tcp;
+
+import org.eclipse.net4j.util.security.INegotiationContext;
+
+/**
+ * A {@link INegotiationContext negotiation context} that is used in TCP transport.
+ *
+ * @author Eike Stepper
+ * @since 2.0
+ * @noextend This interface is not intended to be extended by clients.
+ * @noimplement This interface is not intended to be implemented by clients.
+ */
+public interface ITCPNegotiationContext extends INegotiationContext
+{
+ public ITCPConnector getConnector();
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPPassiveSelectorListener.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPPassiveSelectorListener.java index ecbdfda344..114916e2fa 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPPassiveSelectorListener.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPPassiveSelectorListener.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.tcp; - -import org.eclipse.net4j.acceptor.IAcceptor; - -import java.nio.channels.ServerSocketChannel; - -/** - * Call-back that handles the possible calls from a {@link ITCPSelector selector} to a passive consumer, usually an - * {@link IAcceptor acceptor}. - * - * @author Eike Stepper - * @noimplement This interface is not intended to be implemented by clients. - * @noextend This interface is not intended to be extended by clients. - */ -public interface ITCPPassiveSelectorListener -{ - public void handleRegistration(ITCPSelector selector, ServerSocketChannel serverSocketChannel); - - public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.tcp;
+
+import org.eclipse.net4j.acceptor.IAcceptor;
+
+import java.nio.channels.ServerSocketChannel;
+
+/**
+ * Call-back that handles the possible calls from a {@link ITCPSelector selector} to a passive consumer, usually an
+ * {@link IAcceptor acceptor}.
+ *
+ * @author Eike Stepper
+ * @noimplement This interface is not intended to be implemented by clients.
+ * @noextend This interface is not intended to be extended by clients.
+ */
+public interface ITCPPassiveSelectorListener
+{
+ public void handleRegistration(ITCPSelector selector, ServerSocketChannel serverSocketChannel);
+
+ public void handleAccept(ITCPSelector selector, ServerSocketChannel serverSocketChannel);
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPSelector.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPSelector.java index 662ceeecf8..b55ebcfbfe 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPSelector.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ITCPSelector.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.tcp; - -import org.eclipse.net4j.acceptor.IAcceptor; -import org.eclipse.net4j.connector.IConnector; - -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; - -/** - * Encapsulates a Java {@link Selector socket selector} and orchestrates a number of {@link ITCPPassiveSelectorListener - * active} and {@link ITCPPassiveSelectorListener passive} consumers, usually {@link IConnector connectors} and - * {@link IAcceptor acceptors} that compete for the socket selector's I/O time. - * - * @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 ITCPSelector -{ - public Selector getSocketSelector(); - - public void orderRegistration(ServerSocketChannel channel, ITCPPassiveSelectorListener listener); - - public void orderRegistration(SocketChannel channel, boolean client, ITCPActiveSelectorListener listener); - - public void orderConnectInterest(SelectionKey selectionKey, boolean client, boolean on); - - public void orderReadInterest(SelectionKey selectionKey, boolean client, boolean on); - - public void orderWriteInterest(SelectionKey selectionKey, boolean client, boolean on); -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Eike Stepper - initial API and implementation
+ */
+package org.eclipse.net4j.tcp;
+
+import org.eclipse.net4j.acceptor.IAcceptor;
+import org.eclipse.net4j.connector.IConnector;
+
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+
+/**
+ * Encapsulates a Java {@link Selector socket selector} and orchestrates a number of {@link ITCPPassiveSelectorListener
+ * active} and {@link ITCPPassiveSelectorListener passive} consumers, usually {@link IConnector connectors} and
+ * {@link IAcceptor acceptors} that compete for the socket selector's I/O time.
+ *
+ * @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 ITCPSelector
+{
+ public Selector getSocketSelector();
+
+ public void orderRegistration(ServerSocketChannel channel, ITCPPassiveSelectorListener listener);
+
+ public void orderRegistration(SocketChannel channel, boolean client, ITCPActiveSelectorListener listener);
+
+ public void orderConnectInterest(SelectionKey selectionKey, boolean client, boolean on);
+
+ public void orderReadInterest(SelectionKey selectionKey, boolean client, boolean on);
+
+ public void orderWriteInterest(SelectionKey selectionKey, boolean client, boolean on);
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/TCPUtil.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/TCPUtil.java index 74553e127c..ea99a9e791 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/TCPUtil.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/TCPUtil.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.tcp; - -import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory; -import org.eclipse.net4j.internal.tcp.TCPConnectorFactory; -import org.eclipse.net4j.internal.tcp.TCPSelectorFactory; -import org.eclipse.net4j.internal.tcp.TCPSelectorInjector; -import org.eclipse.net4j.util.container.IManagedContainer; - -/** - * A utility class with static convenience methods. - * - * @author Eike Stepper - */ -public final class TCPUtil -{ - private TCPUtil() - { - } - - public static void prepareContainer(IManagedContainer container) - { - container.registerFactory(new TCPSelectorFactory()); - container.registerFactory(new TCPAcceptorFactory()); - container.registerFactory(new TCPConnectorFactory()); - container.addPostProcessor(new TCPSelectorInjector()); - } - - public static ITCPAcceptor getAcceptor(IManagedContainer container, String description) - { - return (ITCPAcceptor)container.getElement(TCPAcceptorFactory.PRODUCT_GROUP, TCPAcceptorFactory.TYPE, description); - } - - public static ITCPConnector getConnector(IManagedContainer container, String description) - { - return (ITCPConnector)container - .getElement(TCPConnectorFactory.PRODUCT_GROUP, TCPConnectorFactory.TYPE, 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.tcp;
+
+import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory;
+import org.eclipse.net4j.internal.tcp.TCPConnectorFactory;
+import org.eclipse.net4j.internal.tcp.TCPSelectorFactory;
+import org.eclipse.net4j.internal.tcp.TCPSelectorInjector;
+import org.eclipse.net4j.util.container.IManagedContainer;
+
+/**
+ * A utility class with static convenience methods.
+ *
+ * @author Eike Stepper
+ */
+public final class TCPUtil
+{
+ private TCPUtil()
+ {
+ }
+
+ public static void prepareContainer(IManagedContainer container)
+ {
+ container.registerFactory(new TCPSelectorFactory());
+ container.registerFactory(new TCPAcceptorFactory());
+ container.registerFactory(new TCPConnectorFactory());
+ container.addPostProcessor(new TCPSelectorInjector());
+ }
+
+ public static ITCPAcceptor getAcceptor(IManagedContainer container, String description)
+ {
+ return (ITCPAcceptor)container.getElement(TCPAcceptorFactory.PRODUCT_GROUP, TCPAcceptorFactory.TYPE, description);
+ }
+
+ public static ITCPConnector getConnector(IManagedContainer container, String description)
+ {
+ return (ITCPConnector)container
+ .getElement(TCPConnectorFactory.PRODUCT_GROUP, TCPConnectorFactory.TYPE, description);
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/package-info.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/package-info.java index e24bb3fd99..f7fff8edd3 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/package-info.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/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.tcp/src/org/eclipse/net4j/tcp/ssl/SSLUtil.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/SSLUtil.java index f5afd53aba..21223445f1 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/SSLUtil.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/SSLUtil.java @@ -1,254 +1,254 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation - * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation - */ -package org.eclipse.net4j.tcp.ssl; - -import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory; -import org.eclipse.net4j.internal.tcp.TCPConnectorFactory; -import org.eclipse.net4j.internal.tcp.ssl.SSLAcceptorFactory; -import org.eclipse.net4j.internal.tcp.ssl.SSLConnectorFactory; -import org.eclipse.net4j.internal.tcp.ssl.SSLProperties; -import org.eclipse.net4j.tcp.ITCPAcceptor; -import org.eclipse.net4j.tcp.ITCPConnector; -import org.eclipse.net4j.tcp.TCPUtil; -import org.eclipse.net4j.util.container.IManagedContainer; -import org.eclipse.net4j.util.io.IOUtil; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLEngine; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; - -/** - * A utility class with various static factory and convenience methods for SSL transport. - * - * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - * @author Caspar De Groot (No Magic Asia Ltd.) - * @since 4.0 - */ -public class SSLUtil -{ - /** - * The variable for SSL Engine - */ - private static final String PROTOCOL = "TLS"; - - private static String configFile; - - private static String keyPathVar; - - private static String trustPathVar; - - private static String passPhraseVar; - - /** - * Default value of handshake timeout is 12 times. - */ - private static int handShakeTimeOutVar = 12; - - /** - * Default value of handshake wait time is 60 milliseconds. - */ - private static int handShakeWaitTimeVar = 60; - - public static synchronized void setDefaultSSLConfiguration(String keyPath, String trustPath, String passPhrase) - { - keyPathVar = keyPath; - trustPathVar = trustPath; - passPhraseVar = passPhrase; - } - - public static synchronized void setDefaultSSLConfiguration(String keyPath, String trustPath, String passPhrase, - int handShakeTimeOut, int handShakeWaitTime) - { - setDefaultSSLConfiguration(keyPath, trustPath, passPhrase); - - handShakeTimeOutVar = handShakeTimeOut; - handShakeWaitTimeVar = handShakeWaitTime; - } - - public static synchronized void setSSLConfigurationFile(String file) - { - configFile = file; - } - - public static synchronized void prepareContainer(IManagedContainer container) - { - TCPUtil.prepareContainer(container); - - // Prepare SSL - container.registerFactory(new SSLAcceptorFactory()); - container.registerFactory(new SSLConnectorFactory()); - } - - public static synchronized ITCPAcceptor getAcceptor(IManagedContainer container, String description) - { - return (ITCPAcceptor)container.getElement(TCPAcceptorFactory.PRODUCT_GROUP, SSLAcceptorFactory.TYPE, description); - } - - public static synchronized ITCPConnector getConnector(IManagedContainer container, String description) - { - return (ITCPConnector)container - .getElement(TCPConnectorFactory.PRODUCT_GROUP, SSLConnectorFactory.TYPE, description); - } - - public static synchronized SSLEngine createSSLEngine(boolean client, String host, int port) - throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, - KeyManagementException - { - // Get values from the system properties. - SSLProperties sslProperties = new SSLProperties(); - String keyPath = sslProperties.getKeyPath(); - String trustPath = sslProperties.getTrustPath(); - String passPhrase = sslProperties.getPassPhrase(); - - if ((keyPath == null || trustPath == null || passPhrase == null) && configFile != null) - { - sslProperties.load(configFile); - } - - // In case, the system properties does not have the key path property. It will load from local config file. - if (keyPath == null) - { - keyPath = sslProperties.getKeyPath(); - if (keyPath == null) - { - keyPath = keyPathVar; - } - } - - // In case, the system properties does not have the trust path property. It will load from local config file. - if (trustPath == null) - { - trustPath = sslProperties.getTrustPath(); - if (trustPath == null) - { - trustPath = trustPathVar; - } - } - - // In case, the system properties does not have the passphrase property. It will load from local config file. - if (passPhrase == null) - { - passPhrase = sslProperties.getPassPhrase(); - if (passPhrase == null) - { - passPhrase = passPhraseVar; - } - } - - // Handle assign the value of handshake timeout and handshake timewait from local properties or system properties by - // giving the value form system properties is high priority. - String value = sslProperties.getHandShakeTimeOut(); - if (value != null) - { - handShakeTimeOutVar = Integer.parseInt(value); - } - - value = sslProperties.getHandShakeWaitTime(); - if (value != null) - { - handShakeWaitTimeVar = Integer.parseInt(value); - } - - if (keyPath == null && !client || trustPath == null && client || passPhrase == null) - { - if (client) - { - throw new KeyStoreException("Trust Store[" + (trustPath != null) + "] or Pass Phrase[" + (passPhrase != null) - + "] is not provided. [false] means it does not exist."); - } - - throw new KeyStoreException("Key Store[" + (keyPath != null) + "] or Pass Phrase[" + (passPhrase != null) - + "] is not provided. [false] means it does not exist."); - } - - char[] pass = passPhrase.toCharArray(); - - KeyManager[] keyManagers = null; - TrustManager[] trustManagers = null; - - if (client) - { - // Initial key material(private key) for the client. - KeyStore ksTrust = KeyStore.getInstance(KeyStore.getDefaultType()); - - InputStream in = null; - - try - { - in = new URL(trustPath).openStream(); - ksTrust.load(in, pass); - } - finally - { - IOUtil.close(in); - } - - // Initial the trust manager factory - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ksTrust); - - trustManagers = tmf.getTrustManagers(); - } - else - { - // Initial key material (private key) for the server. - KeyStore ksKeys = KeyStore.getInstance(KeyStore.getDefaultType()); - InputStream in = null; - - try - { - in = new URL(keyPath).openStream(); - ksKeys.load(in, pass); - } - finally - { - IOUtil.close(in); - } - - // Initial the key manager factory. - KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - kmf.init(ksKeys, pass); - - keyManagers = kmf.getKeyManagers(); - } - - SSLContext sslContext = SSLContext.getInstance(PROTOCOL); - sslContext.init(keyManagers, trustManagers, null); - - SSLEngine sslEngine = sslContext.createSSLEngine(host, port); - sslEngine.setUseClientMode(client); - return sslEngine; - } - - public static synchronized int getHandShakeTimeOut() - { - return handShakeTimeOutVar; - } - - public static synchronized int getHandShakeWaitTime() - { - return handShakeWaitTimeVar; - } -} +/*
+ * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Teerawat Chaiyakijpichet (No Magic Asia Ltd.) - initial API and implementation
+ * Caspar De Groot (No Magic Asia Ltd.) - initial API and implementation
+ */
+package org.eclipse.net4j.tcp.ssl;
+
+import org.eclipse.net4j.internal.tcp.TCPAcceptorFactory;
+import org.eclipse.net4j.internal.tcp.TCPConnectorFactory;
+import org.eclipse.net4j.internal.tcp.ssl.SSLAcceptorFactory;
+import org.eclipse.net4j.internal.tcp.ssl.SSLConnectorFactory;
+import org.eclipse.net4j.internal.tcp.ssl.SSLProperties;
+import org.eclipse.net4j.tcp.ITCPAcceptor;
+import org.eclipse.net4j.tcp.ITCPConnector;
+import org.eclipse.net4j.tcp.TCPUtil;
+import org.eclipse.net4j.util.container.IManagedContainer;
+import org.eclipse.net4j.util.io.IOUtil;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+
+/**
+ * A utility class with various static factory and convenience methods for SSL transport.
+ *
+ * @author Teerawat Chaiyakijpichet (No Magic Asia Ltd.)
+ * @author Caspar De Groot (No Magic Asia Ltd.)
+ * @since 4.0
+ */
+public class SSLUtil
+{
+ /**
+ * The variable for SSL Engine
+ */
+ private static final String PROTOCOL = "TLS";
+
+ private static String configFile;
+
+ private static String keyPathVar;
+
+ private static String trustPathVar;
+
+ private static String passPhraseVar;
+
+ /**
+ * Default value of handshake timeout is 12 times.
+ */
+ private static int handShakeTimeOutVar = 12;
+
+ /**
+ * Default value of handshake wait time is 60 milliseconds.
+ */
+ private static int handShakeWaitTimeVar = 60;
+
+ public static synchronized void setDefaultSSLConfiguration(String keyPath, String trustPath, String passPhrase)
+ {
+ keyPathVar = keyPath;
+ trustPathVar = trustPath;
+ passPhraseVar = passPhrase;
+ }
+
+ public static synchronized void setDefaultSSLConfiguration(String keyPath, String trustPath, String passPhrase,
+ int handShakeTimeOut, int handShakeWaitTime)
+ {
+ setDefaultSSLConfiguration(keyPath, trustPath, passPhrase);
+
+ handShakeTimeOutVar = handShakeTimeOut;
+ handShakeWaitTimeVar = handShakeWaitTime;
+ }
+
+ public static synchronized void setSSLConfigurationFile(String file)
+ {
+ configFile = file;
+ }
+
+ public static synchronized void prepareContainer(IManagedContainer container)
+ {
+ TCPUtil.prepareContainer(container);
+
+ // Prepare SSL
+ container.registerFactory(new SSLAcceptorFactory());
+ container.registerFactory(new SSLConnectorFactory());
+ }
+
+ public static synchronized ITCPAcceptor getAcceptor(IManagedContainer container, String description)
+ {
+ return (ITCPAcceptor)container.getElement(TCPAcceptorFactory.PRODUCT_GROUP, SSLAcceptorFactory.TYPE, description);
+ }
+
+ public static synchronized ITCPConnector getConnector(IManagedContainer container, String description)
+ {
+ return (ITCPConnector)container
+ .getElement(TCPConnectorFactory.PRODUCT_GROUP, SSLConnectorFactory.TYPE, description);
+ }
+
+ public static synchronized SSLEngine createSSLEngine(boolean client, String host, int port)
+ throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException,
+ KeyManagementException
+ {
+ // Get values from the system properties.
+ SSLProperties sslProperties = new SSLProperties();
+ String keyPath = sslProperties.getKeyPath();
+ String trustPath = sslProperties.getTrustPath();
+ String passPhrase = sslProperties.getPassPhrase();
+
+ if ((keyPath == null || trustPath == null || passPhrase == null) && configFile != null)
+ {
+ sslProperties.load(configFile);
+ }
+
+ // In case, the system properties does not have the key path property. It will load from local config file.
+ if (keyPath == null)
+ {
+ keyPath = sslProperties.getKeyPath();
+ if (keyPath == null)
+ {
+ keyPath = keyPathVar;
+ }
+ }
+
+ // In case, the system properties does not have the trust path property. It will load from local config file.
+ if (trustPath == null)
+ {
+ trustPath = sslProperties.getTrustPath();
+ if (trustPath == null)
+ {
+ trustPath = trustPathVar;
+ }
+ }
+
+ // In case, the system properties does not have the passphrase property. It will load from local config file.
+ if (passPhrase == null)
+ {
+ passPhrase = sslProperties.getPassPhrase();
+ if (passPhrase == null)
+ {
+ passPhrase = passPhraseVar;
+ }
+ }
+
+ // Handle assign the value of handshake timeout and handshake timewait from local properties or system properties by
+ // giving the value form system properties is high priority.
+ String value = sslProperties.getHandShakeTimeOut();
+ if (value != null)
+ {
+ handShakeTimeOutVar = Integer.parseInt(value);
+ }
+
+ value = sslProperties.getHandShakeWaitTime();
+ if (value != null)
+ {
+ handShakeWaitTimeVar = Integer.parseInt(value);
+ }
+
+ if (keyPath == null && !client || trustPath == null && client || passPhrase == null)
+ {
+ if (client)
+ {
+ throw new KeyStoreException("Trust Store[" + (trustPath != null) + "] or Pass Phrase[" + (passPhrase != null)
+ + "] is not provided. [false] means it does not exist.");
+ }
+
+ throw new KeyStoreException("Key Store[" + (keyPath != null) + "] or Pass Phrase[" + (passPhrase != null)
+ + "] is not provided. [false] means it does not exist.");
+ }
+
+ char[] pass = passPhrase.toCharArray();
+
+ KeyManager[] keyManagers = null;
+ TrustManager[] trustManagers = null;
+
+ if (client)
+ {
+ // Initial key material(private key) for the client.
+ KeyStore ksTrust = KeyStore.getInstance(KeyStore.getDefaultType());
+
+ InputStream in = null;
+
+ try
+ {
+ in = new URL(trustPath).openStream();
+ ksTrust.load(in, pass);
+ }
+ finally
+ {
+ IOUtil.close(in);
+ }
+
+ // Initial the trust manager factory
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ tmf.init(ksTrust);
+
+ trustManagers = tmf.getTrustManagers();
+ }
+ else
+ {
+ // Initial key material (private key) for the server.
+ KeyStore ksKeys = KeyStore.getInstance(KeyStore.getDefaultType());
+ InputStream in = null;
+
+ try
+ {
+ in = new URL(keyPath).openStream();
+ ksKeys.load(in, pass);
+ }
+ finally
+ {
+ IOUtil.close(in);
+ }
+
+ // Initial the key manager factory.
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmf.init(ksKeys, pass);
+
+ keyManagers = kmf.getKeyManagers();
+ }
+
+ SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
+ sslContext.init(keyManagers, trustManagers, null);
+
+ SSLEngine sslEngine = sslContext.createSSLEngine(host, port);
+ sslEngine.setUseClientMode(client);
+ return sslEngine;
+ }
+
+ public static synchronized int getHandShakeTimeOut()
+ {
+ return handShakeTimeOutVar;
+ }
+
+ public static synchronized int getHandShakeWaitTime()
+ {
+ return handShakeWaitTimeVar;
+ }
+}
diff --git a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/package-info.java b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/package-info.java index 109303f351..8ad10bab16 100644 --- a/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/package-info.java +++ b/plugins/org.eclipse.net4j.tcp/src/org/eclipse/net4j/tcp/ssl/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
|