--- /dev/null
+eclipse.preferences.version=1
+org.eclipse.jdt.core.formatter.align_type_members_on_columns=false
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_assignment=0
+org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16
+org.eclipse.jdt.core.formatter.alignment_for_compact_if=16
+org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80
+org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0
+org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16
+org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0
+org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80
+org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=16
+org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16
+org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16
+org.eclipse.jdt.core.formatter.blank_lines_after_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_after_package=1
+org.eclipse.jdt.core.formatter.blank_lines_before_field=0
+org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0
+org.eclipse.jdt.core.formatter.blank_lines_before_imports=1
+org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1
+org.eclipse.jdt.core.formatter.blank_lines_before_method=1
+org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1
+org.eclipse.jdt.core.formatter.blank_lines_before_package=0
+org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1
+org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1
+org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line
+org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false
+org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false
+org.eclipse.jdt.core.formatter.comment.format_block_comments=true
+org.eclipse.jdt.core.formatter.comment.format_header=false
+org.eclipse.jdt.core.formatter.comment.format_html=true
+org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true
+org.eclipse.jdt.core.formatter.comment.format_line_comments=true
+org.eclipse.jdt.core.formatter.comment.format_source_code=true
+org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true
+org.eclipse.jdt.core.formatter.comment.indent_root_tags=true
+org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert
+org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert
+org.eclipse.jdt.core.formatter.comment.line_length=80
+org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true
+org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true
+org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false
+org.eclipse.jdt.core.formatter.compact_else_if=true
+org.eclipse.jdt.core.formatter.continuation_indentation=2
+org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2
+org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off
+org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on
+org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false
+org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true
+org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true
+org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_empty_lines=false
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true
+org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true
+org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false
+org.eclipse.jdt.core.formatter.indentation.size=4
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert
+org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert
+org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert
+org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert
+org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert
+org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert
+org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert
+org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert
+org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert
+org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert
+org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert
+org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert
+org.eclipse.jdt.core.formatter.join_lines_in_comments=true
+org.eclipse.jdt.core.formatter.join_wrapped_lines=true
+org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false
+org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false
+org.eclipse.jdt.core.formatter.lineSplit=80
+org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false
+org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false
+org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0
+org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1
+org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true
+org.eclipse.jdt.core.formatter.tabulation.char=space
+org.eclipse.jdt.core.formatter.tabulation.size=4
+org.eclipse.jdt.core.formatter.use_on_off_tags=false
+org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=true
+org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true
+org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true
+org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true
--- /dev/null
+eclipse.preferences.version=1
+formatter_profile=_eclipse [spaces-only]
+formatter_settings_version=12
import android.preference.PreferenceManager;\r
\r
public class AccountUtils {\r
- public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php";\r
- public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";\r
- public static final String WEBDAV_PATH_4_0 = "/remote/webdav.php";\r
- public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";\r
- public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";\r
- public static final String STATUS_PATH = "/status.php";\r
+ public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php";\r
+ public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";\r
+ public static final String WEBDAV_PATH_4_0 = "/remote/webdav.php";\r
+ public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";\r
+ public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";\r
+ public static final String STATUS_PATH = "/status.php";\r
\r
- /**\r
- * Can be used to get the currently selected ownCloud account in the preferences\r
- * \r
- * @param context The current appContext\r
- * @return The current account or first available, if none is available, then null.\r
- */\r
- public static Account getCurrentOwnCloudAccount(Context context) {\r
- Account[] ocAccounts = AccountManager.get(context).getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
- Account defaultAccount = null;\r
- \r
- SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(context);\r
- String accountName = appPreferences.getString("select_oc_account", null);\r
- \r
- if(accountName != null){\r
- for(Account account : ocAccounts){\r
- if(account.name.equals(accountName)){\r
- defaultAccount = account;\r
- break;\r
- }\r
- }\r
- } else if (ocAccounts.length != 0) {\r
- // we at least need to take first account as fallback\r
- defaultAccount = ocAccounts[0];\r
- }\r
- \r
- return defaultAccount;\r
- }\r
- \r
- public static void setCurrentOwnCloudAccount(Context context, String name) {\r
- SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();\r
- appPrefs.putString("select_oc_account", name);\r
- appPrefs.commit();\r
- }\r
- \r
- /**\r
- * \r
- * @param version version of owncloud\r
- * @return webdav path for given OC version, null if OC version unknown\r
- */\r
- public static String getWebdavPath(OwnCloudVersion version) {\r
- if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)\r
- return WEBDAV_PATH_4_0;\r
- if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0 ||\r
- version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)\r
- return WEBDAV_PATH_2_0;\r
- if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)\r
- return WEBDAV_PATH_1_2;\r
- return null;\r
- }\r
+ /**\r
+ * Can be used to get the currently selected ownCloud account in the\r
+ * preferences\r
+ * \r
+ * @param context\r
+ * The current appContext\r
+ * @return The current account or first available, if none is available,\r
+ * then null.\r
+ */\r
+ public static Account getCurrentOwnCloudAccount(Context context) {\r
+ Account[] ocAccounts = AccountManager.get(context).getAccountsByType(\r
+ AccountAuthenticator.ACCOUNT_TYPE);\r
+ Account defaultAccount = null;\r
+\r
+ SharedPreferences appPreferences = PreferenceManager\r
+ .getDefaultSharedPreferences(context);\r
+ String accountName = appPreferences\r
+ .getString("select_oc_account", null);\r
+\r
+ if (accountName != null) {\r
+ for (Account account : ocAccounts) {\r
+ if (account.name.equals(accountName)) {\r
+ defaultAccount = account;\r
+ break;\r
+ }\r
+ }\r
+ } else if (ocAccounts.length != 0) {\r
+ // we at least need to take first account as fallback\r
+ defaultAccount = ocAccounts[0];\r
+ }\r
+\r
+ return defaultAccount;\r
+ }\r
+\r
+ public static void setCurrentOwnCloudAccount(Context context, String name) {\r
+ SharedPreferences.Editor appPrefs = PreferenceManager\r
+ .getDefaultSharedPreferences(context).edit();\r
+ appPrefs.putString("select_oc_account", name);\r
+ appPrefs.commit();\r
+ }\r
+\r
+ /**\r
+ * \r
+ * @param version\r
+ * version of owncloud\r
+ * @return webdav path for given OC version, null if OC version unknown\r
+ */\r
+ public static String getWebdavPath(OwnCloudVersion version) {\r
+ if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)\r
+ return WEBDAV_PATH_4_0;\r
+ if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0\r
+ || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)\r
+ return WEBDAV_PATH_2_0;\r
+ if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)\r
+ return WEBDAV_PATH_1_2;\r
+ return null;\r
+ }\r
\r
}\r
\r
/**\r
* A helper class for some string operations.\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class DisplayUtils {\r
- public static String bitsToHumanReadable(long bitsLen) {\r
- double result = bitsLen;\r
- int attachedsuff = 0;\r
- while (result > 1024 && attachedsuff < suffixes.length) {\r
- result /= 1024.;\r
- attachedsuff++;\r
+ public static String bitsToHumanReadable(long bitsLen) {\r
+ double result = bitsLen;\r
+ int attachedsuff = 0;\r
+ while (result > 1024 && attachedsuff < suffixes.length) {\r
+ result /= 1024.;\r
+ attachedsuff++;\r
+ }\r
+ result = ((int) (result * 100)) / 100.;\r
+ return result + suffixes[attachedsuff];\r
+ }\r
+\r
+ public static String HtmlDecode(String s) {\r
+ String ret = "";\r
+ for (int i = 0; i < s.length(); ++i) {\r
+ if (s.charAt(i) == '%') {\r
+ ret += (char) Integer.parseInt(s.substring(i + 1, i + 3), 16);\r
+ i += 2;\r
+ } else {\r
+ ret += s.charAt(i);\r
+ }\r
+ }\r
+ return ret;\r
}\r
- result = ((int)(result * 100))/100.;\r
- return result+suffixes[attachedsuff];\r
- }\r
- \r
- public static String HtmlDecode(String s) {\r
- String ret = "";\r
- for (int i = 0; i < s.length(); ++i) {\r
- if (s.charAt(i) == '%') {\r
- ret += (char)Integer.parseInt(s.substring(i+1, i+3), 16);\r
- i+=2;\r
- } else {\r
- ret += s.charAt(i);\r
- }\r
+\r
+ public static String convertMIMEtoPrettyPrint(String mimetype) {\r
+ if (mimeType2HUmanReadable.containsKey(mimetype)) {\r
+ return mimeType2HUmanReadable.get(mimetype);\r
+ }\r
+ return mimetype.split("/")[1].toUpperCase() + " file";\r
}\r
- return ret;\r
- }\r
\r
- public static String convertMIMEtoPrettyPrint(String mimetype) {\r
- if (mimeType2HUmanReadable.containsKey(mimetype)) {\r
- return mimeType2HUmanReadable.get(mimetype);\r
+ private static final String[] suffixes = { "B", "KB", "MB", "GB", "TB",\r
+ "PB", "EB", "ZB", "YB" };\r
+\r
+ private static HashMap<String, String> mimeType2HUmanReadable;\r
+ static {\r
+ mimeType2HUmanReadable = new HashMap<String, String>();\r
+ // images\r
+ mimeType2HUmanReadable.put("image/jpeg", "JPEG image");\r
+ mimeType2HUmanReadable.put("image/jpg", "JPEG image");\r
+ mimeType2HUmanReadable.put("image/png", "PNG image");\r
+ mimeType2HUmanReadable.put("image/bmp", "Bitmap image");\r
+ mimeType2HUmanReadable.put("image/gif", "GIF image");\r
+ mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");\r
+ mimeType2HUmanReadable.put("image/tiff", "TIFF image");\r
+ // music\r
+ mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");\r
+ mimeType2HUmanReadable.put("application/ogg", "OGG music file");\r
+\r
}\r
- return mimetype.split("/")[1].toUpperCase() + " file";\r
- }\r
- \r
- private static final String[] suffixes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};\r
- \r
- private static HashMap<String, String> mimeType2HUmanReadable;\r
- static {\r
- mimeType2HUmanReadable = new HashMap<String, String>();\r
- // images\r
- mimeType2HUmanReadable.put("image/jpeg", "JPEG image");\r
- mimeType2HUmanReadable.put("image/jpg", "JPEG image");\r
- mimeType2HUmanReadable.put("image/png", "PNG image");\r
- mimeType2HUmanReadable.put("image/bmp", "Bitmap image");\r
- mimeType2HUmanReadable.put("image/gif", "GIF image");\r
- mimeType2HUmanReadable.put("image/svg+xml", "JPEG image");\r
- mimeType2HUmanReadable.put("image/tiff", "TIFF image");\r
- // music\r
- mimeType2HUmanReadable.put("audio/mpeg", "MP3 music file");\r
- mimeType2HUmanReadable.put("application/ogg", "OGG music file");\r
- \r
- }\r
}\r
import eu.alefzero.webdav.WebdavClient;\r
\r
public class FileDownloader extends Service {\r
- public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";\r
- public static final String EXTRA_ACCOUNT = "ACCOUNT";\r
- public static final String EXTRA_FILE_PATH = "FILE_PATH";\r
- private static final String TAG = "FileDownloader";\r
- \r
- private NotificationManager nm;\r
- private Looper mServiceLooper;\r
- private ServiceHandler mServiceHandler;\r
- private Account mAccount;\r
- private String mFilePath;\r
- \r
- private final class ServiceHandler extends Handler {\r
- public ServiceHandler(Looper looper) {\r
- super(looper);\r
+ public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";\r
+ public static final String EXTRA_ACCOUNT = "ACCOUNT";\r
+ public static final String EXTRA_FILE_PATH = "FILE_PATH";\r
+ private static final String TAG = "FileDownloader";\r
+\r
+ private NotificationManager nm;\r
+ private Looper mServiceLooper;\r
+ private ServiceHandler mServiceHandler;\r
+ private Account mAccount;\r
+ private String mFilePath;\r
+\r
+ private final class ServiceHandler extends Handler {\r
+ public ServiceHandler(Looper looper) {\r
+ super(looper);\r
+ }\r
+\r
+ @Override\r
+ public void handleMessage(Message msg) {\r
+ downloadFile();\r
+ stopSelf(msg.arg1);\r
+ }\r
}\r
+\r
@Override\r
- public void handleMessage(Message msg) {\r
- downloadFile();\r
- stopSelf(msg.arg1);\r
+ public void onCreate() {\r
+ super.onCreate();\r
+ nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\r
+ HandlerThread thread = new HandlerThread("FileDownladerThread",\r
+ Process.THREAD_PRIORITY_BACKGROUND);\r
+ thread.start();\r
+ mServiceLooper = thread.getLooper();\r
+ mServiceHandler = new ServiceHandler(mServiceLooper);\r
}\r
- }\r
- \r
- @Override\r
- public void onCreate() {\r
- super.onCreate();\r
- nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);\r
- HandlerThread thread = new HandlerThread("FileDownladerThread", Process.THREAD_PRIORITY_BACKGROUND);\r
- thread.start();\r
- mServiceLooper = thread.getLooper();\r
- mServiceHandler = new ServiceHandler(mServiceLooper); \r
- }\r
- \r
- @Override\r
- public IBinder onBind(Intent arg0) {\r
- return null;\r
- }\r
-\r
- @Override\r
- public int onStartCommand(Intent intent, int flags, int startId) {\r
- if (!intent.hasExtra(EXTRA_ACCOUNT) && !intent.hasExtra(EXTRA_FILE_PATH)) {\r
- Log.e(TAG, "Not enough information provided in intent");\r
- return START_STICKY;\r
+\r
+ @Override\r
+ public IBinder onBind(Intent arg0) {\r
+ return null;\r
+ }\r
+\r
+ @Override\r
+ public int onStartCommand(Intent intent, int flags, int startId) {\r
+ if (!intent.hasExtra(EXTRA_ACCOUNT)\r
+ && !intent.hasExtra(EXTRA_FILE_PATH)) {\r
+ Log.e(TAG, "Not enough information provided in intent");\r
+ return START_STICKY;\r
+ }\r
+ mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);\r
+ mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);\r
+ Message msg = mServiceHandler.obtainMessage();\r
+ msg.arg1 = startId;\r
+ mServiceHandler.sendMessage(msg);\r
+\r
+ return START_NOT_STICKY;\r
}\r
- mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);\r
- mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);\r
- Message msg = mServiceHandler.obtainMessage();\r
- msg.arg1 = startId;\r
- mServiceHandler.sendMessage(msg);\r
-\r
- return START_NOT_STICKY;\r
- }\r
- \r
- void downloadFile() {\r
- AccountManager am = (AccountManager)getSystemService(ACCOUNT_SERVICE);\r
- Uri oc_url = Uri.parse(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_URL));\r
-\r
- WebdavClient wdc = new WebdavClient(oc_url);\r
- \r
- String username = mAccount.name.split("@")[0];\r
- String password = "";\r
- try {\r
- password = am.blockingGetAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
- } catch (Exception e) {\r
- e.printStackTrace();\r
+\r
+ void downloadFile() {\r
+ AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);\r
+ Uri oc_url = Uri.parse(am.getUserData(mAccount,\r
+ AccountAuthenticator.KEY_OC_URL));\r
+\r
+ WebdavClient wdc = new WebdavClient(oc_url);\r
+\r
+ String username = mAccount.name.split("@")[0];\r
+ String password = "";\r
+ try {\r
+ password = am.blockingGetAuthToken(mAccount,\r
+ AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
+ } catch (Exception e) {\r
+ e.printStackTrace();\r
+ }\r
+\r
+ wdc.setCredentials(username, password);\r
+ wdc.allowUnsignedCertificates();\r
+\r
+ Notification n = new Notification(R.drawable.icon, "Downloading file",\r
+ System.currentTimeMillis());\r
+ PendingIntent pi = PendingIntent.getActivity(this, 1, new Intent(this,\r
+ FileDisplayActivity.class), 0);\r
+ n.setLatestEventInfo(this, "Downloading file", "Downloading file "\r
+ + mFilePath, pi);\r
+ nm.notify(1, n);\r
+\r
+ File sdCard = Environment.getExternalStorageDirectory();\r
+ File dir = new File(sdCard.getAbsolutePath() + "/owncloud");\r
+ dir.mkdirs();\r
+ File file = new File(dir, mFilePath.replace('/', '.'));\r
+\r
+ Log.e(TAG, file.getAbsolutePath() + " " + oc_url.toString());\r
+ wdc.downloadFile(mFilePath, file);\r
+ ContentValues cv = new ContentValues();\r
+ cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());\r
+ getContentResolver().update(\r
+ ProviderTableMeta.CONTENT_URI,\r
+ cv,\r
+ ProviderTableMeta.FILE_NAME + "=? AND "\r
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",\r
+ new String[] {\r
+ mFilePath.substring(mFilePath.lastIndexOf('/') + 1),\r
+ mAccount.name });\r
+ nm.cancel(1);\r
+ Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);\r
+ sendBroadcast(end);\r
}\r
- \r
- wdc.setCredentials(username, password);\r
- wdc.allowUnsignedCertificates();\r
-\r
- Notification n = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis());\r
- PendingIntent pi = PendingIntent.getActivity(this, 1, new Intent(this, FileDisplayActivity.class), 0);\r
- n.setLatestEventInfo(this, "Downloading file", "Downloading file " + mFilePath, pi);\r
- nm.notify(1, n);\r
-\r
- File sdCard = Environment.getExternalStorageDirectory();\r
- File dir = new File (sdCard.getAbsolutePath() + "/owncloud");\r
- dir.mkdirs();\r
- File file = new File(dir, mFilePath.replace('/', '.'));\r
- \r
- Log.e(TAG, file.getAbsolutePath() + " " + oc_url.toString());\r
- wdc.downloadFile(mFilePath, file);\r
- ContentValues cv = new ContentValues();\r
- cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());\r
- getContentResolver().update(ProviderTableMeta.CONTENT_URI,\r
- cv,\r
- ProviderTableMeta.FILE_NAME +"=? AND "+ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",\r
- new String[]{mFilePath.substring(mFilePath.lastIndexOf('/')+1), mAccount.name});\r
- nm.cancel(1);\r
- Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);\r
- sendBroadcast(end);\r
- }\r
- \r
+\r
}\r
\r
/**\r
* Represents a session to an ownCloud instance\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class OwnCloudSession {\r
- private String mSessionName;\r
- private String mSessionUrl;\r
- private int mEntryId;\r
- \r
- public OwnCloudSession(String name, String url, int entryId) {\r
- mSessionName = name;\r
- mSessionUrl = url;\r
- mEntryId = entryId;\r
- }\r
- \r
- public void setName(String name) {\r
- mSessionName = name;\r
- }\r
- \r
- public String getName() {\r
- return mSessionName;\r
- }\r
- \r
- public void setUrl(String url) {\r
- mSessionUrl = url;\r
- }\r
- \r
- public String getUrl() {\r
- return mSessionUrl;\r
- }\r
- \r
- public int getEntryId() {\r
- return mEntryId;\r
- }\r
+ private String mSessionName;\r
+ private String mSessionUrl;\r
+ private int mEntryId;\r
+\r
+ public OwnCloudSession(String name, String url, int entryId) {\r
+ mSessionName = name;\r
+ mSessionUrl = url;\r
+ mEntryId = entryId;\r
+ }\r
+\r
+ public void setName(String name) {\r
+ mSessionName = name;\r
+ }\r
+\r
+ public String getName() {\r
+ return mSessionName;\r
+ }\r
+\r
+ public void setUrl(String url) {\r
+ mSessionUrl = url;\r
+ }\r
+\r
+ public String getUrl() {\r
+ return mSessionUrl;\r
+ }\r
+\r
+ public int getEntryId() {\r
+ return mEntryId;\r
+ }\r
}\r
\r
/**\r
* This can be used to upload things to an ownCloud instance.\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
-public class Uploader extends ListActivity implements OnItemClickListener, android.view.View.OnClickListener {\r
- private static final String TAG = "ownCloudUploader";\r
-\r
- private Account mAccount;\r
- private AccountManager mAccountManager;\r
- private String mUsername, mPassword;\r
- private Cursor mCursor;\r
- private Stack<String> mParents;\r
- private Thread mUploadThread;\r
- private Handler mHandler;\r
- private ArrayList<Parcelable> mStreamsToUpload;\r
-\r
- private final static int DIALOG_NO_ACCOUNT = 0;\r
- private final static int DIALOG_WAITING = 1;\r
- private final static int DIALOG_NO_STREAM = 2;\r
- private final static int DIALOG_MULTIPLE_ACCOUNT = 3;\r
- private final static int DIALOG_GET_DIRNAME = 4;\r
-\r
- private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;\r
-\r
- @Override\r
- protected void onCreate(Bundle savedInstanceState) {\r
- super.onCreate(savedInstanceState);\r
- getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
- mParents = new Stack<String>();\r
- mHandler = new Handler();\r
- if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {\r
- prepareStreamsToUpload();\r
- mAccountManager = (AccountManager)getSystemService(Context.ACCOUNT_SERVICE);\r
- Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
- if (accounts.length == 0) {\r
- Log.i(TAG, "No ownCloud account is available");\r
- showDialog(DIALOG_NO_ACCOUNT);\r
- } else if (accounts.length > 1) {\r
- Log.i(TAG, "More then one ownCloud is available");\r
- showDialog(DIALOG_MULTIPLE_ACCOUNT);\r
- } else {\r
- mAccount = accounts[0];\r
- setContentView(R.layout.uploader_layout);\r
- populateDirectoryList();\r
- }\r
- } else {\r
- showDialog(DIALOG_NO_STREAM);\r
- }\r
- }\r
-\r
- @Override\r
- protected Dialog onCreateDialog(final int id) {\r
- final AlertDialog.Builder builder = new Builder(this);\r
- switch (id) {\r
- case DIALOG_WAITING:\r
- ProgressDialog pDialog = new ProgressDialog(this);\r
- pDialog.setIndeterminate(false);\r
- pDialog.setCancelable(false);\r
- pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));\r
- return pDialog;\r
- case DIALOG_NO_ACCOUNT:\r
- builder.setIcon(android.R.drawable.ic_dialog_alert);\r
- builder.setTitle(R.string.uploader_wrn_no_account_title);\r
- builder.setMessage(R.string.uploader_wrn_no_account_text);\r
- builder.setCancelable(false);\r
- builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {\r
- public void onClick(DialogInterface dialog, int which) {\r
- if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {\r
- // using string value since in API7 this constatn is not defined\r
- // in API7 < this constatant is defined in Settings.ADD_ACCOUNT_SETTINGS\r
- // and Settings.EXTRA_AUTHORITIES\r
- Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
- intent.putExtra("authorities", new String[] {AccountAuthenticator.AUTH_TOKEN_TYPE});\r
- startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);\r
+public class Uploader extends ListActivity implements OnItemClickListener,\r
+ android.view.View.OnClickListener {\r
+ private static final String TAG = "ownCloudUploader";\r
+\r
+ private Account mAccount;\r
+ private AccountManager mAccountManager;\r
+ private String mUsername, mPassword;\r
+ private Cursor mCursor;\r
+ private Stack<String> mParents;\r
+ private Thread mUploadThread;\r
+ private Handler mHandler;\r
+ private ArrayList<Parcelable> mStreamsToUpload;\r
+\r
+ private final static int DIALOG_NO_ACCOUNT = 0;\r
+ private final static int DIALOG_WAITING = 1;\r
+ private final static int DIALOG_NO_STREAM = 2;\r
+ private final static int DIALOG_MULTIPLE_ACCOUNT = 3;\r
+ private final static int DIALOG_GET_DIRNAME = 4;\r
+\r
+ private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;\r
+\r
+ @Override\r
+ protected void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
+ mParents = new Stack<String>();\r
+ mHandler = new Handler();\r
+ if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {\r
+ prepareStreamsToUpload();\r
+ mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);\r
+ Account[] accounts = mAccountManager\r
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
+ if (accounts.length == 0) {\r
+ Log.i(TAG, "No ownCloud account is available");\r
+ showDialog(DIALOG_NO_ACCOUNT);\r
+ } else if (accounts.length > 1) {\r
+ Log.i(TAG, "More then one ownCloud is available");\r
+ showDialog(DIALOG_MULTIPLE_ACCOUNT);\r
} else {\r
- // since in API7 there is no direct call for account setup, so we need to\r
- // show our own AccountSetupAcricity, get desired results and setup\r
- // everything for ourself\r
- Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);\r
- startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);\r
+ mAccount = accounts[0];\r
+ setContentView(R.layout.uploader_layout);\r
+ populateDirectoryList();\r
}\r
- }\r
- });\r
- builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {\r
- public void onClick(DialogInterface dialog, int which) {\r
- finish();\r
- }\r
- });\r
- return builder.create();\r
- case DIALOG_GET_DIRNAME:\r
- final EditText dirName = new EditText(getBaseContext());\r
- builder.setView(dirName);\r
- builder.setTitle(R.string.uploader_info_dirname);\r
- String pathToUpload;\r
- if (mParents.empty()) {\r
- pathToUpload = "/";\r
} else {\r
- mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), \r
- null,\r
- null,\r
- null,\r
- null);\r
- mCursor.moveToFirst();\r
- pathToUpload = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH)) +\r
- mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_NAME)).replace(" ", "%20");\r
+ showDialog(DIALOG_NO_STREAM);\r
}\r
- a a = new a(pathToUpload, dirName);\r
- builder.setPositiveButton(R.string.common_ok, a);\r
- builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {\r
- public void onClick(DialogInterface dialog, int which) {\r
- dialog.cancel();\r
- }\r
- });\r
- return builder.create();\r
- case DIALOG_MULTIPLE_ACCOUNT:\r
- CharSequence ac[] = new CharSequence[mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];\r
- for (int i = 0; i < ac.length; ++i) {\r
- ac[i] = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;\r
+ }\r
+\r
+ @Override\r
+ protected Dialog onCreateDialog(final int id) {\r
+ final AlertDialog.Builder builder = new Builder(this);\r
+ switch (id) {\r
+ case DIALOG_WAITING:\r
+ ProgressDialog pDialog = new ProgressDialog(this);\r
+ pDialog.setIndeterminate(false);\r
+ pDialog.setCancelable(false);\r
+ pDialog.setMessage(getResources().getString(\r
+ R.string.uploader_info_uploading));\r
+ return pDialog;\r
+ case DIALOG_NO_ACCOUNT:\r
+ builder.setIcon(android.R.drawable.ic_dialog_alert);\r
+ builder.setTitle(R.string.uploader_wrn_no_account_title);\r
+ builder.setMessage(R.string.uploader_wrn_no_account_text);\r
+ builder.setCancelable(false);\r
+ builder.setPositiveButton(\r
+ R.string.uploader_wrn_no_account_setup_btn_text,\r
+ new OnClickListener() {\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1) {\r
+ // using string value since in API7 this\r
+ // constatn is not defined\r
+ // in API7 < this constatant is defined in\r
+ // Settings.ADD_ACCOUNT_SETTINGS\r
+ // and Settings.EXTRA_AUTHORITIES\r
+ Intent intent = new Intent(\r
+ "android.settings.ADD_ACCOUNT_SETTINGS");\r
+ intent.putExtra(\r
+ "authorities",\r
+ new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
+ startActivityForResult(intent,\r
+ REQUEST_CODE_SETUP_ACCOUNT);\r
+ } else {\r
+ // since in API7 there is no direct call for\r
+ // account setup, so we need to\r
+ // show our own AccountSetupAcricity, get\r
+ // desired results and setup\r
+ // everything for ourself\r
+ Intent intent = new Intent(getBaseContext(),\r
+ AccountAuthenticator.class);\r
+ startActivityForResult(intent,\r
+ REQUEST_CODE_SETUP_ACCOUNT);\r
+ }\r
+ }\r
+ });\r
+ builder.setNegativeButton(\r
+ R.string.uploader_wrn_no_account_quit_btn_text,\r
+ new OnClickListener() {\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ finish();\r
+ }\r
+ });\r
+ return builder.create();\r
+ case DIALOG_GET_DIRNAME:\r
+ final EditText dirName = new EditText(getBaseContext());\r
+ builder.setView(dirName);\r
+ builder.setTitle(R.string.uploader_info_dirname);\r
+ String pathToUpload;\r
+ if (mParents.empty()) {\r
+ pathToUpload = "/";\r
+ } else {\r
+ mCursor = managedQuery(Uri.withAppendedPath(\r
+ ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()),\r
+ null, null, null, null);\r
+ mCursor.moveToFirst();\r
+ pathToUpload = mCursor.getString(mCursor\r
+ .getColumnIndex(ProviderTableMeta.FILE_PATH))\r
+ + mCursor\r
+ .getString(\r
+ mCursor.getColumnIndex(ProviderTableMeta.FILE_NAME))\r
+ .replace(" ", "%20");\r
+ }\r
+ a a = new a(pathToUpload, dirName);\r
+ builder.setPositiveButton(R.string.common_ok, a);\r
+ builder.setNegativeButton(R.string.common_cancel,\r
+ new OnClickListener() {\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ dialog.cancel();\r
+ }\r
+ });\r
+ return builder.create();\r
+ case DIALOG_MULTIPLE_ACCOUNT:\r
+ CharSequence ac[] = new CharSequence[mAccountManager\r
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE).length];\r
+ for (int i = 0; i < ac.length; ++i) {\r
+ ac[i] = mAccountManager\r
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[i].name;\r
+ }\r
+ builder.setTitle(R.string.common_choose_account);\r
+ builder.setItems(ac, new OnClickListener() {\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ mAccount = mAccountManager\r
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];\r
+ populateDirectoryList();\r
+ }\r
+ });\r
+ builder.setCancelable(true);\r
+ builder.setOnCancelListener(new OnCancelListener() {\r
+ public void onCancel(DialogInterface dialog) {\r
+ dialog.cancel();\r
+ finish();\r
+ }\r
+ });\r
+ return builder.create();\r
+ default:\r
+ throw new IllegalArgumentException("Unknown dialog id: " + id);\r
}\r
- builder.setTitle(R.string.common_choose_account);\r
- builder.setItems(ac, new OnClickListener() {\r
- public void onClick(DialogInterface dialog, int which) {\r
- mAccount = mAccountManager.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE)[which];\r
- populateDirectoryList();\r
- }\r
- });\r
- builder.setCancelable(true);\r
- builder.setOnCancelListener(new OnCancelListener() {\r
- public void onCancel(DialogInterface dialog) {\r
- dialog.cancel();\r
- finish();\r
- }\r
- });\r
- return builder.create();\r
- default:\r
- throw new IllegalArgumentException("Unknown dialog id: " + id);\r
}\r
- }\r
- \r
- class a implements OnClickListener {\r
- String mPath;\r
- EditText mDirname;\r
- public a(String path, EditText dirname) {\r
- mPath = path; mDirname = dirname;\r
+\r
+ class a implements OnClickListener {\r
+ String mPath;\r
+ EditText mDirname;\r
+\r
+ public a(String path, EditText dirname) {\r
+ mPath = path;\r
+ mDirname = dirname;\r
+ }\r
+\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ showDialog(DIALOG_WAITING);\r
+ mUploadThread = new Thread(new BackgroundUploader(mPath\r
+ + mDirname.getText().toString(), mStreamsToUpload,\r
+ mHandler, true));\r
+ mUploadThread.start();\r
+ }\r
}\r
- public void onClick(DialogInterface dialog, int which) {\r
- showDialog(DIALOG_WAITING);\r
- mUploadThread = new Thread(new BackgroundUploader(mPath+mDirname.getText().toString(), mStreamsToUpload, mHandler, true));\r
- mUploadThread.start();\r
+\r
+ @Override\r
+ public void onBackPressed() {\r
+\r
+ if (mParents.size() == 0) {\r
+ super.onBackPressed();\r
+ return;\r
+ } else if (mParents.size() == 1) {\r
+ mParents.pop();\r
+ mCursor = managedQuery(ProviderTableMeta.CONTENT_URI, null,\r
+ ProviderTableMeta.FILE_CONTENT_TYPE + "=?",\r
+ new String[] { "DIR" }, null);\r
+ } else {\r
+ mParents.pop();\r
+ mCursor = managedQuery(Uri.withAppendedPath(\r
+ ProviderTableMeta.CONTENT_URI_DIR, mParents.peek()), null,\r
+ ProviderTableMeta.FILE_CONTENT_TYPE + "=?",\r
+ new String[] { "DIR" }, null);\r
+ }\r
+\r
+ SimpleCursorAdapter sca = new SimpleCursorAdapter(this,\r
+ R.layout.uploader_list_item_layout, mCursor,\r
+ new String[] { ProviderTableMeta.FILE_NAME },\r
+ new int[] { R.id.textView1 });\r
+ setListAdapter(sca);\r
}\r
- }\r
- \r
- @Override\r
- public void onBackPressed() {\r
- \r
- if (mParents.size()==0) {\r
- super.onBackPressed();\r
- return;\r
- } else if (mParents.size() == 1) {\r
- mParents.pop();\r
- mCursor = managedQuery(ProviderTableMeta.CONTENT_URI,\r
- null,\r
- ProviderTableMeta.FILE_CONTENT_TYPE+"=?",\r
- new String[]{"DIR"},\r
- null);\r
- } else {\r
- mParents.pop();\r
- mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, mParents.peek()),\r
- null,\r
- ProviderTableMeta.FILE_CONTENT_TYPE+"=?",\r
- new String[]{"DIR"},\r
- null);\r
+\r
+ public void onItemClick(AdapterView<?> parent, View view, int position,\r
+ long id) {\r
+ if (!mCursor.moveToPosition(position)) {\r
+ throw new IndexOutOfBoundsException("Incorrect item selected");\r
+ }\r
+ String _id = mCursor.getString(mCursor\r
+ .getColumnIndex(ProviderTableMeta._ID));\r
+ mParents.push(_id);\r
+\r
+ mCursor.close();\r
+ mCursor = managedQuery(\r
+ Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, _id),\r
+ null, ProviderTableMeta.FILE_CONTENT_TYPE + "=?",\r
+ new String[] { "DIR" }, null);\r
+ SimpleCursorAdapter sca = new SimpleCursorAdapter(this,\r
+ R.layout.uploader_list_item_layout, mCursor,\r
+ new String[] { ProviderTableMeta.FILE_NAME },\r
+ new int[] { R.id.textView1 });\r
+ setListAdapter(sca);\r
+ getListView().invalidate();\r
}\r
- \r
- SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout,\r
- mCursor,\r
- new String[]{ProviderTableMeta.FILE_NAME},\r
- new int[]{R.id.textView1});\r
- setListAdapter(sca);\r
- }\r
- \r
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\r
- if (!mCursor.moveToPosition(position)) {\r
- throw new IndexOutOfBoundsException("Incorrect item selected");\r
+\r
+ public void onClick(View v) {\r
+ switch (v.getId()) {\r
+ case R.id.uploader_choose_folder:\r
+ String pathToUpload = null;\r
+ if (mParents.empty()) {\r
+ pathToUpload = "/";\r
+ } else {\r
+ mCursor = managedQuery(Uri.withAppendedPath(\r
+ ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()),\r
+ null, null, null, null);\r
+ mCursor.moveToFirst();\r
+ pathToUpload = mCursor.getString(\r
+ mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH))\r
+ .replace(" ", "%20");\r
+ }\r
+ Log.d(TAG, "Uploading file to dir " + pathToUpload);\r
+\r
+ showDialog(DIALOG_WAITING);\r
+ mUploadThread = new Thread(new BackgroundUploader(pathToUpload,\r
+ mStreamsToUpload, mHandler));\r
+ mUploadThread.start();\r
+\r
+ break;\r
+ case android.R.id.button1: // dynamic action for create aditional dir\r
+ showDialog(DIALOG_GET_DIRNAME);\r
+ break;\r
+ default:\r
+ throw new IllegalArgumentException("Wrong element clicked");\r
+ }\r
}\r
- String _id = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID));\r
- mParents.push(_id);\r
- \r
- mCursor.close();\r
- mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_DIR, _id),\r
- null,\r
- ProviderTableMeta.FILE_CONTENT_TYPE+"=?",\r
- new String[]{"DIR"},\r
- null);\r
- SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.uploader_list_item_layout,\r
- mCursor,\r
- new String[]{ProviderTableMeta.FILE_NAME},\r
- new int[]{R.id.textView1});\r
- setListAdapter(sca);\r
- getListView().invalidate();\r
- }\r
-\r
- public void onClick(View v) {\r
- switch (v.getId()) {\r
- case R.id.uploader_choose_folder:\r
- String pathToUpload = null;\r
- if (mParents.empty()) {\r
- pathToUpload = "/";\r
+\r
+ public void onUploadComplete(boolean uploadSucc, String message) {\r
+ dismissDialog(DIALOG_WAITING);\r
+ Log.i(TAG, "UploadSucc: " + uploadSucc + " message: " + message);\r
+ if (uploadSucc) {\r
+ Toast.makeText(this,\r
+ getResources().getString(R.string.uploader_upload_succeed),\r
+ Toast.LENGTH_SHORT).show();\r
} else {\r
- mCursor = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), \r
- null,\r
- null,\r
- null,\r
- null);\r
- mCursor.moveToFirst();\r
- pathToUpload = mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta.FILE_PATH)).replace(" ", "%20");\r
+ Toast.makeText(\r
+ this,\r
+ getResources().getString(R.string.uploader_upload_failed)\r
+ + message, Toast.LENGTH_LONG).show();\r
}\r
- Log.d(TAG, "Uploading file to dir " + pathToUpload);\r
- \r
- showDialog(DIALOG_WAITING);\r
- mUploadThread = new Thread(new BackgroundUploader(pathToUpload, mStreamsToUpload, mHandler));\r
- mUploadThread.start();\r
- \r
- break;\r
- case android.R.id.button1: // dynamic action for create aditional dir\r
- showDialog(DIALOG_GET_DIRNAME);\r
- break;\r
- default:\r
- throw new IllegalArgumentException("Wrong element clicked");\r
- }\r
- }\r
-\r
- public void onUploadComplete(boolean uploadSucc, String message) {\r
- dismissDialog(DIALOG_WAITING);\r
- Log.i(TAG, "UploadSucc: " + uploadSucc + " message: " + message);\r
- if (uploadSucc) {\r
- Toast.makeText(this, getResources().getString(R.string.uploader_upload_succeed), Toast.LENGTH_SHORT).show();\r
- } else {\r
- Toast.makeText(this, getResources().getString(R.string.uploader_upload_failed) + message, Toast.LENGTH_LONG).show();\r
- }\r
- finish();\r
- }\r
- \r
- @Override\r
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {\r
- super.onActivityResult(requestCode, resultCode, data);\r
- Log.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);\r
- if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {\r
- dismissDialog(DIALOG_NO_ACCOUNT);\r
- if (resultCode == RESULT_CANCELED) {\r
finish();\r
- }\r
- Account[] accounts = mAccountManager.getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);\r
- if (accounts.length == 0) {\r
- showDialog(DIALOG_NO_ACCOUNT);\r
- } else {\r
- // there is no need for checking for is there more then one account at this point\r
- // since account setup can set only one account at time\r
- mAccount = accounts[0];\r
- populateDirectoryList();\r
- }\r
- }\r
- }\r
- \r
- private void populateDirectoryList() {\r
- mUsername = mAccount.name.substring(0, mAccount.name.indexOf('@'));\r
- mPassword = mAccountManager.getPassword(mAccount);\r
- setContentView(R.layout.uploader_layout);\r
- \r
- mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI,\r
- null,\r
- ProviderTableMeta.FILE_NAME+"=? AND " +ProviderTableMeta.FILE_ACCOUNT_OWNER+"=?",\r
- new String[]{"/", mAccount.name},\r
- null);\r
- \r
- if (mCursor.moveToFirst()) {\r
- mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI,\r
- null,\r
- ProviderTableMeta.FILE_CONTENT_TYPE+"=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " +ProviderTableMeta.FILE_PARENT+"=?",\r
- new String[]{"DIR", mAccount.name, mCursor.getString(mCursor.getColumnIndex(ProviderTableMeta._ID))},\r
- null); \r
- \r
- ListView lv = getListView();\r
- lv.setOnItemClickListener(this);\r
- SimpleCursorAdapter sca = new SimpleCursorAdapter(this,\r
- R.layout.uploader_list_item_layout,\r
- mCursor,\r
- new String[]{ProviderTableMeta.FILE_NAME},\r
- new int[]{R.id.textView1});\r
- setListAdapter(sca);\r
- Button btn = (Button) findViewById(R.id.uploader_choose_folder);\r
- btn.setOnClickListener(this);\r
- // insert create new directory for multiple items uploading\r
- if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {\r
- Button createDirBtn = new Button(this);\r
- createDirBtn.setId(android.R.id.button1);\r
- createDirBtn.setText(R.string.uploader_btn_create_dir_text);\r
- createDirBtn.setOnClickListener(this);\r
- ((LinearLayout)findViewById(R.id.linearLayout1)).addView(createDirBtn, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);\r
- }\r
}\r
- }\r
- \r
- private void prepareStreamsToUpload() {\r
- if (getIntent().getAction().equals(Intent.ACTION_SEND)) {\r
- mStreamsToUpload = new ArrayList<Parcelable>();\r
- mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));\r
- } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {\r
- mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);\r
- } else {\r
- // unknow action inserted\r
- throw new IllegalArgumentException("Unknown action given: " + getIntent().getAction());\r
+\r
+ @Override\r
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {\r
+ super.onActivityResult(requestCode, resultCode, data);\r
+ Log.i(TAG, "result received. req: " + requestCode + " res: "\r
+ + resultCode);\r
+ if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {\r
+ dismissDialog(DIALOG_NO_ACCOUNT);\r
+ if (resultCode == RESULT_CANCELED) {\r
+ finish();\r
+ }\r
+ Account[] accounts = mAccountManager\r
+ .getAccountsByType(AccountAuthenticator.AUTH_TOKEN_TYPE);\r
+ if (accounts.length == 0) {\r
+ showDialog(DIALOG_NO_ACCOUNT);\r
+ } else {\r
+ // there is no need for checking for is there more then one\r
+ // account at this point\r
+ // since account setup can set only one account at time\r
+ mAccount = accounts[0];\r
+ populateDirectoryList();\r
+ }\r
+ }\r
}\r
- }\r
- \r
- public void PartialupdateUpload(String fileLocalPath, String filename, String filepath, String contentType, String contentLength) {\r
- ContentValues cv = new ContentValues();\r
- cv.put(ProviderTableMeta.FILE_NAME, filename);\r
- cv.put(ProviderTableMeta.FILE_PATH, filepath);\r
- cv.put(ProviderTableMeta.FILE_STORAGE_PATH, fileLocalPath);\r
- cv.put(ProviderTableMeta.FILE_MODIFIED, WebdavUtils.DISPLAY_DATE_FORMAT.format(new java.util.Date()));\r
- cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, contentType);\r
- cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, contentLength);\r
- cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);\r
- Log.d(TAG, filename+" ++ "+filepath+" ++ " + contentLength + " ++ " + contentType + " ++ " + fileLocalPath);\r
- if (!mParents.empty()) {\r
- Cursor c = managedQuery(Uri.withAppendedPath(ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()),\r
- null,\r
- null,\r
- null,\r
- null);\r
- c.moveToFirst();\r
- cv.put(ProviderTableMeta.FILE_PARENT, c.getString(c.getColumnIndex(ProviderTableMeta._ID)));\r
- c.close();\r
+\r
+ private void populateDirectoryList() {\r
+ mUsername = mAccount.name.substring(0, mAccount.name.indexOf('@'));\r
+ mPassword = mAccountManager.getPassword(mAccount);\r
+ setContentView(R.layout.uploader_layout);\r
+\r
+ mCursor = managedQuery(ProviderMeta.ProviderTableMeta.CONTENT_URI,\r
+ null, ProviderTableMeta.FILE_NAME + "=? AND "\r
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",\r
+ new String[] { "/", mAccount.name }, null);\r
+\r
+ if (mCursor.moveToFirst()) {\r
+ mCursor = managedQuery(\r
+ ProviderMeta.ProviderTableMeta.CONTENT_URI,\r
+ null,\r
+ ProviderTableMeta.FILE_CONTENT_TYPE + "=? AND "\r
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND "\r
+ + ProviderTableMeta.FILE_PARENT + "=?",\r
+ new String[] {\r
+ "DIR",\r
+ mAccount.name,\r
+ mCursor.getString(mCursor\r
+ .getColumnIndex(ProviderTableMeta._ID)) },\r
+ null);\r
+\r
+ ListView lv = getListView();\r
+ lv.setOnItemClickListener(this);\r
+ SimpleCursorAdapter sca = new SimpleCursorAdapter(this,\r
+ R.layout.uploader_list_item_layout, mCursor,\r
+ new String[] { ProviderTableMeta.FILE_NAME },\r
+ new int[] { R.id.textView1 });\r
+ setListAdapter(sca);\r
+ Button btn = (Button) findViewById(R.id.uploader_choose_folder);\r
+ btn.setOnClickListener(this);\r
+ // insert create new directory for multiple items uploading\r
+ if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {\r
+ Button createDirBtn = new Button(this);\r
+ createDirBtn.setId(android.R.id.button1);\r
+ createDirBtn.setText(R.string.uploader_btn_create_dir_text);\r
+ createDirBtn.setOnClickListener(this);\r
+ ((LinearLayout) findViewById(R.id.linearLayout1)).addView(\r
+ createDirBtn, LayoutParams.FILL_PARENT,\r
+ LayoutParams.WRAP_CONTENT);\r
+ }\r
+ }\r
}\r
- getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);\r
- }\r
- \r
- class BackgroundUploader implements Runnable {\r
- private ArrayList<Parcelable> mUploadStreams;\r
- private Handler mHandler;\r
- private String mUploadPath;\r
- private boolean mCreateDir;\r
- \r
- public BackgroundUploader(String pathToUpload, ArrayList<Parcelable> streamsToUpload,\r
- Handler handler) {\r
- mUploadStreams = streamsToUpload;\r
- mHandler = handler;\r
- mUploadPath = pathToUpload.replace(" ", "%20");\r
- mCreateDir = false;\r
+\r
+ private void prepareStreamsToUpload() {\r
+ if (getIntent().getAction().equals(Intent.ACTION_SEND)) {\r
+ mStreamsToUpload = new ArrayList<Parcelable>();\r
+ mStreamsToUpload.add(getIntent().getParcelableExtra(\r
+ Intent.EXTRA_STREAM));\r
+ } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {\r
+ mStreamsToUpload = getIntent().getParcelableArrayListExtra(\r
+ Intent.EXTRA_STREAM);\r
+ } else {\r
+ // unknow action inserted\r
+ throw new IllegalArgumentException("Unknown action given: "\r
+ + getIntent().getAction());\r
+ }\r
}\r
\r
- public BackgroundUploader(String pathToUpload, ArrayList<Parcelable> streamsToUpload,\r
- Handler handler, boolean createDir) {\r
- mUploadStreams = streamsToUpload;\r
- mHandler = handler;\r
- mUploadPath = pathToUpload.replace(" ", "%20");\r
- mCreateDir = createDir;\r
+ public void PartialupdateUpload(String fileLocalPath, String filename,\r
+ String filepath, String contentType, String contentLength) {\r
+ ContentValues cv = new ContentValues();\r
+ cv.put(ProviderTableMeta.FILE_NAME, filename);\r
+ cv.put(ProviderTableMeta.FILE_PATH, filepath);\r
+ cv.put(ProviderTableMeta.FILE_STORAGE_PATH, fileLocalPath);\r
+ cv.put(ProviderTableMeta.FILE_MODIFIED,\r
+ WebdavUtils.DISPLAY_DATE_FORMAT.format(new java.util.Date()));\r
+ cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, contentType);\r
+ cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, contentLength);\r
+ cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);\r
+ Log.d(TAG, filename + " ++ " + filepath + " ++ " + contentLength\r
+ + " ++ " + contentType + " ++ " + fileLocalPath);\r
+ if (!mParents.empty()) {\r
+ Cursor c = managedQuery(Uri.withAppendedPath(\r
+ ProviderTableMeta.CONTENT_URI_FILE, mParents.peek()), null,\r
+ null, null, null);\r
+ c.moveToFirst();\r
+ cv.put(ProviderTableMeta.FILE_PARENT,\r
+ c.getString(c.getColumnIndex(ProviderTableMeta._ID)));\r
+ c.close();\r
+ }\r
+ getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);\r
}\r
\r
- public void run() {\r
- WebdavClient wdc = new WebdavClient(Uri.parse(mAccountManager.getUserData(mAccount,\r
- AccountAuthenticator.KEY_OC_URL)));\r
- wdc.setCredentials(mUsername, mPassword);\r
- wdc.allowUnsignedCertificates();\r
-\r
- // create last directory in path if nessesary\r
- if (mCreateDir) {\r
- wdc.createDirectory(mUploadPath);\r
- }\r
- \r
- for (int i = 0; i < mUploadStreams.size(); ++i) {\r
- Uri uri = (Uri) mUploadStreams.get(i);\r
- if (uri.getScheme().equals("content")) {\r
- final Cursor c = getContentResolver().query((Uri) mUploadStreams.get(i), null, null, null, null);\r
- \r
- if (!wdc.putFile(c.getString(c.getColumnIndex(Media.DATA)),\r
- mUploadPath+"/"+c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),\r
- c.getString(c.getColumnIndex(Media.MIME_TYPE)))) {\r
- mHandler.post(new Runnable() {\r
- public void run() {\r
- Uploader.this.onUploadComplete(false, "Error while uploading file: " + c.getString(c.getColumnIndex(Media.DISPLAY_NAME)));\r
- }\r
- });\r
- } else {\r
- mHandler.post(new Runnable() {\r
- public void run() {\r
- Uploader.this.PartialupdateUpload(c.getString(c.getColumnIndex(Media.DATA)),\r
- c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),\r
- mUploadPath+"/"+c.getString(c.getColumnIndex(Media.DISPLAY_NAME)),\r
- c.getString(c.getColumnIndex(Media.MIME_TYPE)),\r
- c.getString(c.getColumnIndex(Media.SIZE)));\r
- }\r
- });\r
- }\r
- } else if (uri.getScheme().equals("file")) {\r
- final File file = new File(Uri.decode(uri.toString()).replace(uri.getScheme()+"://", ""));\r
- FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
- String contentType = fileNameMap.getContentTypeFor(uri.toString());\r
- if (contentType == null) {\r
- contentType = "text/plain";\r
- }\r
- if (!wdc.putFile(file.getAbsolutePath(), mUploadPath+"/"+file.getName(), contentType)) {\r
- mHandler.post(new Runnable() {\r
- public void run() {\r
- Uploader.this.onUploadComplete(false, "Error while uploading file: " + file.getName());\r
- }\r
- });\r
- }\r
+ class BackgroundUploader implements Runnable {\r
+ private ArrayList<Parcelable> mUploadStreams;\r
+ private Handler mHandler;\r
+ private String mUploadPath;\r
+ private boolean mCreateDir;\r
+\r
+ public BackgroundUploader(String pathToUpload,\r
+ ArrayList<Parcelable> streamsToUpload, Handler handler) {\r
+ mUploadStreams = streamsToUpload;\r
+ mHandler = handler;\r
+ mUploadPath = pathToUpload.replace(" ", "%20");\r
+ mCreateDir = false;\r
+ }\r
+\r
+ public BackgroundUploader(String pathToUpload,\r
+ ArrayList<Parcelable> streamsToUpload, Handler handler,\r
+ boolean createDir) {\r
+ mUploadStreams = streamsToUpload;\r
+ mHandler = handler;\r
+ mUploadPath = pathToUpload.replace(" ", "%20");\r
+ mCreateDir = createDir;\r
}\r
- \r
- }\r
- mHandler.post(new Runnable() {\r
+\r
public void run() {\r
- Uploader.this.onUploadComplete(true, null);\r
+ WebdavClient wdc = new WebdavClient(Uri.parse(mAccountManager\r
+ .getUserData(mAccount, AccountAuthenticator.KEY_OC_URL)));\r
+ wdc.setCredentials(mUsername, mPassword);\r
+ wdc.allowUnsignedCertificates();\r
+\r
+ // create last directory in path if nessesary\r
+ if (mCreateDir) {\r
+ wdc.createDirectory(mUploadPath);\r
+ }\r
+\r
+ for (int i = 0; i < mUploadStreams.size(); ++i) {\r
+ Uri uri = (Uri) mUploadStreams.get(i);\r
+ if (uri.getScheme().equals("content")) {\r
+ final Cursor c = getContentResolver()\r
+ .query((Uri) mUploadStreams.get(i), null, null,\r
+ null, null);\r
+\r
+ if (!wdc.putFile(\r
+ c.getString(c.getColumnIndex(Media.DATA)),\r
+ mUploadPath\r
+ + "/"\r
+ + c.getString(c\r
+ .getColumnIndex(Media.DISPLAY_NAME)),\r
+ c.getString(c.getColumnIndex(Media.MIME_TYPE)))) {\r
+ mHandler.post(new Runnable() {\r
+ public void run() {\r
+ Uploader.this\r
+ .onUploadComplete(\r
+ false,\r
+ "Error while uploading file: "\r
+ + c.getString(c\r
+ .getColumnIndex(Media.DISPLAY_NAME)));\r
+ }\r
+ });\r
+ } else {\r
+ mHandler.post(new Runnable() {\r
+ public void run() {\r
+ Uploader.this.PartialupdateUpload(\r
+ c.getString(c\r
+ .getColumnIndex(Media.DATA)),\r
+ c.getString(c\r
+ .getColumnIndex(Media.DISPLAY_NAME)),\r
+ mUploadPath\r
+ + "/"\r
+ + c.getString(c\r
+ .getColumnIndex(Media.DISPLAY_NAME)),\r
+ c.getString(c\r
+ .getColumnIndex(Media.MIME_TYPE)),\r
+ c.getString(c\r
+ .getColumnIndex(Media.SIZE)));\r
+ }\r
+ });\r
+ }\r
+ } else if (uri.getScheme().equals("file")) {\r
+ final File file = new File(Uri.decode(uri.toString())\r
+ .replace(uri.getScheme() + "://", ""));\r
+ FileNameMap fileNameMap = URLConnection.getFileNameMap();\r
+ String contentType = fileNameMap.getContentTypeFor(uri\r
+ .toString());\r
+ if (contentType == null) {\r
+ contentType = "text/plain";\r
+ }\r
+ if (!wdc.putFile(file.getAbsolutePath(), mUploadPath + "/"\r
+ + file.getName(), contentType)) {\r
+ mHandler.post(new Runnable() {\r
+ public void run() {\r
+ Uploader.this.onUploadComplete(\r
+ false,\r
+ "Error while uploading file: "\r
+ + file.getName());\r
+ }\r
+ });\r
+ }\r
+ }\r
+\r
+ }\r
+ mHandler.post(new Runnable() {\r
+ public void run() {\r
+ Uploader.this.onUploadComplete(true, null);\r
+ }\r
+ });\r
}\r
- });\r
+\r
}\r
\r
- }\r
- \r
}\r
import android.util.Log;\r
\r
public class AccountAuthenticator extends AbstractAccountAuthenticator {\r
- /**\r
- * Is used by android system to assign accounts to authenticators. Should be\r
- * used by application and all extensions.\r
- */\r
- public static final String ACCOUNT_TYPE = "owncloud";\r
- public static final String AUTH_TOKEN_TYPE = "org.owncloud";\r
-\r
- public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";\r
- public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";\r
- public static final String KEY_LOGIN_OPTIONS = "loginOptions";\r
- public static final String KEY_ACCOUNT = "account";\r
- /**\r
- * Value under this key should handle path to webdav php script. Will be\r
- * removed and usage should be replaced by combining\r
- * {@link eu.alefzero.owncloud.authenticator.KEY_OC_BASE_URL} and\r
- * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}\r
- * \r
- * @deprecated\r
- */\r
- public static final String KEY_OC_URL = "oc_url";\r
- /**\r
- * Version should be 3 numbers separated by dot so it can be parsed by\r
- * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}\r
- */\r
- public static final String KEY_OC_VERSION = "oc_version";\r
- /**\r
- * Base url should point to owncloud installation without trailing / ie:\r
- * http://server/path or https://owncloud.server\r
- */\r
- public static final String KEY_OC_BASE_URL = "oc_base_url";\r
-\r
- private static final String TAG = "AccountAuthenticator";\r
- private Context mContext;\r
-\r
- public AccountAuthenticator(Context context) {\r
- super(context);\r
- mContext = context;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- */\r
- @Override\r
- public Bundle addAccount(AccountAuthenticatorResponse response,\r
- String accountType,\r
- String authTokenType,\r
- String[] requiredFeatures,\r
- Bundle options) throws NetworkErrorException {\r
- Log.i(TAG, "Adding account with type " + accountType + " and auth token " + authTokenType);\r
- try {\r
- validateAccountType(accountType);\r
- } catch (AuthenticatorException e) {\r
- Log.e(TAG, "Failed to validate account type "+ accountType +": " + e.getMessage());\r
- e.printStackTrace();\r
- return e.getFailureBundle();\r
+ /**\r
+ * Is used by android system to assign accounts to authenticators. Should be\r
+ * used by application and all extensions.\r
+ */\r
+ public static final String ACCOUNT_TYPE = "owncloud";\r
+ public static final String AUTH_TOKEN_TYPE = "org.owncloud";\r
+\r
+ public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";\r
+ public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";\r
+ public static final String KEY_LOGIN_OPTIONS = "loginOptions";\r
+ public static final String KEY_ACCOUNT = "account";\r
+ /**\r
+ * Value under this key should handle path to webdav php script. Will be\r
+ * removed and usage should be replaced by combining\r
+ * {@link eu.alefzero.owncloud.authenticator.KEY_OC_BASE_URL} and\r
+ * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}\r
+ * \r
+ * @deprecated\r
+ */\r
+ public static final String KEY_OC_URL = "oc_url";\r
+ /**\r
+ * Version should be 3 numbers separated by dot so it can be parsed by\r
+ * {@link eu.alefzero.owncloud.utils.OwnCloudVersion}\r
+ */\r
+ public static final String KEY_OC_VERSION = "oc_version";\r
+ /**\r
+ * Base url should point to owncloud installation without trailing / ie:\r
+ * http://server/path or https://owncloud.server\r
+ */\r
+ public static final String KEY_OC_BASE_URL = "oc_base_url";\r
+\r
+ private static final String TAG = "AccountAuthenticator";\r
+ private Context mContext;\r
+\r
+ public AccountAuthenticator(Context context) {\r
+ super(context);\r
+ mContext = context;\r
}\r
- final Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
- intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);\r
- intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);\r
- intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);\r
- intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
-\r
- setIntentFlags(intent);\r
- final Bundle bundle = new Bundle();\r
- bundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
- return bundle;\r
- }\r
-\r
- /**\r
- * {@inheritDoc}\r
- */\r
- @Override\r
- public Bundle confirmCredentials(AccountAuthenticatorResponse response,\r
- Account account, Bundle options) throws NetworkErrorException {\r
- try {\r
- validateAccountType(account.type);\r
- } catch (AuthenticatorException e) {\r
- Log.e(TAG, "Failed to validate account type "+ account.type +": " + e.getMessage());\r
- e.printStackTrace();\r
- return e.getFailureBundle();\r
+\r
+ /**\r
+ * {@inheritDoc}\r
+ */\r
+ @Override\r
+ public Bundle addAccount(AccountAuthenticatorResponse response,\r
+ String accountType, String authTokenType,\r
+ String[] requiredFeatures, Bundle options)\r
+ throws NetworkErrorException {\r
+ Log.i(TAG, "Adding account with type " + accountType\r
+ + " and auth token " + authTokenType);\r
+ try {\r
+ validateAccountType(accountType);\r
+ } catch (AuthenticatorException e) {\r
+ Log.e(TAG, "Failed to validate account type " + accountType + ": "\r
+ + e.getMessage());\r
+ e.printStackTrace();\r
+ return e.getFailureBundle();\r
+ }\r
+ final Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
+ intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,\r
+ response);\r
+ intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);\r
+ intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);\r
+ intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
+\r
+ setIntentFlags(intent);\r
+ final Bundle bundle = new Bundle();\r
+ bundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
+ return bundle;\r
+ }\r
+\r
+ /**\r
+ * {@inheritDoc}\r
+ */\r
+ @Override\r
+ public Bundle confirmCredentials(AccountAuthenticatorResponse response,\r
+ Account account, Bundle options) throws NetworkErrorException {\r
+ try {\r
+ validateAccountType(account.type);\r
+ } catch (AuthenticatorException e) {\r
+ Log.e(TAG, "Failed to validate account type " + account.type + ": "\r
+ + e.getMessage());\r
+ e.printStackTrace();\r
+ return e.getFailureBundle();\r
+ }\r
+ Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
+ intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,\r
+ response);\r
+ intent.putExtra(KEY_ACCOUNT, account);\r
+ intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
+\r
+ setIntentFlags(intent);\r
+\r
+ Bundle resultBundle = new Bundle();\r
+ resultBundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
+ return resultBundle;\r
+ }\r
+\r
+ @Override\r
+ public Bundle editProperties(AccountAuthenticatorResponse response,\r
+ String accountType) {\r
+ return null;\r
+ }\r
+\r
+ @Override\r
+ public Bundle getAuthToken(AccountAuthenticatorResponse response,\r
+ Account account, String authTokenType, Bundle options)\r
+ throws NetworkErrorException {\r
+ try {\r
+ validateAccountType(account.type);\r
+ validateAuthTokenType(authTokenType);\r
+ } catch (AuthenticatorException e) {\r
+ Log.e(TAG, "Failed to validate account type " + account.type + ": "\r
+ + e.getMessage());\r
+ e.printStackTrace();\r
+ return e.getFailureBundle();\r
+ }\r
+ final AccountManager am = AccountManager.get(mContext);\r
+ final String password = am.getPassword(account);\r
+ if (password != null) {\r
+ final Bundle result = new Bundle();\r
+ result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);\r
+ result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);\r
+ result.putString(AccountManager.KEY_AUTHTOKEN, password);\r
+ return result;\r
+ }\r
+\r
+ final Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
+ intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,\r
+ response);\r
+ intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);\r
+ intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
+ intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);\r
+\r
+ final Bundle bundle = new Bundle();\r
+ bundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
+ return bundle;\r
}\r
- Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
- intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);\r
- intent.putExtra(KEY_ACCOUNT, account);\r
- intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
-\r
- setIntentFlags(intent);\r
-\r
- Bundle resultBundle = new Bundle();\r
- resultBundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
- return resultBundle;\r
- }\r
-\r
- @Override\r
- public Bundle editProperties(AccountAuthenticatorResponse response,\r
- String accountType) {\r
- return null;\r
- }\r
-\r
- @Override\r
- public Bundle getAuthToken(AccountAuthenticatorResponse response,\r
- Account account,\r
- String authTokenType,\r
- Bundle options) throws NetworkErrorException {\r
- try {\r
- validateAccountType(account.type);\r
- validateAuthTokenType(authTokenType);\r
- } catch (AuthenticatorException e) {\r
- Log.e(TAG, "Failed to validate account type "+ account.type +": " + e.getMessage());\r
- e.printStackTrace();\r
- return e.getFailureBundle();\r
+\r
+ @Override\r
+ public String getAuthTokenLabel(String authTokenType) {\r
+ return null;\r
}\r
- final AccountManager am = AccountManager.get(mContext);\r
- final String password = am.getPassword(account);\r
- if (password != null) {\r
- final Bundle result = new Bundle();\r
- result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);\r
- result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);\r
- result.putString(AccountManager.KEY_AUTHTOKEN, password);\r
- return result;\r
+\r
+ @Override\r
+ public Bundle hasFeatures(AccountAuthenticatorResponse response,\r
+ Account account, String[] features) throws NetworkErrorException {\r
+ final Bundle result = new Bundle();\r
+ result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);\r
+ return result;\r
}\r
\r
- final Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
- intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);\r
- intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);\r
- intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
- intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);\r
-\r
- final Bundle bundle = new Bundle();\r
- bundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
- return bundle;\r
- }\r
-\r
- @Override\r
- public String getAuthTokenLabel(String authTokenType) {\r
- return null;\r
- }\r
-\r
- @Override\r
- public Bundle hasFeatures(AccountAuthenticatorResponse response,\r
- Account account,\r
- String[] features) throws NetworkErrorException {\r
- final Bundle result = new Bundle();\r
- result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);\r
- return result;\r
- }\r
-\r
- @Override\r
- public Bundle updateCredentials(AccountAuthenticatorResponse response,\r
- Account account,\r
- String authTokenType,\r
- Bundle options) throws NetworkErrorException {\r
- final Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
- intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);\r
- intent.putExtra(KEY_ACCOUNT, account);\r
- intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);\r
- intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
- setIntentFlags(intent);\r
-\r
- final Bundle bundle = new Bundle();\r
- bundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
- return bundle;\r
- }\r
-\r
- @Override\r
- public Bundle getAccountRemovalAllowed(AccountAuthenticatorResponse response,\r
- Account account) throws NetworkErrorException {\r
- return super.getAccountRemovalAllowed(response, account);\r
- }\r
-\r
- private void setIntentFlags(Intent intent) {\r
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
- intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);\r
- intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);\r
- intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);\r
- intent.addFlags(Intent.FLAG_FROM_BACKGROUND);\r
- }\r
-\r
- private void validateAccountType(String type)\r
- throws UnsupportedAccountTypeException {\r
- if (!type.equals(ACCOUNT_TYPE)) {\r
- throw new UnsupportedAccountTypeException();\r
+ @Override\r
+ public Bundle updateCredentials(AccountAuthenticatorResponse response,\r
+ Account account, String authTokenType, Bundle options)\r
+ throws NetworkErrorException {\r
+ final Intent intent = new Intent(mContext, AuthenticatorActivity.class);\r
+ intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,\r
+ response);\r
+ intent.putExtra(KEY_ACCOUNT, account);\r
+ intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);\r
+ intent.putExtra(KEY_LOGIN_OPTIONS, options);\r
+ setIntentFlags(intent);\r
+\r
+ final Bundle bundle = new Bundle();\r
+ bundle.putParcelable(AccountManager.KEY_INTENT, intent);\r
+ return bundle;\r
}\r
- }\r
\r
- private void validateAuthTokenType(String authTokenType)\r
- throws UnsupportedAuthTokenTypeException {\r
- if (!authTokenType.equals(AUTH_TOKEN_TYPE)) {\r
- throw new UnsupportedAuthTokenTypeException();\r
+ @Override\r
+ public Bundle getAccountRemovalAllowed(\r
+ AccountAuthenticatorResponse response, Account account)\r
+ throws NetworkErrorException {\r
+ return super.getAccountRemovalAllowed(response, account);\r
}\r
- }\r
\r
- public static class AuthenticatorException extends Exception {\r
- private static final long serialVersionUID = 1L;\r
- private Bundle mFailureBundle;\r
+ private void setIntentFlags(Intent intent) {\r
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
+ intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);\r
+ intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);\r
+ intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);\r
+ intent.addFlags(Intent.FLAG_FROM_BACKGROUND);\r
+ }\r
\r
- public AuthenticatorException(int code, String errorMsg) {\r
- mFailureBundle = new Bundle();\r
- mFailureBundle.putInt(AccountManager.KEY_ERROR_CODE, code);\r
- mFailureBundle.putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg);\r
+ private void validateAccountType(String type)\r
+ throws UnsupportedAccountTypeException {\r
+ if (!type.equals(ACCOUNT_TYPE)) {\r
+ throw new UnsupportedAccountTypeException();\r
+ }\r
}\r
\r
- public Bundle getFailureBundle() {\r
- return mFailureBundle;\r
+ private void validateAuthTokenType(String authTokenType)\r
+ throws UnsupportedAuthTokenTypeException {\r
+ if (!authTokenType.equals(AUTH_TOKEN_TYPE)) {\r
+ throw new UnsupportedAuthTokenTypeException();\r
+ }\r
}\r
- }\r
\r
- public static class UnsupportedAccountTypeException\r
- extends\r
- AuthenticatorException {\r
- private static final long serialVersionUID = 1L;\r
+ public static class AuthenticatorException extends Exception {\r
+ private static final long serialVersionUID = 1L;\r
+ private Bundle mFailureBundle;\r
+\r
+ public AuthenticatorException(int code, String errorMsg) {\r
+ mFailureBundle = new Bundle();\r
+ mFailureBundle.putInt(AccountManager.KEY_ERROR_CODE, code);\r
+ mFailureBundle\r
+ .putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg);\r
+ }\r
\r
- public UnsupportedAccountTypeException() {\r
- super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,\r
- "Unsupported account type");\r
+ public Bundle getFailureBundle() {\r
+ return mFailureBundle;\r
+ }\r
}\r
- }\r
\r
- public static class UnsupportedAuthTokenTypeException\r
- extends\r
- AuthenticatorException {\r
- private static final long serialVersionUID = 1L;\r
+ public static class UnsupportedAccountTypeException extends\r
+ AuthenticatorException {\r
+ private static final long serialVersionUID = 1L;\r
\r
- public UnsupportedAuthTokenTypeException() {\r
- super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,\r
- "Unsupported auth token type");\r
+ public UnsupportedAccountTypeException() {\r
+ super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,\r
+ "Unsupported account type");\r
+ }\r
}\r
- }\r
\r
- public static class UnsupportedFeaturesException\r
- extends\r
- AuthenticatorException {\r
- public static final long serialVersionUID = 1L;\r
+ public static class UnsupportedAuthTokenTypeException extends\r
+ AuthenticatorException {\r
+ private static final long serialVersionUID = 1L;\r
\r
- public UnsupportedFeaturesException() {\r
- super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,\r
- "Unsupported features");\r
+ public UnsupportedAuthTokenTypeException() {\r
+ super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,\r
+ "Unsupported auth token type");\r
+ }\r
}\r
- }\r
\r
- public static class AccessDeniedException extends AuthenticatorException {\r
- public AccessDeniedException(int code, String errorMsg) {\r
- super(AccountManager.ERROR_CODE_INVALID_RESPONSE, "Access Denied");\r
+ public static class UnsupportedFeaturesException extends\r
+ AuthenticatorException {\r
+ public static final long serialVersionUID = 1L;\r
+\r
+ public UnsupportedFeaturesException() {\r
+ super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,\r
+ "Unsupported features");\r
+ }\r
}\r
\r
- private static final long serialVersionUID = 1L;\r
+ public static class AccessDeniedException extends AuthenticatorException {\r
+ public AccessDeniedException(int code, String errorMsg) {\r
+ super(AccountManager.ERROR_CODE_INVALID_RESPONSE, "Access Denied");\r
+ }\r
+\r
+ private static final long serialVersionUID = 1L;\r
\r
- }\r
+ }\r
}\r
public class AccountAuthenticatorService extends Service {
- private AccountAuthenticator mAuthenticator;
- static final public String ACCOUNT_TYPE = "owncloud";
-
- @Override
- public void onCreate() {
- super.onCreate();
- mAuthenticator = new AccountAuthenticator(this);
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return mAuthenticator.getIBinder();
- }
+ private AccountAuthenticator mAuthenticator;
+ static final public String ACCOUNT_TYPE = "owncloud";
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mAuthenticator = new AccountAuthenticator(this);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mAuthenticator.getIBinder();
+ }
}
public class AuthenticationRunnable implements Runnable {
- private OnAuthenticationResultListener mListener;
- private Handler mHandler;
- private URL mUrl;
- private String mUsername;
- private String mPassword;
+ private OnAuthenticationResultListener mListener;
+ private Handler mHandler;
+ private URL mUrl;
+ private String mUsername;
+ private String mPassword;
- public AuthenticationRunnable(URL url, String username, String password) {
- mListener = null;
- mUrl = url;
- mUsername = username;
- mPassword = password;
- }
-
- public void setOnAuthenticationResultListener(OnAuthenticationResultListener listener, Handler handler) {
- mListener = listener;
- mHandler = handler;
- }
-
- @Override
- public void run() {
- Uri uri;
- uri = Uri.parse(mUrl.toString());
- WebdavClient client = new WebdavClient(uri);
- client.setCredentials(mUsername, mPassword);
- int login_result = client.tryToLogin();
- switch (login_result) {
- case HttpStatus.SC_OK:
- postResult(true, uri.toString());
- break;
- case HttpStatus.SC_UNAUTHORIZED:
- postResult(false, "Invalid login or/and password");
- break;
- case HttpStatus.SC_NOT_FOUND:
- postResult(false, "Wrong path given");
- break;
- default:
- postResult(false, "Internal server error, code: " + login_result);
+ public AuthenticationRunnable(URL url, String username, String password) {
+ mListener = null;
+ mUrl = url;
+ mUsername = username;
+ mPassword = password;
}
- }
- private void postResult(final boolean success, final String message) {
- if (mHandler != null && mListener != null) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mListener.onAuthenticationResult(success, message);
+ public void setOnAuthenticationResultListener(
+ OnAuthenticationResultListener listener, Handler handler) {
+ mListener = listener;
+ mHandler = handler;
+ }
+
+ @Override
+ public void run() {
+ Uri uri;
+ uri = Uri.parse(mUrl.toString());
+ WebdavClient client = new WebdavClient(uri);
+ client.setCredentials(mUsername, mPassword);
+ int login_result = client.tryToLogin();
+ switch (login_result) {
+ case HttpStatus.SC_OK:
+ postResult(true, uri.toString());
+ break;
+ case HttpStatus.SC_UNAUTHORIZED:
+ postResult(false, "Invalid login or/and password");
+ break;
+ case HttpStatus.SC_NOT_FOUND:
+ postResult(false, "Wrong path given");
+ break;
+ default:
+ postResult(false, "Internal server error, code: " + login_result);
+ }
+ }
+
+ private void postResult(final boolean success, final String message) {
+ if (mHandler != null && mListener != null) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mListener.onAuthenticationResult(success, message);
+ }
+ });
}
- });
}
- }
}
import android.util.Log;
public class ConnectionCheckerRunnable implements Runnable {
- private static final String TAG = "ConnectionCheckerRunnable";
- private OnConnectCheckListener mListener;
- private String mUrl;
- private Handler mHandler;
- private ResultType mLatestResult;
- private Context mContext;
- private OwnCloudVersion mOCVersion;
-
- public void setListener(OnConnectCheckListener listener, Handler handler) {
- mListener = listener;
- mHandler = handler;
- }
-
- public ConnectionCheckerRunnable(String url, Context context) {
- mListener = null;
- mHandler = null;
- mUrl = url;
- mContext = context;
- mOCVersion = null;
- }
-
- @Override
- public void run() {
-
- if (!isOnline()) {
- postResult(ResultType.NO_NETWORK_CONNECTION);
- return;
+ private static final String TAG = "ConnectionCheckerRunnable";
+ private OnConnectCheckListener mListener;
+ private String mUrl;
+ private Handler mHandler;
+ private ResultType mLatestResult;
+ private Context mContext;
+ private OwnCloudVersion mOCVersion;
+
+ public void setListener(OnConnectCheckListener listener, Handler handler) {
+ mListener = listener;
+ mHandler = handler;
+ }
+
+ public ConnectionCheckerRunnable(String url, Context context) {
+ mListener = null;
+ mHandler = null;
+ mUrl = url;
+ mContext = context;
+ mOCVersion = null;
+ }
+
+ @Override
+ public void run() {
+
+ if (!isOnline()) {
+ postResult(ResultType.NO_NETWORK_CONNECTION);
+ return;
+ }
+ if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) {
+ mLatestResult = ResultType.OK;
+ tryConnection(Uri.parse(mUrl + AccountUtils.STATUS_PATH));
+ postResult(mLatestResult);
+ } else {
+ Uri uri = Uri.parse("https://" + mUrl + AccountUtils.STATUS_PATH);
+ if (tryConnection(uri)) {
+ postResult(ResultType.OK);
+ return;
+ }
+ Log.d(TAG,
+ "establishing secure connection failed, trying non secure connection");
+ uri = Uri.parse("http://" + mUrl + AccountUtils.STATUS_PATH);
+
+ if (tryConnection(uri)) {
+ postResult(ResultType.OK_NO_SSL);
+ return;
+ }
+ postResult(mLatestResult);
+ }
}
- if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) {
- mLatestResult = ResultType.OK;
- tryConnection(Uri.parse(mUrl + AccountUtils.STATUS_PATH));
- postResult(mLatestResult);
- } else {
- Uri uri = Uri.parse("https://" + mUrl + AccountUtils.STATUS_PATH);
- if (tryConnection(uri)) {
- postResult(ResultType.OK);
- return;
- }
- Log.d(TAG, "establishing secure connection failed, trying non secure connection");
- uri = Uri.parse("http://" + mUrl + AccountUtils.STATUS_PATH);
-
- if (tryConnection(uri)) {
- postResult(ResultType.OK_NO_SSL);
- return;
- }
- postResult(mLatestResult);
+
+ public OwnCloudVersion getDiscoveredVersion() {
+ return mOCVersion;
}
- }
-
- public OwnCloudVersion getDiscoveredVersion() {
- return mOCVersion;
- }
-
- private boolean tryConnection(Uri uri) {
- WebdavClient wc = new WebdavClient(uri);
- wc.allowUnsignedCertificates();
- GetMethod get = new GetMethod(uri.toString());
- boolean retval = false;
- try {
- int status = wc.executeMethod(get);
- switch (status) {
- case HttpStatus.SC_OK: {
- String response = get.getResponseBodyAsString();
- JSONObject json = new JSONObject(response);
- if (!json.getBoolean("installed")) {
- mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
- break;
- }
- mOCVersion = new OwnCloudVersion(json.getString("version"));
- if (!mOCVersion.isVersionValid())
- break;
- retval = true;
- break;
+
+ private boolean tryConnection(Uri uri) {
+ WebdavClient wc = new WebdavClient(uri);
+ wc.allowUnsignedCertificates();
+ GetMethod get = new GetMethod(uri.toString());
+ boolean retval = false;
+ try {
+ int status = wc.executeMethod(get);
+ switch (status) {
+ case HttpStatus.SC_OK: {
+ String response = get.getResponseBodyAsString();
+ JSONObject json = new JSONObject(response);
+ if (!json.getBoolean("installed")) {
+ mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
+ break;
+ }
+ mOCVersion = new OwnCloudVersion(json.getString("version"));
+ if (!mOCVersion.isVersionValid())
+ break;
+ retval = true;
+ break;
+ }
+ case HttpStatus.SC_NOT_FOUND:
+ mLatestResult = ResultType.FILE_NOT_FOUND;
+ break;
+ case HttpStatus.SC_INTERNAL_SERVER_ERROR:
+ mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
+ break;
+ default:
+ mLatestResult = ResultType.UNKNOWN_ERROR;
+ Log.e(TAG, "Not handled status received from server: " + status);
+ }
+
+ } catch (Exception e) {
+ if (e instanceof UnknownHostException
+ || e instanceof ConnectException) {
+ mLatestResult = ResultType.HOST_NOT_AVAILABLE;
+ } else if (e instanceof JSONException) {
+ mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
+ } else if (e instanceof SSLHandshakeException) {
+ mLatestResult = ResultType.SSL_INIT_ERROR;
+ } else {
+ mLatestResult = ResultType.UNKNOWN_ERROR;
+ }
+ e.printStackTrace();
}
- case HttpStatus.SC_NOT_FOUND:
- mLatestResult = ResultType.FILE_NOT_FOUND;
- break;
- case HttpStatus.SC_INTERNAL_SERVER_ERROR:
- mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
- break;
- default:
- mLatestResult = ResultType.UNKNOWN_ERROR;
- Log.e(TAG,"Not handled status received from server: " + status);
- }
-
- } catch (Exception e) {
- if (e instanceof UnknownHostException || e instanceof ConnectException) {
- mLatestResult = ResultType.HOST_NOT_AVAILABLE;
- } else if (e instanceof JSONException) {
- mLatestResult = ResultType.INSTANCE_NOT_CONFIGURED;
- } else if (e instanceof SSLHandshakeException) {
- mLatestResult = ResultType.SSL_INIT_ERROR;
- } else {
- mLatestResult = ResultType.UNKNOWN_ERROR;
- }
- e.printStackTrace();
+
+ return retval;
+ }
+
+ private boolean isOnline() {
+ ConnectivityManager cm = (ConnectivityManager) mContext
+ .getSystemService(Context.CONNECTIVITY_SERVICE);
+ return cm != null && cm.getActiveNetworkInfo() != null
+ && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
- return retval;
- }
-
- private boolean isOnline() {
- ConnectivityManager cm =
- (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- return cm != null
- && cm.getActiveNetworkInfo() != null
- && cm.getActiveNetworkInfo().isConnectedOrConnecting();
- }
-
- private void postResult(final ResultType result) {
- if (mHandler != null && mListener != null) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mListener.onConnectionCheckResult(result);
+ private void postResult(final ResultType result) {
+ if (mHandler != null && mListener != null) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mListener.onConnectionCheckResult(result);
+ }
+ });
}
- });
}
- }
-
+
}
/**
* <p>
- * EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s
- * that accept self-signed certificates.
+ * EasySSLProtocolSocketFactory can be used to creats SSL {@link Socket}s that
+ * accept self-signed certificates.
* </p>
* <p>
- * This socket factory SHOULD NOT be used for productive systems
- * due to security reasons, unless it is a concious decision and
- * you are perfectly aware of security implications of accepting
- * self-signed certificates
+ * This socket factory SHOULD NOT be used for productive systems due to security
+ * reasons, unless it is a concious decision and you are perfectly aware of
+ * security implications of accepting self-signed certificates
* </p>
- *
+ *
* <p>
* Example of using custom protocol socket factory for a specific host:
- * <pre>
- * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- *
- * URI uri = new URI("https://localhost/", true);
- * // use relative url only
- * GetMethod httpget = new GetMethod(uri.getPathQuery());
- * HostConfiguration hc = new HostConfiguration();
- * hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
- * HttpClient client = new HttpClient();
- * client.executeMethod(hc, httpget);
- * </pre>
+ *
+ * <pre>
+ * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(),
+ * 443);
+ *
+ * URI uri = new URI("https://localhost/", true);
+ * // use relative url only
+ * GetMethod httpget = new GetMethod(uri.getPathQuery());
+ * HostConfiguration hc = new HostConfiguration();
+ * hc.setHost(uri.getHost(), uri.getPort(), easyhttps);
+ * HttpClient client = new HttpClient();
+ * client.executeMethod(hc, httpget);
+ * </pre>
+ *
* </p>
* <p>
- * Example of using custom protocol socket factory per default instead of the standard one:
- * <pre>
- * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
- * Protocol.registerProtocol("https", easyhttps);
- *
- * HttpClient client = new HttpClient();
- * GetMethod httpget = new GetMethod("https://localhost/");
- * client.executeMethod(httpget);
- * </pre>
+ * Example of using custom protocol socket factory per default instead of the
+ * standard one:
+ *
+ * <pre>
+ * Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(),
+ * 443);
+ * Protocol.registerProtocol("https", easyhttps);
+ *
+ * HttpClient client = new HttpClient();
+ * GetMethod httpget = new GetMethod("https://localhost/");
+ * client.executeMethod(httpget);
+ * </pre>
+ *
* </p>
*
* @author <a href="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
*
- * <p>
- * DISCLAIMER: HttpClient developers DO NOT actively support this component.
- * The component is provided as a reference material, which may be inappropriate
- * for use without additional customization.
- * </p>
+ * <p>
+ * DISCLAIMER: HttpClient developers DO NOT actively support this
+ * component. The component is provided as a reference material, which
+ * may be inappropriate for use without additional customization.
+ * </p>
*/
public class EasySSLSocketFactory implements ProtocolSocketFactory {
private static SSLContext createEasySSLContext() {
try {
SSLContext context = SSLContext.getInstance("TLS");
- context.init(
- null,
- new TrustManager[] {new EasyX509TrustManager(null)},
- null);
+ context.init(null, new TrustManager[] { new EasyX509TrustManager(
+ null) }, null);
return context;
} catch (Exception er) {
- Log.e(TAG, er.getMessage()+"");
+ Log.e(TAG, er.getMessage() + "");
throw new HttpClientError(er.toString());
}
}
/**
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
*/
- public Socket createSocket(
- String host,
- int port,
- InetAddress clientHost,
- int clientPort)
- throws IOException, UnknownHostException {
-
- return getSSLContext().getSocketFactory().createSocket(
- host,
- port,
- clientHost,
- clientPort
- );
+ public Socket createSocket(String host, int port, InetAddress clientHost,
+ int clientPort) throws IOException, UnknownHostException {
+
+ return getSSLContext().getSocketFactory().createSocket(host, port,
+ clientHost, clientPort);
}
/**
- * Attempts to get a new socket connection to the given host within the given time limit.
+ * Attempts to get a new socket connection to the given host within the
+ * given time limit.
* <p>
- * To circumvent the limitations of older JREs that do not support connect timeout a
- * controller thread is executed. The controller thread attempts to create a new socket
- * within the given limit of time. If socket constructor does not return until the
- * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
+ * To circumvent the limitations of older JREs that do not support connect
+ * timeout a controller thread is executed. The controller thread attempts
+ * to create a new socket within the given limit of time. If socket
+ * constructor does not return until the timeout expires, the controller
+ * terminates and throws an {@link ConnectTimeoutException}
* </p>
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param clientHost the local host name/IP to bind the socket to
- * @param clientPort the port on the local machine
- * @param params {@link HttpConnectionParams Http connection parameters}
+ *
+ * @param host
+ * the host name/IP
+ * @param port
+ * the port on the host
+ * @param clientHost
+ * the local host name/IP to bind the socket to
+ * @param clientPort
+ * the port on the local machine
+ * @param params
+ * {@link HttpConnectionParams Http connection parameters}
*
* @return Socket a new socket
*
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
+ * @throws IOException
+ * if an I/O error occurs while creating the socket
+ * @throws UnknownHostException
+ * if the IP address of the host cannot be determined
*/
- public Socket createSocket(
- final String host,
- final int port,
- final InetAddress localAddress,
- final int localPort,
- final HttpConnectionParams params
- ) throws IOException, UnknownHostException, ConnectTimeoutException {
+ public Socket createSocket(final String host, final int port,
+ final InetAddress localAddress, final int localPort,
+ final HttpConnectionParams params) throws IOException,
+ UnknownHostException, ConnectTimeoutException {
if (params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
SocketFactory socketfactory = getSSLContext().getSocketFactory();
if (timeout == 0) {
- return socketfactory.createSocket(host, port, localAddress, localPort);
+ return socketfactory.createSocket(host, port, localAddress,
+ localPort);
} else {
Socket socket = socketfactory.createSocket();
- SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
+ SocketAddress localaddr = new InetSocketAddress(localAddress,
+ localPort);
SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.bind(localaddr);
socket.connect(remoteaddr, timeout);
/**
* @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
*/
- public Socket createSocket(String host, int port)
- throws IOException, UnknownHostException {
- return getSSLContext().getSocketFactory().createSocket(
- host,
- port
- );
+ public Socket createSocket(String host, int port) throws IOException,
+ UnknownHostException {
+ return getSSLContext().getSocketFactory().createSocket(host, port);
}
/**
* @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
*/
- public Socket createSocket(
- Socket socket,
- String host,
- int port,
- boolean autoClose)
- throws IOException, UnknownHostException {
- return getSSLContext().getSocketFactory().createSocket(
- socket,
- host,
- port,
- autoClose
- );
+ public Socket createSocket(Socket socket, String host, int port,
+ boolean autoClose) throws IOException, UnknownHostException {
+ return getSSLContext().getSocketFactory().createSocket(socket, host,
+ port, autoClose);
}
public boolean equals(Object obj) {
- return ((obj != null) && obj.getClass().equals(EasySSLSocketFactory.class));
+ return ((obj != null) && obj.getClass().equals(
+ EasySSLSocketFactory.class));
}
public int hashCode() {
/**
* @author olamy
- * @version $Id: EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse $
+ * @version $Id: EasyX509TrustManager.java 765355 2009-04-15 20:59:07Z evenisse
+ * $
* @since 1.2.3
*/
-public class EasyX509TrustManager
- implements X509TrustManager
-{
+public class EasyX509TrustManager implements X509TrustManager {
private X509TrustManager standardTrustManager = null;
/**
* Constructor for EasyX509TrustManager.
*/
- public EasyX509TrustManager( KeyStore keystore )
- throws NoSuchAlgorithmException, KeyStoreException
- {
+ public EasyX509TrustManager(KeyStore keystore)
+ throws NoSuchAlgorithmException, KeyStoreException {
super();
- TrustManagerFactory factory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() );
- factory.init( keystore );
+ TrustManagerFactory factory = TrustManagerFactory
+ .getInstance(TrustManagerFactory.getDefaultAlgorithm());
+ factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
- if ( trustmanagers.length == 0 )
- {
- throw new NoSuchAlgorithmException( "no trust manager found" );
+ if (trustmanagers.length == 0) {
+ throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
- * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
+ * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
+ * String authType)
*/
- public void checkClientTrusted( X509Certificate[] certificates, String authType )
- throws CertificateException
- {
- standardTrustManager.checkClientTrusted( certificates, authType );
+ public void checkClientTrusted(X509Certificate[] certificates,
+ String authType) throws CertificateException {
+ standardTrustManager.checkClientTrusted(certificates, authType);
}
/**
- * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
+ * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
+ * String authType)
*/
- public void checkServerTrusted( X509Certificate[] certificates, String authType )
- throws CertificateException
- {
- if ( ( certificates != null ) && ( certificates.length == 1 ) )
- {
+ public void checkServerTrusted(X509Certificate[] certificates,
+ String authType) throws CertificateException {
+ if ((certificates != null) && (certificates.length == 1)) {
certificates[0].checkValidity();
- }
- else
- {
- //standardTrustManager.checkServerTrusted( certificates, authType );
+ } else {
+ // standardTrustManager.checkServerTrusted( certificates, authType
+ // );
}
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
- public X509Certificate[] getAcceptedIssuers()
- {
+ public X509Certificate[] getAcceptedIssuers() {
return this.standardTrustManager.getAcceptedIssuers();
}
package eu.alefzero.owncloud.authenticator;
public interface OnAuthenticationResultListener {
-
- public void onAuthenticationResult(boolean success, String message);
+
+ public void onAuthenticationResult(boolean success, String message);
}
package eu.alefzero.owncloud.authenticator;
public interface OnConnectCheckListener {
-
- enum ResultType {
- OK,
- OK_NO_SSL,
- SSL_INIT_ERROR,
- HOST_NOT_AVAILABLE,
- TIMEOUT,
- NO_NETWORK_CONNECTION,
- INORRECT_ADDRESS,
- INSTANCE_NOT_CONFIGURED,
- FILE_NOT_FOUND,
- UNKNOWN_ERROR
- }
-
- public void onConnectionCheckResult(ResultType type);
-
+
+ enum ResultType {
+ OK, OK_NO_SSL, SSL_INIT_ERROR, HOST_NOT_AVAILABLE, TIMEOUT, NO_NETWORK_CONNECTION, INORRECT_ADDRESS, INSTANCE_NOT_CONFIGURED, FILE_NOT_FOUND, UNKNOWN_ERROR
+ }
+
+ public void onConnectionCheckResult(ResultType type);
+
}
public interface DataStorageManager {
- public OCFile getFileByPath(String path);
-
- public OCFile getFileById(long id);
-
- public boolean fileExists(String path);
-
- public boolean fileExists(long id);
-
- public boolean saveFile(OCFile file);
-
- public Vector<OCFile> getDirectoryContent(OCFile f);
+ public OCFile getFileByPath(String path);
+
+ public OCFile getFileById(long id);
+
+ public boolean fileExists(String path);
+
+ public boolean fileExists(long id);
+
+ public boolean saveFile(OCFile file);
+
+ public Vector<OCFile> getDirectoryContent(OCFile f);
}
public class FileDataStorageManager implements DataStorageManager {
- private ContentResolver mContentResolver;
- private ContentProviderClient mContentProvider;
- private Account mAccount;
-
- private static String TAG = "FileDataStorageManager";
-
- public FileDataStorageManager(Account account, ContentResolver cr) {
- mContentProvider = null;
- mContentResolver = cr;
- mAccount = account;
- }
-
- public FileDataStorageManager(Account account, ContentProviderClient cp) {
- mContentProvider = cp;
- mContentResolver = null;
- mAccount = account;
- }
-
- @Override
- public OCFile getFileByPath(String path) {
- Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
- OCFile file = null;
- if (c.moveToFirst()) {
- file = createFileInstance(c);
- c.close();
+ private ContentResolver mContentResolver;
+ private ContentProviderClient mContentProvider;
+ private Account mAccount;
+
+ private static String TAG = "FileDataStorageManager";
+
+ public FileDataStorageManager(Account account, ContentResolver cr) {
+ mContentProvider = null;
+ mContentResolver = cr;
+ mAccount = account;
}
- return file;
- }
-
- @Override
- public OCFile getFileById(long id) {
- Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
- OCFile file = null;
- if (c.moveToFirst()) {
- file = createFileInstance(c);
- c.close();
+
+ public FileDataStorageManager(Account account, ContentProviderClient cp) {
+ mContentProvider = cp;
+ mContentResolver = null;
+ mAccount = account;
}
- return file;
- }
-
- @Override
- public boolean fileExists(long id) {
- return fileExists(ProviderTableMeta._ID, String.valueOf(id));
- }
-
- @Override
- public boolean fileExists(String path) {
- return fileExists(ProviderTableMeta.FILE_PATH, path);
- }
-
- @Override
- public boolean saveFile(OCFile file) {
- boolean overriden = false;
- ContentValues cv = new ContentValues();
- cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
- cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
- cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
- cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
- cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
- if (file.getParentId() != 0)
- cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
- cv.put(ProviderTableMeta.FILE_PATH, file.getPath());
- cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
- cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
-
- if (fileExists(file.getPath())) {
- OCFile tmpfile = getFileByPath(file.getPath());
- file.setStoragePath(tmpfile.getStoragePath());
- cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
- file.setFileId(tmpfile.getFileId());
-
- overriden = true;
- if (getContentResolver() != null) {
- getContentResolver().update(ProviderTableMeta.CONTENT_URI,
- cv,
- ProviderTableMeta._ID + "=?",
- new String[] {String.valueOf(file.getFileId())});
- } else {
- try {
- getContentProvider().update(ProviderTableMeta.CONTENT_URI,
- cv,
- ProviderTableMeta._ID + "=?",
- new String[] {String.valueOf(file.getFileId())});
- } catch (RemoteException e) {
- Log.e(TAG, "Fail to insert insert file to database " + e.getMessage());
+
+ @Override
+ public OCFile getFileByPath(String path) {
+ Cursor c = getCursorForValue(ProviderTableMeta.FILE_PATH, path);
+ OCFile file = null;
+ if (c.moveToFirst()) {
+ file = createFileInstance(c);
+ c.close();
}
- }
- } else {
- Uri result_uri = null;
- if (getContentResolver() != null) {
- result_uri = getContentResolver().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
- } else {
- try {
- result_uri = getContentProvider().insert(ProviderTableMeta.CONTENT_URI_FILE, cv);
- } catch (RemoteException e) {
- Log.e(TAG, "Fail to insert insert file to database " + e.getMessage());
+ return file;
+ }
+
+ @Override
+ public OCFile getFileById(long id) {
+ Cursor c = getCursorForValue(ProviderTableMeta._ID, String.valueOf(id));
+ OCFile file = null;
+ if (c.moveToFirst()) {
+ file = createFileInstance(c);
+ c.close();
}
- }
- if (result_uri != null) {
- long new_id = Long.parseLong(result_uri.getPathSegments().get(1));
- file.setFileId(new_id);
- }
+ return file;
+ }
+
+ @Override
+ public boolean fileExists(long id) {
+ return fileExists(ProviderTableMeta._ID, String.valueOf(id));
+ }
+
+ @Override
+ public boolean fileExists(String path) {
+ return fileExists(ProviderTableMeta.FILE_PATH, path);
}
- if (file.isDirectory() && file.needsUpdatingWhileSaving())
- for (OCFile f : getDirectoryContent(file))
- saveFile(f);
-
- return overriden;
- }
-
- public void setAccount(Account account) {
- mAccount = account;
- }
-
- public Account getAccount() {
- return mAccount;
- }
-
- public void setContentResolver(ContentResolver cr) {
- mContentResolver = cr;
- }
-
- public ContentResolver getContentResolver() {
- return mContentResolver;
- }
-
- public void setContentProvider(ContentProviderClient cp) {
- mContentProvider = cp;
- }
-
- public ContentProviderClient getContentProvider() {
- return mContentProvider;
- }
-
- public Vector<OCFile> getDirectoryContent(OCFile f) {
- if (f != null && f.isDirectory() && f.getFileId() != -1) {
- Vector<OCFile> ret = new Vector<OCFile>();
-
- Uri req_uri = Uri.withAppendedPath(
- ProviderTableMeta.CONTENT_URI_DIR, String.valueOf(f.getFileId()));
- Cursor c = null;
-
- if (getContentProvider() != null) {
- try {
- c = getContentProvider().query(req_uri,
- null,
- ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[]{mAccount.name},
- null);
- } catch (RemoteException e) {
- Log.e(TAG, e.getMessage());
- return ret;
+ @Override
+ public boolean saveFile(OCFile file) {
+ boolean overriden = false;
+ ContentValues cv = new ContentValues();
+ cv.put(ProviderTableMeta.FILE_MODIFIED, file.getModificationTimestamp());
+ cv.put(ProviderTableMeta.FILE_CREATION, file.getCreationTimestamp());
+ cv.put(ProviderTableMeta.FILE_CONTENT_LENGTH, file.getFileLength());
+ cv.put(ProviderTableMeta.FILE_CONTENT_TYPE, file.getMimetype());
+ cv.put(ProviderTableMeta.FILE_NAME, file.getFileName());
+ if (file.getParentId() != 0)
+ cv.put(ProviderTableMeta.FILE_PARENT, file.getParentId());
+ cv.put(ProviderTableMeta.FILE_PATH, file.getPath());
+ cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
+ cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, mAccount.name);
+
+ if (fileExists(file.getPath())) {
+ OCFile tmpfile = getFileByPath(file.getPath());
+ file.setStoragePath(tmpfile.getStoragePath());
+ cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getStoragePath());
+ file.setFileId(tmpfile.getFileId());
+
+ overriden = true;
+ if (getContentResolver() != null) {
+ getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv,
+ ProviderTableMeta._ID + "=?",
+ new String[] { String.valueOf(file.getFileId()) });
+ } else {
+ try {
+ getContentProvider().update(ProviderTableMeta.CONTENT_URI,
+ cv, ProviderTableMeta._ID + "=?",
+ new String[] { String.valueOf(file.getFileId()) });
+ } catch (RemoteException e) {
+ Log.e(TAG,
+ "Fail to insert insert file to database "
+ + e.getMessage());
+ }
+ }
+ } else {
+ Uri result_uri = null;
+ if (getContentResolver() != null) {
+ result_uri = getContentResolver().insert(
+ ProviderTableMeta.CONTENT_URI_FILE, cv);
+ } else {
+ try {
+ result_uri = getContentProvider().insert(
+ ProviderTableMeta.CONTENT_URI_FILE, cv);
+ } catch (RemoteException e) {
+ Log.e(TAG,
+ "Fail to insert insert file to database "
+ + e.getMessage());
+ }
+ }
+ if (result_uri != null) {
+ long new_id = Long.parseLong(result_uri.getPathSegments()
+ .get(1));
+ file.setFileId(new_id);
+ }
}
- } else {
- c = getContentResolver().query(req_uri,
- null,
- ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[]{mAccount.name},
- null);
- }
-
- if (c.moveToFirst()) {
- do {
- OCFile child = createFileInstance(c);
- ret.add(child);
- } while (c.moveToNext());
- }
-
- c.close();
- return ret;
+
+ if (file.isDirectory() && file.needsUpdatingWhileSaving())
+ for (OCFile f : getDirectoryContent(file))
+ saveFile(f);
+
+ return overriden;
+ }
+
+ public void setAccount(Account account) {
+ mAccount = account;
}
- return null;
- }
-
-
- private boolean fileExists(String cmp_key, String value) {
- Cursor c;
- if (getContentResolver() != null) {
- c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
- null,
- cmp_key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[] {value, mAccount.name},
- null);
- } else {
- try {
- c = getContentProvider().query(ProviderTableMeta.CONTENT_URI,
- null,
- cmp_key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[] {value, mAccount.name},
- null);
- } catch (RemoteException e) {
- Log.e(TAG, "Couldn't determine file existance, assuming non existance: " + e.getMessage());
- return false;
- }
+
+ public Account getAccount() {
+ return mAccount;
}
- boolean retval = c.moveToFirst();
- c.close();
- return retval;
- }
-
- private Cursor getCursorForValue(String key, String value) {
- Cursor c = null;
- if (getContentResolver() != null) {
- c = getContentResolver().query(ProviderTableMeta.CONTENT_URI,
- null,
- key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[] {value, mAccount.name},
- null);
- } else {
- try {
- c = getContentProvider().query(ProviderTableMeta.CONTENT_URI,
- null,
- key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
- new String[]{value, mAccount.name},
- null);
- } catch (RemoteException e) {
- Log.e(TAG, "Could not get file details: " + e.getMessage());
- c = null;
- }
+
+ public void setContentResolver(ContentResolver cr) {
+ mContentResolver = cr;
+ }
+
+ public ContentResolver getContentResolver() {
+ return mContentResolver;
}
- return c;
- }
-
- private OCFile createFileInstance(Cursor c) {
- OCFile file = null;
- if (c != null) {
- file = new OCFile(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH)));
- file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
- file.setParentId(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_PARENT)));
- file.setStoragePath(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
- file.setMimetype(c.getString(c.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
- file.setFileLength(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
- file.setCreationTimestamp(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_CREATION)));
- file.setModificationTimestamp(c.getLong(c.getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
+
+ public void setContentProvider(ContentProviderClient cp) {
+ mContentProvider = cp;
+ }
+
+ public ContentProviderClient getContentProvider() {
+ return mContentProvider;
+ }
+
+ public Vector<OCFile> getDirectoryContent(OCFile f) {
+ if (f != null && f.isDirectory() && f.getFileId() != -1) {
+ Vector<OCFile> ret = new Vector<OCFile>();
+
+ Uri req_uri = Uri.withAppendedPath(
+ ProviderTableMeta.CONTENT_URI_DIR,
+ String.valueOf(f.getFileId()));
+ Cursor c = null;
+
+ if (getContentProvider() != null) {
+ try {
+ c = getContentProvider().query(req_uri, null,
+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+ new String[] { mAccount.name }, null);
+ } catch (RemoteException e) {
+ Log.e(TAG, e.getMessage());
+ return ret;
+ }
+ } else {
+ c = getContentResolver().query(req_uri, null,
+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+ new String[] { mAccount.name }, null);
+ }
+
+ if (c.moveToFirst()) {
+ do {
+ OCFile child = createFileInstance(c);
+ ret.add(child);
+ } while (c.moveToNext());
+ }
+
+ c.close();
+ return ret;
+ }
+ return null;
+ }
+
+ private boolean fileExists(String cmp_key, String value) {
+ Cursor c;
+ if (getContentResolver() != null) {
+ c = getContentResolver()
+ .query(ProviderTableMeta.CONTENT_URI,
+ null,
+ cmp_key + "=? AND "
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER
+ + "=?",
+ new String[] { value, mAccount.name }, null);
+ } else {
+ try {
+ c = getContentProvider().query(
+ ProviderTableMeta.CONTENT_URI,
+ null,
+ cmp_key + "=? AND "
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
+ new String[] { value, mAccount.name }, null);
+ } catch (RemoteException e) {
+ Log.e(TAG,
+ "Couldn't determine file existance, assuming non existance: "
+ + e.getMessage());
+ return false;
+ }
+ }
+ boolean retval = c.moveToFirst();
+ c.close();
+ return retval;
+ }
+
+ private Cursor getCursorForValue(String key, String value) {
+ Cursor c = null;
+ if (getContentResolver() != null) {
+ c = getContentResolver()
+ .query(ProviderTableMeta.CONTENT_URI,
+ null,
+ key + "=? AND "
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER
+ + "=?",
+ new String[] { value, mAccount.name }, null);
+ } else {
+ try {
+ c = getContentProvider().query(
+ ProviderTableMeta.CONTENT_URI,
+ null,
+ key + "=? AND " + ProviderTableMeta.FILE_ACCOUNT_OWNER
+ + "=?", new String[] { value, mAccount.name },
+ null);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Could not get file details: " + e.getMessage());
+ c = null;
+ }
+ }
+ return c;
+ }
+
+ private OCFile createFileInstance(Cursor c) {
+ OCFile file = null;
+ if (c != null) {
+ file = new OCFile(c.getString(c
+ .getColumnIndex(ProviderTableMeta.FILE_PATH)));
+ file.setFileId(c.getLong(c.getColumnIndex(ProviderTableMeta._ID)));
+ file.setParentId(c.getLong(c
+ .getColumnIndex(ProviderTableMeta.FILE_PARENT)));
+ file.setStoragePath(c.getString(c
+ .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH)));
+ file.setMimetype(c.getString(c
+ .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE)));
+ file.setFileLength(c.getLong(c
+ .getColumnIndex(ProviderTableMeta.FILE_CONTENT_LENGTH)));
+ file.setCreationTimestamp(c.getLong(c
+ .getColumnIndex(ProviderTableMeta.FILE_CREATION)));
+ file.setModificationTimestamp(c.getLong(c
+ .getColumnIndex(ProviderTableMeta.FILE_MODIFIED)));
+ }
+ return file;
}
- return file;
- }
}
public class OCFile implements Parcelable {
- public static final Parcelable.Creator<OCFile> CREATOR = new Parcelable.Creator<OCFile>() {
- @Override
- public OCFile createFromParcel(Parcel source) {
- return new OCFile(source);
- }
-
- @Override
- public OCFile[] newArray(int size) {
- return new OCFile[size];
- }
- };
-
- private long mId;
- private long mParentId;
- private long mLength;
- private long mCreationTimestamp;
- private long mModifiedTimestamp;
- private String mRemotePath;
- private String mLocalPath;
- private String mMimeType;
- private boolean mNeedsUpdating;
-
- /**
- * Create new {@link OCFile} with given path
- *
- * @param path
- * The remote path of the file
- */
- public OCFile(String path) {
- resetData();
- mNeedsUpdating = false;
- mRemotePath = path;
- }
-
- /**
- * Reconstruct from parcel
- * @param source The source parcel
- */
- private OCFile(Parcel source){
- mId = source.readLong();
- mParentId = source.readLong();
- mLength = source.readLong();
- mCreationTimestamp = source.readLong();
- mModifiedTimestamp = source.readLong();
- mRemotePath = source.readString();
- mLocalPath = source.readString();
- mMimeType = source.readString();
- mNeedsUpdating = source.readInt() == 0;
- }
-
- /**
- * Gets the ID of the file
- *
- * @return the file ID
- */
- public long getFileId() {
- return mId;
- }
-
- /**
- * Returns the path of the file
- *
- * @return The path
- */
- public String getPath() {
- return mRemotePath;
- }
-
- /**
- * Can be used to check, whether or not this file exists in the database
- * already
- *
- * @return true, if the file exists in the database
- */
- public boolean fileExists() {
- return mId != -1;
- }
-
- /**
- * Use this to find out if this file is a Directory
- *
- * @return true if it is a directory
- */
- public boolean isDirectory() {
- return mMimeType != null && mMimeType.equals("DIR");
- }
-
- /**
- * Use this to check if this file is available locally
- *
- * @return true if it is
- */
- public boolean isDownloaded() {
- return mLocalPath != null || mLocalPath.equals("");
- }
-
- /**
- * The path, where the file is stored locally
- *
- * @return The local path to the file
- */
- public String getStoragePath() {
- return mLocalPath;
- }
-
- /**
- * Can be used to set the path where the file is stored
- *
- * @param storage_path
- * to set
- */
- public void setStoragePath(String storage_path) {
- mLocalPath = storage_path;
- }
-
- /**
- * Get a UNIX timestamp of the file creation time
- *
- * @return A UNIX timestamp of the time that file was created
- */
- public long getCreationTimestamp() {
- return mCreationTimestamp;
- }
-
- /**
- * Set a UNIX timestamp of the time the file was created
- *
- * @param creation_timestamp
- * to set
- */
- public void setCreationTimestamp(long creation_timestamp) {
- mCreationTimestamp = creation_timestamp;
- }
-
- /**
- * Get a UNIX timestamp of the file modification time
- *
- * @return A UNIX timestamp of the modification time
- */
- public long getModificationTimestamp() {
- return mModifiedTimestamp;
- }
-
- /**
- * Set a UNIX timestamp of the time the time the file was modified.
- *
- * @param modification_timestamp
- * to set
- */
- public void setModificationTimestamp(long modification_timestamp) {
- mModifiedTimestamp = modification_timestamp;
- }
-
- /**
- * Returns the filename and "/" for the root directory
- *
- * @return The name of the file
- */
- public String getFileName() {
- if (mRemotePath != null) {
- File f = new File(mRemotePath);
- return f.getName().equals("") ? "/" : f.getName();
- }
- return null;
- }
-
- /**
- * Can be used to get the Mimetype
- *
- * @return the Mimetype as a String
- */
- public String getMimetype() {
- return mMimeType;
- }
-
- /**
- * Adds a file to this directory. If this file is not a directory, an
- * exception gets thrown.
- *
- * @param file
- * to add
- * @throws IllegalStateException
- * if you try to add a something and this is not a directory
- */
- public void addFile(OCFile file) throws IllegalStateException {
- if (isDirectory()) {
- file.mParentId = mId;
- mNeedsUpdating = true;
- return;
- }
- throw new IllegalStateException(
- "This is not a directory where you can add stuff to!");
- }
-
- /**
- * Used internally. Reset all file properties
- */
- private void resetData() {
- mId = -1;
- mRemotePath = null;
- mParentId = 0;
- mLocalPath = null;
- mMimeType = null;
- mLength = 0;
- mCreationTimestamp = 0;
- mModifiedTimestamp = 0;
- }
-
- /**
- * Sets the ID of the file
- *
- * @param file_id
- * to set
- */
- public void setFileId(long file_id) {
- mId = file_id;
- }
-
- /**
- * Sets the Mime-Type of the
- *
- * @param mimetype
- * to set
- */
- public void setMimetype(String mimetype) {
- mMimeType = mimetype;
- }
-
- /**
- * Sets the ID of the parent folder
- *
- * @param parent_id
- * to set
- */
- public void setParentId(long parent_id) {
- mParentId = parent_id;
- }
-
- /**
- * Sets the file size in bytes
- *
- * @param file_len
- * to set
- */
- public void setFileLength(long file_len) {
- mLength = file_len;
- }
-
- /**
- * Returns the size of the file in bytes
- *
- * @return The filesize in bytes
- */
- public long getFileLength() {
- return mLength;
- }
-
- /**
- * Returns the ID of the parent Folder
- *
- * @return The ID
- */
- public long getParentId() {
- return mParentId;
- }
-
- /**
- * Check, if this file needs updating
- *
- * @return
- */
- public boolean needsUpdatingWhileSaving() {
- return mNeedsUpdating;
- }
-
- @Override
- public int describeContents() {
- return this.hashCode();
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mId);
- dest.writeLong(mParentId);
- dest.writeLong(mLength);
- dest.writeLong(mCreationTimestamp);
- dest.writeLong(mModifiedTimestamp);
- dest.writeString(mRemotePath);
- dest.writeString(mLocalPath);
- dest.writeString(mMimeType);
- dest.writeInt(mNeedsUpdating ? 0 : 1 ); // No writeBoolean method exists - yay :D
- }
-
+ public static final Parcelable.Creator<OCFile> CREATOR = new Parcelable.Creator<OCFile>() {
+ @Override
+ public OCFile createFromParcel(Parcel source) {
+ return new OCFile(source);
+ }
+
+ @Override
+ public OCFile[] newArray(int size) {
+ return new OCFile[size];
+ }
+ };
+
+ private long mId;
+ private long mParentId;
+ private long mLength;
+ private long mCreationTimestamp;
+ private long mModifiedTimestamp;
+ private String mRemotePath;
+ private String mLocalPath;
+ private String mMimeType;
+ private boolean mNeedsUpdating;
+
+ /**
+ * Create new {@link OCFile} with given path
+ *
+ * @param path
+ * The remote path of the file
+ */
+ public OCFile(String path) {
+ resetData();
+ mNeedsUpdating = false;
+ mRemotePath = path;
+ }
+
+ /**
+ * Reconstruct from parcel
+ *
+ * @param source
+ * The source parcel
+ */
+ private OCFile(Parcel source) {
+ mId = source.readLong();
+ mParentId = source.readLong();
+ mLength = source.readLong();
+ mCreationTimestamp = source.readLong();
+ mModifiedTimestamp = source.readLong();
+ mRemotePath = source.readString();
+ mLocalPath = source.readString();
+ mMimeType = source.readString();
+ mNeedsUpdating = source.readInt() == 0;
+ }
+
+ /**
+ * Gets the ID of the file
+ *
+ * @return the file ID
+ */
+ public long getFileId() {
+ return mId;
+ }
+
+ /**
+ * Returns the path of the file
+ *
+ * @return The path
+ */
+ public String getPath() {
+ return mRemotePath;
+ }
+
+ /**
+ * Can be used to check, whether or not this file exists in the database
+ * already
+ *
+ * @return true, if the file exists in the database
+ */
+ public boolean fileExists() {
+ return mId != -1;
+ }
+
+ /**
+ * Use this to find out if this file is a Directory
+ *
+ * @return true if it is a directory
+ */
+ public boolean isDirectory() {
+ return mMimeType != null && mMimeType.equals("DIR");
+ }
+
+ /**
+ * Use this to check if this file is available locally
+ *
+ * @return true if it is
+ */
+ public boolean isDownloaded() {
+ return mLocalPath != null || mLocalPath.equals("");
+ }
+
+ /**
+ * The path, where the file is stored locally
+ *
+ * @return The local path to the file
+ */
+ public String getStoragePath() {
+ return mLocalPath;
+ }
+
+ /**
+ * Can be used to set the path where the file is stored
+ *
+ * @param storage_path
+ * to set
+ */
+ public void setStoragePath(String storage_path) {
+ mLocalPath = storage_path;
+ }
+
+ /**
+ * Get a UNIX timestamp of the file creation time
+ *
+ * @return A UNIX timestamp of the time that file was created
+ */
+ public long getCreationTimestamp() {
+ return mCreationTimestamp;
+ }
+
+ /**
+ * Set a UNIX timestamp of the time the file was created
+ *
+ * @param creation_timestamp
+ * to set
+ */
+ public void setCreationTimestamp(long creation_timestamp) {
+ mCreationTimestamp = creation_timestamp;
+ }
+
+ /**
+ * Get a UNIX timestamp of the file modification time
+ *
+ * @return A UNIX timestamp of the modification time
+ */
+ public long getModificationTimestamp() {
+ return mModifiedTimestamp;
+ }
+
+ /**
+ * Set a UNIX timestamp of the time the time the file was modified.
+ *
+ * @param modification_timestamp
+ * to set
+ */
+ public void setModificationTimestamp(long modification_timestamp) {
+ mModifiedTimestamp = modification_timestamp;
+ }
+
+ /**
+ * Returns the filename and "/" for the root directory
+ *
+ * @return The name of the file
+ */
+ public String getFileName() {
+ if (mRemotePath != null) {
+ File f = new File(mRemotePath);
+ return f.getName().equals("") ? "/" : f.getName();
+ }
+ return null;
+ }
+
+ /**
+ * Can be used to get the Mimetype
+ *
+ * @return the Mimetype as a String
+ */
+ public String getMimetype() {
+ return mMimeType;
+ }
+
+ /**
+ * Adds a file to this directory. If this file is not a directory, an
+ * exception gets thrown.
+ *
+ * @param file
+ * to add
+ * @throws IllegalStateException
+ * if you try to add a something and this is not a directory
+ */
+ public void addFile(OCFile file) throws IllegalStateException {
+ if (isDirectory()) {
+ file.mParentId = mId;
+ mNeedsUpdating = true;
+ return;
+ }
+ throw new IllegalStateException(
+ "This is not a directory where you can add stuff to!");
+ }
+
+ /**
+ * Used internally. Reset all file properties
+ */
+ private void resetData() {
+ mId = -1;
+ mRemotePath = null;
+ mParentId = 0;
+ mLocalPath = null;
+ mMimeType = null;
+ mLength = 0;
+ mCreationTimestamp = 0;
+ mModifiedTimestamp = 0;
+ }
+
+ /**
+ * Sets the ID of the file
+ *
+ * @param file_id
+ * to set
+ */
+ public void setFileId(long file_id) {
+ mId = file_id;
+ }
+
+ /**
+ * Sets the Mime-Type of the
+ *
+ * @param mimetype
+ * to set
+ */
+ public void setMimetype(String mimetype) {
+ mMimeType = mimetype;
+ }
+
+ /**
+ * Sets the ID of the parent folder
+ *
+ * @param parent_id
+ * to set
+ */
+ public void setParentId(long parent_id) {
+ mParentId = parent_id;
+ }
+
+ /**
+ * Sets the file size in bytes
+ *
+ * @param file_len
+ * to set
+ */
+ public void setFileLength(long file_len) {
+ mLength = file_len;
+ }
+
+ /**
+ * Returns the size of the file in bytes
+ *
+ * @return The filesize in bytes
+ */
+ public long getFileLength() {
+ return mLength;
+ }
+
+ /**
+ * Returns the ID of the parent Folder
+ *
+ * @return The ID
+ */
+ public long getParentId() {
+ return mParentId;
+ }
+
+ /**
+ * Check, if this file needs updating
+ *
+ * @return
+ */
+ public boolean needsUpdatingWhileSaving() {
+ return mNeedsUpdating;
+ }
+
+ @Override
+ public int describeContents() {
+ return this.hashCode();
+ }
+
+ @Override
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeLong(mId);
+ dest.writeLong(mParentId);
+ dest.writeLong(mLength);
+ dest.writeLong(mCreationTimestamp);
+ dest.writeLong(mModifiedTimestamp);
+ dest.writeString(mRemotePath);
+ dest.writeString(mLocalPath);
+ dest.writeString(mMimeType);
+ dest.writeInt(mNeedsUpdating ? 0 : 1); // No writeBoolean method exists
+ // - yay :D
+ }
+
}
\r
/**\r
* Custom database helper for ownCloud\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class DbHandler {\r
- private SQLiteDatabase mDB;\r
- private OpenerHepler mHelper;\r
- private final String mDatabaseName = "ownCloud";\r
- private final String TABLE_SESSIONS = "sessions";\r
- private final int mDatabaseVersion = 1;\r
- \r
- public DbHandler(Context context) {\r
- mHelper = new OpenerHepler(context);\r
- mDB = mHelper.getWritableDatabase();\r
- }\r
- \r
- public Vector<OwnCloudSession> getSessionList() {\r
- Cursor c = mDB.query(TABLE_SESSIONS, null, null, null, null, null, null);\r
- Vector<OwnCloudSession> v = new Vector<OwnCloudSession>();\r
- if (!c.moveToFirst()) {\r
- return v;\r
+ private SQLiteDatabase mDB;\r
+ private OpenerHepler mHelper;\r
+ private final String mDatabaseName = "ownCloud";\r
+ private final String TABLE_SESSIONS = "sessions";\r
+ private final int mDatabaseVersion = 1;\r
+\r
+ public DbHandler(Context context) {\r
+ mHelper = new OpenerHepler(context);\r
+ mDB = mHelper.getWritableDatabase();\r
}\r
- while (!c.isAfterLast()) {\r
- v.add(new OwnCloudSession(c.getString(c.getColumnIndex("sessionName")),\r
- c.getString(c.getColumnIndex("sessionUrl")),\r
- c.getInt(c.getColumnIndex("_id"))));\r
- c.moveToNext();\r
+\r
+ public Vector<OwnCloudSession> getSessionList() {\r
+ Cursor c = mDB\r
+ .query(TABLE_SESSIONS, null, null, null, null, null, null);\r
+ Vector<OwnCloudSession> v = new Vector<OwnCloudSession>();\r
+ if (!c.moveToFirst()) {\r
+ return v;\r
+ }\r
+ while (!c.isAfterLast()) {\r
+ v.add(new OwnCloudSession(c.getString(c\r
+ .getColumnIndex("sessionName")), c.getString(c\r
+ .getColumnIndex("sessionUrl")), c.getInt(c\r
+ .getColumnIndex("_id"))));\r
+ c.moveToNext();\r
+ }\r
+ c.close();\r
+ return v;\r
+ }\r
+\r
+ public void addSession(String sessionName, String uri) {\r
+ ContentValues cv = new ContentValues();\r
+ cv.put("sessionName", sessionName);\r
+ cv.put("sessionUrl", uri);\r
+ mDB.insert(TABLE_SESSIONS, null, cv);\r
}\r
- c.close();\r
- return v;\r
- }\r
- \r
- public void addSession(String sessionName, String uri) {\r
- ContentValues cv = new ContentValues();\r
- cv.put("sessionName", sessionName);\r
- cv.put("sessionUrl", uri);\r
- mDB.insert(TABLE_SESSIONS, null, cv);\r
- }\r
- \r
- public void removeSessionWithId(int sessionId) {\r
- mDB.delete(TABLE_SESSIONS, "_id = ?", new String[] {String.valueOf(sessionId)});\r
- }\r
\r
- public void changeSessionFields(int id, String hostname, String uri) {\r
- ContentValues cv = new ContentValues();\r
- cv.put("sessionName", hostname);\r
- cv.put("sessionUrl", uri);\r
- mDB.update(TABLE_SESSIONS, cv, "_id = ?", new String[] {String.valueOf(id)});\r
- }\r
- \r
- public void close() {\r
- mDB.close();\r
- }\r
- \r
- private class OpenerHepler extends SQLiteOpenHelper {\r
- public OpenerHepler(Context context) {\r
- super(context, mDatabaseName, null, mDatabaseVersion);\r
+ public void removeSessionWithId(int sessionId) {\r
+ mDB.delete(TABLE_SESSIONS, "_id = ?",\r
+ new String[] { String.valueOf(sessionId) });\r
}\r
\r
- @Override\r
- public void onCreate(SQLiteDatabase db) {\r
- db.execSQL("CREATE TABLE " + TABLE_SESSIONS + " (" +\r
- " _id INTEGER PRIMARY KEY, " +\r
- " sessionName TEXT, " +\r
- " sessionUrl TEXT);");\r
+ public void changeSessionFields(int id, String hostname, String uri) {\r
+ ContentValues cv = new ContentValues();\r
+ cv.put("sessionName", hostname);\r
+ cv.put("sessionUrl", uri);\r
+ mDB.update(TABLE_SESSIONS, cv, "_id = ?",\r
+ new String[] { String.valueOf(id) });\r
}\r
\r
- @Override\r
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r
+ public void close() {\r
+ mDB.close();\r
+ }\r
+\r
+ private class OpenerHepler extends SQLiteOpenHelper {\r
+ public OpenerHepler(Context context) {\r
+ super(context, mDatabaseName, null, mDatabaseVersion);\r
+ }\r
+\r
+ @Override\r
+ public void onCreate(SQLiteDatabase db) {\r
+ db.execSQL("CREATE TABLE " + TABLE_SESSIONS + " ("\r
+ + " _id INTEGER PRIMARY KEY, " + " sessionName TEXT, "\r
+ + " sessionUrl TEXT);");\r
+ }\r
+\r
+ @Override\r
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r
+ }\r
}\r
- }\r
}\r
\r
/**\r
* Meta-Class that holds various static field information\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class ProviderMeta {\r
\r
- public static final String AUTHORITY_FILES = "org.owncloud";\r
- public static final String DB_FILE = "owncloud.db";\r
- public static final String DB_NAME = "filelist";\r
- public static final int DB_VERSION = 1;\r
- \r
- private ProviderMeta() { }\r
- \r
- static public class ProviderTableMeta implements BaseColumns {\r
+ public static final String AUTHORITY_FILES = "org.owncloud";\r
+ public static final String DB_FILE = "owncloud.db";\r
public static final String DB_NAME = "filelist";\r
- public static final Uri CONTENT_URI = \r
- Uri.parse("content://" + AUTHORITY_FILES + "/");\r
- public static final Uri CONTENT_URI_FILE =\r
- Uri.parse("content://" + AUTHORITY_FILES + "/file");\r
- public static final Uri CONTENT_URI_DIR =\r
- Uri.parse("content://" + AUTHORITY_FILES + "/dir");\r
+ public static final int DB_VERSION = 1;\r
+\r
+ private ProviderMeta() {\r
+ }\r
+\r
+ static public class ProviderTableMeta implements BaseColumns {\r
+ public static final String DB_NAME = "filelist";\r
+ public static final Uri CONTENT_URI = Uri.parse("content://"\r
+ + AUTHORITY_FILES + "/");\r
+ public static final Uri CONTENT_URI_FILE = Uri.parse("content://"\r
+ + AUTHORITY_FILES + "/file");\r
+ public static final Uri CONTENT_URI_DIR = Uri.parse("content://"\r
+ + AUTHORITY_FILES + "/dir");\r
+\r
+ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.owncloud.file";\r
+ public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.owncloud.file";\r
+\r
+ public static final String FILE_PARENT = "parent";\r
+ public static final String FILE_NAME = "filename";\r
+ public static final String FILE_CREATION = "created";\r
+ public static final String FILE_MODIFIED = "modified";\r
+ public static final String FILE_CONTENT_LENGTH = "content_length";\r
+ public static final String FILE_CONTENT_TYPE = "content_type";\r
+ public static final String FILE_STORAGE_PATH = "media_path";\r
+ public static final String FILE_PATH = "path";\r
+ public static final String FILE_ACCOUNT_OWNER = "file_owner";\r
\r
- public static final String CONTENT_TYPE =\r
- "vnd.android.cursor.dir/vnd.owncloud.file";\r
- public static final String CONTENT_TYPE_ITEM =\r
- "vnd.android.cursor.item/vnd.owncloud.file";\r
- \r
- public static final String FILE_PARENT = "parent";\r
- public static final String FILE_NAME = "filename";\r
- public static final String FILE_CREATION = "created";\r
- public static final String FILE_MODIFIED = "modified";\r
- public static final String FILE_CONTENT_LENGTH = "content_length";\r
- public static final String FILE_CONTENT_TYPE = "content_type";\r
- public static final String FILE_STORAGE_PATH = "media_path";\r
- public static final String FILE_PATH = "path";\r
- public static final String FILE_ACCOUNT_OWNER = "file_owner";\r
- \r
- public static final String DEFAULT_SORT_ORDER = FILE_NAME + " collate nocase asc";\r
+ public static final String DEFAULT_SORT_ORDER = FILE_NAME\r
+ + " collate nocase asc";\r
\r
- }\r
+ }\r
}\r
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ExtensionsAvailableActivity extends SherlockFragmentActivity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- FragmentManager fm = getSupportFragmentManager();
- ExtensionsAvailableDialog ead = new ExtensionsAvailableDialog();
- ead.show(fm, "extensions_available_dialog");
- }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ FragmentManager fm = getSupportFragmentManager();
+ ExtensionsAvailableDialog ead = new ExtensionsAvailableDialog();
+ ead.show(fm, "extensions_available_dialog");
+ }
}
import android.view.View.OnClickListener;
import android.widget.Button;
-public class ExtensionsAvailableDialog extends DialogFragment implements OnClickListener {
+public class ExtensionsAvailableDialog extends DialogFragment implements
+ OnClickListener {
- public ExtensionsAvailableDialog() { }
+ public ExtensionsAvailableDialog() {
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.extensions_available_dialog,
+ container);
+ Button btnYes = (Button) view.findViewById(R.id.buttonYes);
+ Button btnNo = (Button) view.findViewById(R.id.buttonNo);
+ btnYes.setOnClickListener(this);
+ btnNo.setOnClickListener(this);
+ getDialog().setTitle(R.string.extensions_avail_title);
+ return view;
+ }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.extensions_available_dialog, container);
- Button btnYes = (Button) view.findViewById(R.id.buttonYes);
- Button btnNo = (Button) view.findViewById(R.id.buttonNo);
- btnYes.setOnClickListener(this);
- btnNo.setOnClickListener(this);
- getDialog().setTitle(R.string.extensions_avail_title);
- return view;
- }
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.buttonYes:
- {
- Intent i = new Intent(getActivity(), ExtensionsListActivity.class);
- startActivity(i);
- getActivity().finish();
+ @Override
+ public void onClick(View v) {
+ switch (v.getId()) {
+ case R.id.buttonYes: {
+ Intent i = new Intent(getActivity(), ExtensionsListActivity.class);
+ startActivity(i);
+ getActivity().finish();
+ }
+ break;
+ case R.id.buttonNo:
+ getActivity().finish();
+ break;
+ default:
+ Log.e("EAD", "Button with unknown id clicked " + v.getId());
}
- break;
- case R.id.buttonNo:
- getActivity().finish();
- break;
- default:
- Log.e("EAD", "Button with unknown id clicked " + v.getId());
}
- }
}
public class ExtensionsListActivity extends ListActivity {
- private static final String packages_url = "http://alefzero.eu/a/packages.php";
-
- private Thread mGetterThread;
- private final Handler mHandler = new Handler();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mGetterThread = new Thread(new JsonGetter());
- mGetterThread.start();
- }
-
- public void done(JSONArray a) {
- LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String,String>>();
- for (int i = 0; i < a.length(); ++i) {
- try {
- ExtensionApplicationEntry ela = new ExtensionApplicationEntry(((JSONObject)a.get(i)));
- HashMap<String, String> ss = new HashMap<String, String>();
- ss.put("NAME", ela.getName());
- ss.put("DESC", ela.getDescription());
- ll.add(ss);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- setListAdapter(new SimpleAdapter(this,
- ll,
- R.layout.simple_list_item_2,
- new String[] {"NAME", "DESC"},
- new int[] {android.R.id.text1, android.R.id.text2}));
-
- }
-
- private class JsonGetter implements Runnable {
+ private static final String packages_url = "http://alefzero.eu/a/packages.php";
+
+ private Thread mGetterThread;
+ private final Handler mHandler = new Handler();
@Override
- public void run() {
- HttpClient hc = new HttpClient();
- GetMethod gm = new GetMethod(packages_url);
- final JSONArray ar;
- try {
- hc.executeMethod(gm);
- Log.e("ASD", gm.getResponseBodyAsString()+"");
- ar = new JSONObject(gm.getResponseBodyAsString()).getJSONArray("apps");
- } catch (Exception e) {
- e.printStackTrace();
- return;
- }
-
- mHandler.post(new Runnable() {
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ mGetterThread = new Thread(new JsonGetter());
+ mGetterThread.start();
+ }
+
+ public void done(JSONArray a) {
+ LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String, String>>();
+ for (int i = 0; i < a.length(); ++i) {
+ try {
+ ExtensionApplicationEntry ela = new ExtensionApplicationEntry(
+ ((JSONObject) a.get(i)));
+ HashMap<String, String> ss = new HashMap<String, String>();
+ ss.put("NAME", ela.getName());
+ ss.put("DESC", ela.getDescription());
+ ll.add(ss);
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+ setListAdapter(new SimpleAdapter(this, ll, R.layout.simple_list_item_2,
+ new String[] { "NAME", "DESC" }, new int[] {
+ android.R.id.text1, android.R.id.text2 }));
+
+ }
+
+ private class JsonGetter implements Runnable {
+
@Override
public void run() {
- done(ar);
+ HttpClient hc = new HttpClient();
+ GetMethod gm = new GetMethod(packages_url);
+ final JSONArray ar;
+ try {
+ hc.executeMethod(gm);
+ Log.e("ASD", gm.getResponseBodyAsString() + "");
+ ar = new JSONObject(gm.getResponseBodyAsString())
+ .getJSONArray("apps");
+ } catch (Exception e) {
+ e.printStackTrace();
+ return;
+ }
+
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ done(ar);
+ }
+ });
+
}
- });
-
+
}
-
- }
-
- private class ExtensionApplicationEntry {
- private static final String APP_NAME = "name";
- private static final String APP_VERSION = "version";
- private static final String APP_DESC = "description";
- private static final String APP_ICON = "icon";
- private static final String APP_URL = "download";
- private static final String APP_PLAYID = "play_id";
-
- private String mName, mDescription, mIcon, mDownload, mPlayId;
- private OwnCloudVersion mVersion;
-
- public ExtensionApplicationEntry(JSONObject appentry) {
- try {
- mName = appentry.getString(APP_NAME);
- mDescription = appentry.getString(APP_DESC);
- mIcon = appentry.getString(APP_ICON);
- mDownload = appentry.getString(APP_URL);
- mPlayId = appentry.getString(APP_PLAYID);
- mVersion = new OwnCloudVersion(appentry.getString(APP_VERSION));
- } catch (JSONException e) {
- e.printStackTrace();
- }
+
+ private class ExtensionApplicationEntry {
+ private static final String APP_NAME = "name";
+ private static final String APP_VERSION = "version";
+ private static final String APP_DESC = "description";
+ private static final String APP_ICON = "icon";
+ private static final String APP_URL = "download";
+ private static final String APP_PLAYID = "play_id";
+
+ private String mName, mDescription, mIcon, mDownload, mPlayId;
+ private OwnCloudVersion mVersion;
+
+ public ExtensionApplicationEntry(JSONObject appentry) {
+ try {
+ mName = appentry.getString(APP_NAME);
+ mDescription = appentry.getString(APP_DESC);
+ mIcon = appentry.getString(APP_ICON);
+ mDownload = appentry.getString(APP_URL);
+ mPlayId = appentry.getString(APP_PLAYID);
+ mVersion = new OwnCloudVersion(appentry.getString(APP_VERSION));
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String getName() {
+ return mName;
+ }
+
+ public String getDescription() {
+ return mDescription;
+ }
+
+ public String getIcon() {
+ return mIcon;
+ }
+
+ public String getDownload() {
+ return mDownload;
+ }
+
+ public String getPlayId() {
+ return mPlayId;
+ }
+
+ public OwnCloudVersion getVersion() {
+ return mVersion;
+ }
}
-
- public String getName() { return mName; }
- public String getDescription() { return mDescription; }
- public String getIcon() { return mIcon; }
- public String getDownload() { return mDownload; }
- public String getPlayId() { return mPlayId; }
- public OwnCloudVersion getVersion() { return mVersion; }
- }
}
public class FileUploader extends Service {
- public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
- public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
- public static final String KEY_ACCOUNT = "ACCOUNT";
- public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
-
- public static final int UPLOAD_SINGLE_FILE = 0;
- public static final int UPLOAD_MULTIPLE_FILES = 1;
-
- private static final String TAG = "FileUploader";
- private NotificationManager mNotificationManager;
- private Looper mServiceLooper;
- private ServiceHandler mServiceHandler;
- private AccountManager mAccountManager;
- private Account mAccount;
- private String[] mLocalPaths, mRemotePaths;
- private boolean mResult;
- private int mUploadType;
-
- @Override
- public IBinder onBind(Intent arg0) {
- return null;
- }
-
- private final class ServiceHandler extends Handler {
- public ServiceHandler(Looper looper) {
- super(looper);
- }
+ public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
+ public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
+ public static final String KEY_ACCOUNT = "ACCOUNT";
+ public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
+
+ public static final int UPLOAD_SINGLE_FILE = 0;
+ public static final int UPLOAD_MULTIPLE_FILES = 1;
+
+ private static final String TAG = "FileUploader";
+ private NotificationManager mNotificationManager;
+ private Looper mServiceLooper;
+ private ServiceHandler mServiceHandler;
+ private AccountManager mAccountManager;
+ private Account mAccount;
+ private String[] mLocalPaths, mRemotePaths;
+ private boolean mResult;
+ private int mUploadType;
+
@Override
- public void handleMessage(Message msg) {
- uploadFile();
- stopSelf(msg.arg1);
+ public IBinder onBind(Intent arg0) {
+ return null;
}
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
- thread.start();
- mServiceLooper = thread.getLooper();
- mServiceHandler = new ServiceHandler(mServiceLooper);
- mAccountManager = AccountManager.get(this);
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
- Log.e(TAG, "Not enought data in intent provided");
- return Service.START_NOT_STICKY;
- }
- mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
- mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
- if (mUploadType == -1) {
- Log.e(TAG, "Incorrect upload type provided");
- return Service.START_NOT_STICKY;
+
+ private final class ServiceHandler extends Handler {
+ public ServiceHandler(Looper looper) {
+ super(looper);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ uploadFile();
+ stopSelf(msg.arg1);
+ }
}
- if (mUploadType == UPLOAD_SINGLE_FILE) {
- mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
- mRemotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
- } else { // mUploadType == UPLOAD_MULTIPLE_FILES
- mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
- mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+ HandlerThread thread = new HandlerThread("FileUploaderThread",
+ Process.THREAD_PRIORITY_BACKGROUND);
+ thread.start();
+ mServiceLooper = thread.getLooper();
+ mServiceHandler = new ServiceHandler(mServiceLooper);
+ mAccountManager = AccountManager.get(this);
}
-
- for (int i = 0; i < mRemotePaths.length; ++i)
- mRemotePaths[i] = mRemotePaths[i].replace(' ', '+');
-
- if (mLocalPaths.length != mRemotePaths.length) {
- Log.e(TAG, "Remote paths and local paths are not equal!");
- return Service.START_NOT_STICKY;
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
+ Log.e(TAG, "Not enought data in intent provided");
+ return Service.START_NOT_STICKY;
+ }
+ mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
+ mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
+ if (mUploadType == -1) {
+ Log.e(TAG, "Incorrect upload type provided");
+ return Service.START_NOT_STICKY;
+ }
+ if (mUploadType == UPLOAD_SINGLE_FILE) {
+ mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
+ mRemotePaths = new String[] { intent
+ .getStringExtra(KEY_REMOTE_FILE) };
+ } else { // mUploadType == UPLOAD_MULTIPLE_FILES
+ mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
+ mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
+ }
+
+ for (int i = 0; i < mRemotePaths.length; ++i)
+ mRemotePaths[i] = mRemotePaths[i].replace(' ', '+');
+
+ if (mLocalPaths.length != mRemotePaths.length) {
+ Log.e(TAG, "Remote paths and local paths are not equal!");
+ return Service.START_NOT_STICKY;
+ }
+
+ Message msg = mServiceHandler.obtainMessage();
+ msg.arg1 = startId;
+ mServiceHandler.sendMessage(msg);
+
+ return Service.START_NOT_STICKY;
}
-
- Message msg = mServiceHandler.obtainMessage();
- msg.arg1 = startId;
- mServiceHandler.sendMessage(msg);
-
- return Service.START_NOT_STICKY;
- }
-
- public void run() {
- if (mResult) {
- Toast.makeText(this, "Upload successfull", Toast.LENGTH_SHORT).show();
- } else {
- Toast.makeText(this, "No i kupa", Toast.LENGTH_SHORT).show();
+
+ public void run() {
+ if (mResult) {
+ Toast.makeText(this, "Upload successfull", Toast.LENGTH_SHORT)
+ .show();
+ } else {
+ Toast.makeText(this, "No i kupa", Toast.LENGTH_SHORT).show();
+ }
}
- }
public void uploadFile() {
- String baseUrl = mAccountManager.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL),
- ocVerStr = mAccountManager.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
- OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
- String webdav_path = AccountUtils.getWebdavPath(ocVer);
- Uri ocUri = Uri.parse(baseUrl + webdav_path);
- String username = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
- String password = mAccountManager.getPassword(mAccount);
- Notification notification = new Notification(eu.alefzero.owncloud.R.drawable.icon,
- "Uploading...", System.currentTimeMillis());
- notification.flags |= Notification.FLAG_ONGOING_EVENT;
- notification.contentView = new RemoteViews(getApplicationContext().getPackageName(),
- R.layout.progressbar_layout);
- notification.contentView.setProgressBar(R.id.status_progress, mLocalPaths.length-1, 0, false);
- notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
-
- mNotificationManager.notify(42, notification);
-
- WebdavClient wc = new WebdavClient(ocUri);
- wc.setCredentials(username, password);
-
- for (int i = 0; i < mLocalPaths.length; ++i) {
- String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mLocalPaths[i].substring(mLocalPaths[i].lastIndexOf('.')+1));
- mResult = false;
- if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
- mResult |= true;
- }
- notification.contentView.setProgressBar(R.id.status_progress, mLocalPaths.length-1, i+1, false);
-
+ String baseUrl = mAccountManager.getUserData(mAccount,
+ AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
+ .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
+ OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
+ String webdav_path = AccountUtils.getWebdavPath(ocVer);
+ Uri ocUri = Uri.parse(baseUrl + webdav_path);
+ String username = mAccount.name.substring(0,
+ mAccount.name.lastIndexOf('@'));
+ String password = mAccountManager.getPassword(mAccount);
+ Notification notification = new Notification(
+ eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
+ System.currentTimeMillis());
+ notification.flags |= Notification.FLAG_ONGOING_EVENT;
+ notification.contentView = new RemoteViews(getApplicationContext()
+ .getPackageName(), R.layout.progressbar_layout);
+ notification.contentView.setProgressBar(R.id.status_progress,
+ mLocalPaths.length - 1, 0, false);
+ notification.contentView.setImageViewResource(R.id.status_icon,
+ R.drawable.icon);
+
mNotificationManager.notify(42, notification);
- }
- //notification.contentView.setProgressBar(R.id.status_progress, mLocalPaths.length-1, mLocalPaths.length-1, false);
- mNotificationManager.cancel(42);
- run();
+
+ WebdavClient wc = new WebdavClient(ocUri);
+ wc.setCredentials(username, password);
+
+ for (int i = 0; i < mLocalPaths.length; ++i) {
+ String mimeType = MimeTypeMap.getSingleton()
+ .getMimeTypeFromExtension(
+ mLocalPaths[i].substring(mLocalPaths[i]
+ .lastIndexOf('.') + 1));
+ mResult = false;
+ if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
+ mResult |= true;
+ }
+ notification.contentView.setProgressBar(R.id.status_progress,
+ mLocalPaths.length - 1, i + 1, false);
+
+ mNotificationManager.notify(42, notification);
+ }
+ // notification.contentView.setProgressBar(R.id.status_progress,
+ // mLocalPaths.length-1, mLocalPaths.length-1, false);
+ mNotificationManager.cancel(42);
+ run();
}
}
package eu.alefzero.owncloud.files.services;
public interface OnUploadCompletedListener extends Runnable {
-
- public boolean getUploadResult();
-
- public void setUploadResult(boolean result);
+
+ public boolean getUploadResult();
+
+ public void setUploadResult(boolean result);
}
public class LocationServiceLauncherReciever extends BroadcastReceiver {
- private final String TAG = getClass().getSimpleName();
-
- @Override
- public void onReceive(Context context, Intent intent) {
- Intent deviceTrackingIntent = new Intent();
- deviceTrackingIntent.setAction("eu.alefzero.owncloud.location.LocationUpdateService");
- SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
- boolean trackDevice = preferences.getBoolean("enable_devicetracking", true);
-
- // Used in Preferences activity so that tracking is disabled or reenabled
- if(intent.hasExtra("TRACKING_SETTING")){
- trackDevice = intent.getBooleanExtra("TRACKING_SETTING", true);
- }
-
- startOrStopDeviceTracking(context, trackDevice);
- }
-
- /**
- * Used internally. Starts or stops the device tracking service
- *
- * @param trackDevice
- * true to start the service, false to stop it
- */
- private void startOrStopDeviceTracking(Context context, boolean trackDevice) {
- Intent deviceTrackingIntent = new Intent();
- deviceTrackingIntent
- .setAction("eu.alefzero.owncloud.location.LocationUpdateService");
- if (!isDeviceTrackingServiceRunning(context) && trackDevice) {
- Log.d(TAG, "Starting device tracker service");
- context.startService(deviceTrackingIntent);
- } else if (isDeviceTrackingServiceRunning(context) && !trackDevice) {
- Log.d(TAG, "Stopping device tracker service");
- context.stopService(deviceTrackingIntent);
- }
- }
-
- /**
- * Checks to see whether or not the LocationUpdateService is running
- *
- * @return true, if it is. Otherwise false
- */
- private boolean isDeviceTrackingServiceRunning(Context context) {
- ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager
- .getRunningServices(Integer.MAX_VALUE)) {
- if (getClass().getName().equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
+ private final String TAG = getClass().getSimpleName();
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Intent deviceTrackingIntent = new Intent();
+ deviceTrackingIntent
+ .setAction("eu.alefzero.owncloud.location.LocationUpdateService");
+ SharedPreferences preferences = PreferenceManager
+ .getDefaultSharedPreferences(context);
+ boolean trackDevice = preferences.getBoolean("enable_devicetracking",
+ true);
+
+ // Used in Preferences activity so that tracking is disabled or
+ // reenabled
+ if (intent.hasExtra("TRACKING_SETTING")) {
+ trackDevice = intent.getBooleanExtra("TRACKING_SETTING", true);
+ }
+
+ startOrStopDeviceTracking(context, trackDevice);
+ }
+
+ /**
+ * Used internally. Starts or stops the device tracking service
+ *
+ * @param trackDevice
+ * true to start the service, false to stop it
+ */
+ private void startOrStopDeviceTracking(Context context, boolean trackDevice) {
+ Intent deviceTrackingIntent = new Intent();
+ deviceTrackingIntent
+ .setAction("eu.alefzero.owncloud.location.LocationUpdateService");
+ if (!isDeviceTrackingServiceRunning(context) && trackDevice) {
+ Log.d(TAG, "Starting device tracker service");
+ context.startService(deviceTrackingIntent);
+ } else if (isDeviceTrackingServiceRunning(context) && !trackDevice) {
+ Log.d(TAG, "Stopping device tracker service");
+ context.stopService(deviceTrackingIntent);
+ }
+ }
+
+ /**
+ * Checks to see whether or not the LocationUpdateService is running
+ *
+ * @return true, if it is. Otherwise false
+ */
+ private boolean isDeviceTrackingServiceRunning(Context context) {
+ ActivityManager manager = (ActivityManager) context
+ .getSystemService(Context.ACTIVITY_SERVICE);
+ for (RunningServiceInfo service : manager
+ .getRunningServices(Integer.MAX_VALUE)) {
+ if (getClass().getName().equals(service.service.getClassName())) {
+ return true;
+ }
+ }
+ return false;
+ }
}
import android.util.Log;
import android.widget.Toast;
-public class LocationUpdateService extends IntentService implements LocationListener {
-
- public static final String TAG = "LocationUpdateService";
-
- private LocationManager mLocationManager;
- private LocationProvider mLocationProvider;
- private SharedPreferences mPreferences;
-
- public LocationUpdateService() {
- super(TAG);
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
- // Determine, how we can track the device
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- criteria.setPowerRequirement(Criteria.POWER_LOW);
- mLocationProvider = mLocationManager.getProvider(mLocationManager.getBestProvider(criteria, true));
-
- // Notify user if there is no way to track the device
- if(mLocationProvider == null){
- Toast.makeText(this, eu.alefzero.owncloud.R.string.location_no_provider, Toast.LENGTH_LONG);
- stopSelf();
- return;
- }
-
- // Get preferences for device tracking
- mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
- boolean trackDevice = mPreferences.getBoolean("enable_devicetracking", true);
- int updateIntervall = Integer.parseInt(mPreferences.getString("devicetracking_update_intervall", "30")) * 60 * 1000;
- int distanceBetweenLocationChecks = 50;
-
- // If we do shall track the device -> Stop
- if(!trackDevice){
- Log.d(TAG, "Devicetracking is disabled");
- stopSelf();
- return;
- }
-
- mLocationManager.requestLocationUpdates(mLocationProvider.getName(), updateIntervall, distanceBetweenLocationChecks, this);
- }
-
- @Override
- public void onLocationChanged(Location location) {
- Log.d(TAG, "Location changed: " + location);
-
- }
-
- @Override
- public void onProviderDisabled(String arg0) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void onProviderEnabled(String arg0) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
- // TODO Auto-generated method stub
-
- }
+public class LocationUpdateService extends IntentService implements
+ LocationListener {
+ public static final String TAG = "LocationUpdateService";
+
+ private LocationManager mLocationManager;
+ private LocationProvider mLocationProvider;
+ private SharedPreferences mPreferences;
+
+ public LocationUpdateService() {
+ super(TAG);
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
+ // Determine, how we can track the device
+ Criteria criteria = new Criteria();
+ criteria.setAccuracy(Criteria.ACCURACY_FINE);
+ criteria.setPowerRequirement(Criteria.POWER_LOW);
+ mLocationProvider = mLocationManager.getProvider(mLocationManager
+ .getBestProvider(criteria, true));
+
+ // Notify user if there is no way to track the device
+ if (mLocationProvider == null) {
+ Toast.makeText(this,
+ eu.alefzero.owncloud.R.string.location_no_provider,
+ Toast.LENGTH_LONG);
+ stopSelf();
+ return;
+ }
+
+ // Get preferences for device tracking
+ mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
+ boolean trackDevice = mPreferences.getBoolean("enable_devicetracking",
+ true);
+ int updateIntervall = Integer.parseInt(mPreferences.getString(
+ "devicetracking_update_intervall", "30")) * 60 * 1000;
+ int distanceBetweenLocationChecks = 50;
+
+ // If we do shall track the device -> Stop
+ if (!trackDevice) {
+ Log.d(TAG, "Devicetracking is disabled");
+ stopSelf();
+ return;
+ }
+
+ mLocationManager.requestLocationUpdates(mLocationProvider.getName(),
+ updateIntervall, distanceBetweenLocationChecks, this);
+ }
+
+ @Override
+ public void onLocationChanged(Location location) {
+ Log.d(TAG, "Location changed: " + location);
+
+ }
+
+ @Override
+ public void onProviderDisabled(String arg0) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onProviderEnabled(String arg0) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
+ // TODO Auto-generated method stub
+
+ }
}
import android.text.TextUtils;\r
\r
/**\r
-* The ContentProvider for the ownCloud App.\r
-* @author Bartek Przybylski\r
-* \r
-*/\r
+ * The ContentProvider for the ownCloud App.\r
+ * \r
+ * @author Bartek Przybylski\r
+ * \r
+ */\r
public class FileContentProvider extends ContentProvider {\r
\r
- private DataBaseHelper mDbHelper;\r
- \r
- private static HashMap<String, String> mProjectionMap;\r
- static {\r
- mProjectionMap = new HashMap<String, String>();\r
- mProjectionMap.put(ProviderTableMeta._ID,\r
- ProviderTableMeta._ID);\r
- mProjectionMap.put(ProviderTableMeta.FILE_PARENT,\r
- ProviderTableMeta.FILE_PARENT);\r
- mProjectionMap.put(ProviderTableMeta.FILE_PATH,\r
- ProviderTableMeta.FILE_PATH);\r
- mProjectionMap.put(ProviderTableMeta.FILE_NAME,\r
- ProviderTableMeta.FILE_NAME);\r
- mProjectionMap.put(ProviderTableMeta.FILE_CREATION,\r
- ProviderTableMeta.FILE_CREATION);\r
- mProjectionMap.put(ProviderTableMeta.FILE_MODIFIED,\r
- ProviderTableMeta.FILE_MODIFIED);\r
- mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_LENGTH,\r
- ProviderTableMeta.FILE_CONTENT_LENGTH);\r
- mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_TYPE,\r
- ProviderTableMeta.FILE_CONTENT_TYPE);\r
- mProjectionMap.put(ProviderTableMeta.FILE_STORAGE_PATH,\r
- ProviderTableMeta.FILE_STORAGE_PATH);\r
- }\r
- \r
- private static final int SINGLE_FILE = 1;\r
- private static final int DIRECTORY = 2;\r
- private static final int ROOT_DIRECTORY = 3;\r
- private static final UriMatcher mUriMatcher;\r
- static {\r
- mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);\r
- mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "/", ROOT_DIRECTORY);\r
- mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/", SINGLE_FILE);\r
- mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/#", SINGLE_FILE);\r
- mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "dir/#", DIRECTORY);\r
- }\r
- \r
- @Override\r
- public int delete(Uri uri, String where, String[] whereArgs) {\r
- SQLiteDatabase db = mDbHelper.getWritableDatabase();\r
- int count = 0;\r
- switch (mUriMatcher.match(uri)) {\r
- case SINGLE_FILE:\r
- count = db.delete(ProviderTableMeta.DB_NAME,\r
- ProviderTableMeta._ID + "=" + uri.getPathSegments().get(1)\r
- + (!TextUtils.isEmpty(where)?" AND (" + where +")" : ""),\r
- whereArgs);\r
- break;\r
- case ROOT_DIRECTORY:\r
- count = db.delete(ProviderTableMeta.DB_NAME, where, whereArgs);\r
- break;\r
- default:\r
- throw new IllegalArgumentException("Unknown uri: " + uri.toString());\r
- }\r
- getContext().getContentResolver().notifyChange(uri, null);\r
- return count;\r
- }\r
-\r
- @Override\r
- public String getType(Uri uri) {\r
- switch (mUriMatcher.match(uri)) {\r
- case ROOT_DIRECTORY:\r
- return ProviderTableMeta.CONTENT_TYPE;\r
- case SINGLE_FILE:\r
- return ProviderTableMeta.CONTENT_TYPE_ITEM;\r
- default:\r
- throw new IllegalArgumentException("Unknown Uri id." + uri.toString());\r
+ private DataBaseHelper mDbHelper;\r
+\r
+ private static HashMap<String, String> mProjectionMap;\r
+ static {\r
+ mProjectionMap = new HashMap<String, String>();\r
+ mProjectionMap.put(ProviderTableMeta._ID, ProviderTableMeta._ID);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_PARENT,\r
+ ProviderTableMeta.FILE_PARENT);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_PATH,\r
+ ProviderTableMeta.FILE_PATH);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_NAME,\r
+ ProviderTableMeta.FILE_NAME);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_CREATION,\r
+ ProviderTableMeta.FILE_CREATION);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_MODIFIED,\r
+ ProviderTableMeta.FILE_MODIFIED);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_LENGTH,\r
+ ProviderTableMeta.FILE_CONTENT_LENGTH);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_CONTENT_TYPE,\r
+ ProviderTableMeta.FILE_CONTENT_TYPE);\r
+ mProjectionMap.put(ProviderTableMeta.FILE_STORAGE_PATH,\r
+ ProviderTableMeta.FILE_STORAGE_PATH);\r
}\r
- }\r
\r
- @Override\r
- public Uri insert(Uri uri, ContentValues values) {\r
- if (mUriMatcher.match(uri) != SINGLE_FILE) {\r
- throw new IllegalArgumentException("Unknown uri id: " + uri);\r
+ private static final int SINGLE_FILE = 1;\r
+ private static final int DIRECTORY = 2;\r
+ private static final int ROOT_DIRECTORY = 3;\r
+ private static final UriMatcher mUriMatcher;\r
+ static {\r
+ mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);\r
+ mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "/", ROOT_DIRECTORY);\r
+ mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/", SINGLE_FILE);\r
+ mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "file/#", SINGLE_FILE);\r
+ mUriMatcher.addURI(ProviderMeta.AUTHORITY_FILES, "dir/#", DIRECTORY);\r
}\r
- \r
- SQLiteDatabase db = mDbHelper.getWritableDatabase();\r
- long rowId = db.insert(ProviderTableMeta.DB_NAME, null, values);\r
- if (rowId > 0) {\r
- Uri insertedFileUri = ContentUris.withAppendedId(ProviderTableMeta.CONTENT_URI_FILE, rowId);\r
- getContext().getContentResolver().notifyChange(insertedFileUri, null);\r
- return insertedFileUri;\r
+\r
+ @Override\r
+ public int delete(Uri uri, String where, String[] whereArgs) {\r
+ SQLiteDatabase db = mDbHelper.getWritableDatabase();\r
+ int count = 0;\r
+ switch (mUriMatcher.match(uri)) {\r
+ case SINGLE_FILE:\r
+ count = db.delete(ProviderTableMeta.DB_NAME,\r
+ ProviderTableMeta._ID\r
+ + "="\r
+ + uri.getPathSegments().get(1)\r
+ + (!TextUtils.isEmpty(where) ? " AND (" + where\r
+ + ")" : ""), whereArgs);\r
+ break;\r
+ case ROOT_DIRECTORY:\r
+ count = db.delete(ProviderTableMeta.DB_NAME, where, whereArgs);\r
+ break;\r
+ default:\r
+ throw new IllegalArgumentException("Unknown uri: " + uri.toString());\r
+ }\r
+ getContext().getContentResolver().notifyChange(uri, null);\r
+ return count;\r
}\r
- throw new SQLException("ERROR " + uri);\r
- }\r
-\r
- @Override\r
- public boolean onCreate() {\r
- mDbHelper = new DataBaseHelper(getContext());\r
- return true;\r
- }\r
-\r
- @Override\r
- public Cursor query(Uri uri, String[] projection, String selection,\r
- String[] selectionArgs, String sortOrder) {\r
- SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();\r
- \r
- sqlQuery.setTables(ProviderTableMeta.DB_NAME);\r
- sqlQuery.setProjectionMap(mProjectionMap);\r
- \r
- switch (mUriMatcher.match(uri)) {\r
- case ROOT_DIRECTORY:\r
- break;\r
- case DIRECTORY:\r
- sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + "="+uri.getPathSegments().get(1));\r
- break;\r
- case SINGLE_FILE:\r
- if (uri.getPathSegments().size() > 1) {\r
- sqlQuery.appendWhere(ProviderTableMeta._ID + "=" +\r
- uri.getPathSegments().get(1));\r
+\r
+ @Override\r
+ public String getType(Uri uri) {\r
+ switch (mUriMatcher.match(uri)) {\r
+ case ROOT_DIRECTORY:\r
+ return ProviderTableMeta.CONTENT_TYPE;\r
+ case SINGLE_FILE:\r
+ return ProviderTableMeta.CONTENT_TYPE_ITEM;\r
+ default:\r
+ throw new IllegalArgumentException("Unknown Uri id."\r
+ + uri.toString());\r
}\r
- break;\r
- default:\r
- throw new IllegalArgumentException("Unknown uri id: " + uri);\r
}\r
- \r
- String order;\r
- if (TextUtils.isEmpty(sortOrder)) {\r
- order = ProviderTableMeta.DEFAULT_SORT_ORDER;\r
- } else {\r
- order = sortOrder;\r
+\r
+ @Override\r
+ public Uri insert(Uri uri, ContentValues values) {\r
+ if (mUriMatcher.match(uri) != SINGLE_FILE) {\r
+ throw new IllegalArgumentException("Unknown uri id: " + uri);\r
+ }\r
+\r
+ SQLiteDatabase db = mDbHelper.getWritableDatabase();\r
+ long rowId = db.insert(ProviderTableMeta.DB_NAME, null, values);\r
+ if (rowId > 0) {\r
+ Uri insertedFileUri = ContentUris.withAppendedId(\r
+ ProviderTableMeta.CONTENT_URI_FILE, rowId);\r
+ getContext().getContentResolver().notifyChange(insertedFileUri,\r
+ null);\r
+ return insertedFileUri;\r
+ }\r
+ throw new SQLException("ERROR " + uri);\r
}\r
- \r
- SQLiteDatabase db = mDbHelper.getReadableDatabase();\r
- Cursor c = sqlQuery.query(db, projection, selection, selectionArgs, null, null, order);\r
- \r
- c.setNotificationUri(getContext().getContentResolver(), uri);\r
-\r
- return c;\r
- }\r
-\r
- @Override\r
- public int update(Uri uri, ContentValues values, String selection,\r
- String[] selectionArgs) {\r
- return mDbHelper.getWritableDatabase().update(ProviderTableMeta.DB_NAME, values, selection, selectionArgs);\r
- }\r
-\r
- class DataBaseHelper extends SQLiteOpenHelper {\r
-\r
- public DataBaseHelper(Context context) {\r
- super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);\r
- \r
+\r
+ @Override\r
+ public boolean onCreate() {\r
+ mDbHelper = new DataBaseHelper(getContext());\r
+ return true;\r
}\r
- \r
+\r
@Override\r
- public void onCreate(SQLiteDatabase db) {\r
- db.execSQL("CREATE TABLE " + ProviderTableMeta.DB_NAME + "(" +\r
- ProviderTableMeta._ID + " INTEGER PRIMARY KEY, " +\r
- ProviderTableMeta.FILE_NAME + " TEXT, " +\r
- ProviderTableMeta.FILE_PATH + " TEXT, " +\r
- ProviderTableMeta.FILE_PARENT + " INTEGER, " +\r
- ProviderTableMeta.FILE_CREATION + " INTEGER, " +\r
- ProviderTableMeta.FILE_MODIFIED + " INTEGER, " +\r
- ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, " +\r
- ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, " +\r
- ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, " +\r
- ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT);");\r
+ public Cursor query(Uri uri, String[] projection, String selection,\r
+ String[] selectionArgs, String sortOrder) {\r
+ SQLiteQueryBuilder sqlQuery = new SQLiteQueryBuilder();\r
+\r
+ sqlQuery.setTables(ProviderTableMeta.DB_NAME);\r
+ sqlQuery.setProjectionMap(mProjectionMap);\r
+\r
+ switch (mUriMatcher.match(uri)) {\r
+ case ROOT_DIRECTORY:\r
+ break;\r
+ case DIRECTORY:\r
+ sqlQuery.appendWhere(ProviderTableMeta.FILE_PARENT + "="\r
+ + uri.getPathSegments().get(1));\r
+ break;\r
+ case SINGLE_FILE:\r
+ if (uri.getPathSegments().size() > 1) {\r
+ sqlQuery.appendWhere(ProviderTableMeta._ID + "="\r
+ + uri.getPathSegments().get(1));\r
+ }\r
+ break;\r
+ default:\r
+ throw new IllegalArgumentException("Unknown uri id: " + uri);\r
+ }\r
+\r
+ String order;\r
+ if (TextUtils.isEmpty(sortOrder)) {\r
+ order = ProviderTableMeta.DEFAULT_SORT_ORDER;\r
+ } else {\r
+ order = sortOrder;\r
+ }\r
+\r
+ SQLiteDatabase db = mDbHelper.getReadableDatabase();\r
+ Cursor c = sqlQuery.query(db, projection, selection, selectionArgs,\r
+ null, null, order);\r
+\r
+ c.setNotificationUri(getContext().getContentResolver(), uri);\r
+\r
+ return c;\r
}\r
\r
@Override\r
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r
- \r
+ public int update(Uri uri, ContentValues values, String selection,\r
+ String[] selectionArgs) {\r
+ return mDbHelper.getWritableDatabase().update(\r
+ ProviderTableMeta.DB_NAME, values, selection, selectionArgs);\r
+ }\r
+\r
+ class DataBaseHelper extends SQLiteOpenHelper {\r
+\r
+ public DataBaseHelper(Context context) {\r
+ super(context, ProviderMeta.DB_NAME, null, ProviderMeta.DB_VERSION);\r
+\r
+ }\r
+\r
+ @Override\r
+ public void onCreate(SQLiteDatabase db) {\r
+ db.execSQL("CREATE TABLE " + ProviderTableMeta.DB_NAME + "("\r
+ + ProviderTableMeta._ID + " INTEGER PRIMARY KEY, "\r
+ + ProviderTableMeta.FILE_NAME + " TEXT, "\r
+ + ProviderTableMeta.FILE_PATH + " TEXT, "\r
+ + ProviderTableMeta.FILE_PARENT + " INTEGER, "\r
+ + ProviderTableMeta.FILE_CREATION + " INTEGER, "\r
+ + ProviderTableMeta.FILE_MODIFIED + " INTEGER, "\r
+ + ProviderTableMeta.FILE_CONTENT_TYPE + " TEXT, "\r
+ + ProviderTableMeta.FILE_CONTENT_LENGTH + " INTEGER, "\r
+ + ProviderTableMeta.FILE_STORAGE_PATH + " TEXT, "\r
+ + ProviderTableMeta.FILE_ACCOUNT_OWNER + " TEXT);");\r
+ }\r
+\r
+ @Override\r
+ public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r
+\r
+ }\r
+\r
}\r
- \r
- }\r
- \r
+\r
}\r
* @author sassman\r
* \r
*/\r
-public abstract class AbstractOwnCloudSyncAdapter extends AbstractThreadedSyncAdapter {\r
-\r
- private AccountManager accountManager;\r
- private Account account;\r
- private ContentProviderClient contentProvider;\r
- private Date lastUpdated;\r
- private DataStorageManager mStoreManager;\r
-\r
- private WebdavClient mClient = null;\r
-\r
- public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {\r
- super(context, autoInitialize);\r
- this.setAccountManager(AccountManager.get(context));\r
- }\r
-\r
- public AccountManager getAccountManager() {\r
- return accountManager;\r
- }\r
-\r
- public void setAccountManager(AccountManager accountManager) {\r
- this.accountManager = accountManager;\r
- }\r
-\r
- public Account getAccount() {\r
- return account;\r
- }\r
-\r
- public void setAccount(Account account) {\r
- this.account = account;\r
- }\r
-\r
- public ContentProviderClient getContentProvider() {\r
- return contentProvider;\r
- }\r
-\r
- public void setContentProvider(ContentProviderClient contentProvider) {\r
- this.contentProvider = contentProvider;\r
- }\r
-\r
- public Date getLastUpdated() {\r
- return lastUpdated;\r
- }\r
-\r
- public void setLastUpdated(Date lastUpdated) {\r
- this.lastUpdated = lastUpdated;\r
- }\r
-\r
- public void setStorageManager(DataStorageManager storage_manager) {\r
- mStoreManager = storage_manager;\r
- }\r
- \r
- public DataStorageManager getStorageManager() {\r
- return mStoreManager;\r
- }\r
- \r
- protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {\r
- return new ConnectionKeepAliveStrategy() {\r
- public long getKeepAliveDuration(HttpResponse response,\r
- HttpContext context) {\r
- // Change keep alive straategy basing on response: ie\r
- // forbidden/not found/etc\r
- // should have keep alive 0\r
- // default return: 5s\r
- int statusCode = response.getStatusLine().getStatusCode();\r
-\r
- // HTTP 400, 500 Errors as well as HTTP 118 - Connection timed\r
- // out\r
- if ((statusCode >= 400 && statusCode <= 418)\r
- || (statusCode >= 421 && statusCode <= 426)\r
- || (statusCode >= 500 && statusCode <= 510)\r
- || statusCode == 118) {\r
- return 0;\r
- }\r
-\r
- return 5 * 1000;\r
- }\r
- };\r
- }\r
-\r
- protected HttpResponse fireRawRequest(HttpRequest query)\r
- throws ClientProtocolException, OperationCanceledException,\r
- AuthenticatorException, IOException {\r
- /*BasicHttpContext httpContext = new BasicHttpContext();\r
- BasicScheme basicAuth = new BasicScheme();\r
- httpContext.setAttribute("preemptive-auth", basicAuth);\r
-\r
- HttpResponse response = getClient().execute(mHost, query, httpContext);*/\r
- return null;\r
- }\r
-\r
- protected Uri getUri() {\r
- return Uri.parse(this.getAccountManager().getUserData(getAccount(),\r
- AccountAuthenticator.KEY_OC_URL));\r
- }\r
-\r
- protected WebdavClient getClient() throws OperationCanceledException,\r
- AuthenticatorException, IOException {\r
- if (mClient == null) {\r
- String username = getAccount().name.split("@")[0];\r
- String password = this.getAccountManager().blockingGetAuthToken(\r
- getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
- if (this.getAccountManager().getUserData(getAccount(),\r
- AccountAuthenticator.KEY_OC_URL) == null) {\r
- throw new UnknownHostException();\r
- }\r
- Uri uri = getUri();\r
-\r
- mClient = new WebdavClient(uri);\r
- mClient.setCredentials(username, password);\r
- mClient.allowUnsignedCertificates();\r
- //mHost = mClient.getTargetHost();\r
- }\r
-\r
- return mClient;\r
- }\r
+public abstract class AbstractOwnCloudSyncAdapter extends\r
+ AbstractThreadedSyncAdapter {\r
+\r
+ private AccountManager accountManager;\r
+ private Account account;\r
+ private ContentProviderClient contentProvider;\r
+ private Date lastUpdated;\r
+ private DataStorageManager mStoreManager;\r
+\r
+ private WebdavClient mClient = null;\r
+\r
+ public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) {\r
+ super(context, autoInitialize);\r
+ this.setAccountManager(AccountManager.get(context));\r
+ }\r
+\r
+ public AccountManager getAccountManager() {\r
+ return accountManager;\r
+ }\r
+\r
+ public void setAccountManager(AccountManager accountManager) {\r
+ this.accountManager = accountManager;\r
+ }\r
+\r
+ public Account getAccount() {\r
+ return account;\r
+ }\r
+\r
+ public void setAccount(Account account) {\r
+ this.account = account;\r
+ }\r
+\r
+ public ContentProviderClient getContentProvider() {\r
+ return contentProvider;\r
+ }\r
+\r
+ public void setContentProvider(ContentProviderClient contentProvider) {\r
+ this.contentProvider = contentProvider;\r
+ }\r
+\r
+ public Date getLastUpdated() {\r
+ return lastUpdated;\r
+ }\r
+\r
+ public void setLastUpdated(Date lastUpdated) {\r
+ this.lastUpdated = lastUpdated;\r
+ }\r
+\r
+ public void setStorageManager(DataStorageManager storage_manager) {\r
+ mStoreManager = storage_manager;\r
+ }\r
+\r
+ public DataStorageManager getStorageManager() {\r
+ return mStoreManager;\r
+ }\r
+\r
+ protected ConnectionKeepAliveStrategy getKeepAliveStrategy() {\r
+ return new ConnectionKeepAliveStrategy() {\r
+ public long getKeepAliveDuration(HttpResponse response,\r
+ HttpContext context) {\r
+ // Change keep alive straategy basing on response: ie\r
+ // forbidden/not found/etc\r
+ // should have keep alive 0\r
+ // default return: 5s\r
+ int statusCode = response.getStatusLine().getStatusCode();\r
+\r
+ // HTTP 400, 500 Errors as well as HTTP 118 - Connection timed\r
+ // out\r
+ if ((statusCode >= 400 && statusCode <= 418)\r
+ || (statusCode >= 421 && statusCode <= 426)\r
+ || (statusCode >= 500 && statusCode <= 510)\r
+ || statusCode == 118) {\r
+ return 0;\r
+ }\r
+\r
+ return 5 * 1000;\r
+ }\r
+ };\r
+ }\r
+\r
+ protected HttpResponse fireRawRequest(HttpRequest query)\r
+ throws ClientProtocolException, OperationCanceledException,\r
+ AuthenticatorException, IOException {\r
+ /*\r
+ * BasicHttpContext httpContext = new BasicHttpContext(); BasicScheme\r
+ * basicAuth = new BasicScheme();\r
+ * httpContext.setAttribute("preemptive-auth", basicAuth);\r
+ * \r
+ * HttpResponse response = getClient().execute(mHost, query,\r
+ * httpContext);\r
+ */\r
+ return null;\r
+ }\r
+\r
+ protected Uri getUri() {\r
+ return Uri.parse(this.getAccountManager().getUserData(getAccount(),\r
+ AccountAuthenticator.KEY_OC_URL));\r
+ }\r
+\r
+ protected WebdavClient getClient() throws OperationCanceledException,\r
+ AuthenticatorException, IOException {\r
+ if (mClient == null) {\r
+ String username = getAccount().name.split("@")[0];\r
+ String password = this.getAccountManager().blockingGetAuthToken(\r
+ getAccount(), AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
+ if (this.getAccountManager().getUserData(getAccount(),\r
+ AccountAuthenticator.KEY_OC_URL) == null) {\r
+ throw new UnknownHostException();\r
+ }\r
+ Uri uri = getUri();\r
+\r
+ mClient = new WebdavClient(uri);\r
+ mClient.setCredentials(username, password);\r
+ mClient.allowUnsignedCertificates();\r
+ // mHost = mClient.getTargetHost();\r
+ }\r
+\r
+ return mClient;\r
+ }\r
}
\ No newline at end of file
import android.util.Log;
public class ContactSyncAdapter extends AbstractOwnCloudSyncAdapter {
- private String mAddrBookUri;
-
- public ContactSyncAdapter(Context context, boolean autoInitialize) {
- super(context, autoInitialize);
- mAddrBookUri = null;
- }
+ private String mAddrBookUri;
- @Override
- public void onPerformSync(Account account, Bundle extras, String authority,
- ContentProviderClient provider, SyncResult syncResult) {
- setAccount(account);
- setContentProvider(provider);
- Cursor c = getLocalContacts(false);
- if (c.moveToFirst()) {
- do {
- String lookup = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
- String a = getAddressBookUri();
- String uri = a + lookup + ".vcf";
- FileInputStream f;
- try {
- f = getContactVcard(lookup);
- HttpPut query = new HttpPut(uri);
- byte[] b = new byte[f.available()];
- f.read(b);
- query.setEntity(new ByteArrayEntity(b));
- HttpResponse response = fireRawRequest(query);
- } catch (IOException e) {
- e.printStackTrace();
- return;
- } catch (OperationCanceledException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (AuthenticatorException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }while (c.moveToNext());
- //} while (c.moveToNext());
+ public ContactSyncAdapter(Context context, boolean autoInitialize) {
+ super(context, autoInitialize);
+ mAddrBookUri = null;
}
- }
+ @Override
+ public void onPerformSync(Account account, Bundle extras, String authority,
+ ContentProviderClient provider, SyncResult syncResult) {
+ setAccount(account);
+ setContentProvider(provider);
+ Cursor c = getLocalContacts(false);
+ if (c.moveToFirst()) {
+ do {
+ String lookup = c.getString(c
+ .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
+ String a = getAddressBookUri();
+ String uri = a + lookup + ".vcf";
+ FileInputStream f;
+ try {
+ f = getContactVcard(lookup);
+ HttpPut query = new HttpPut(uri);
+ byte[] b = new byte[f.available()];
+ f.read(b);
+ query.setEntity(new ByteArrayEntity(b));
+ HttpResponse response = fireRawRequest(query);
+ } catch (IOException e) {
+ e.printStackTrace();
+ return;
+ } catch (OperationCanceledException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (AuthenticatorException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ } while (c.moveToNext());
+ // } while (c.moveToNext());
+ }
- private String getAddressBookUri() {
- if (mAddrBookUri != null) return mAddrBookUri;
+ }
+
+ private String getAddressBookUri() {
+ if (mAddrBookUri != null)
+ return mAddrBookUri;
+
+ AccountManager am = getAccountManager();
+ String uri = am.getUserData(getAccount(),
+ AccountAuthenticator.KEY_OC_URL).replace(
+ AccountUtils.WEBDAV_PATH_2_0, AccountUtils.CARDDAV_PATH_2_0);
+ uri += "/addressbooks/"
+ + getAccount().name.substring(0,
+ getAccount().name.lastIndexOf('@')) + "/default/";
+ mAddrBookUri = uri;
+ return uri;
+ }
+
+ private FileInputStream getContactVcard(String lookupKey)
+ throws IOException {
+ Uri uri = Uri.withAppendedPath(
+ ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
+ AssetFileDescriptor fd = getContext().getContentResolver()
+ .openAssetFileDescriptor(uri, "r");
+ return fd.createInputStream();
+ }
+
+ private Cursor getLocalContacts(boolean include_hidden_contacts) {
+ return getContext().getContentResolver().query(
+ ContactsContract.Contacts.CONTENT_URI,
+ new String[] { ContactsContract.Contacts._ID,
+ ContactsContract.Contacts.LOOKUP_KEY },
+ ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?",
+ new String[] { (include_hidden_contacts ? "0" : "1") },
+ ContactsContract.Contacts._ID + " DESC");
+ }
- AccountManager am = getAccountManager();
- String uri = am.getUserData(getAccount(), AccountAuthenticator.KEY_OC_URL)
- .replace(AccountUtils.WEBDAV_PATH_2_0, AccountUtils.CARDDAV_PATH_2_0);
- uri += "/addressbooks/" + getAccount().name.substring(0, getAccount().name.lastIndexOf('@'))
- + "/default/";
- mAddrBookUri = uri;
- return uri;
- }
-
- private FileInputStream getContactVcard(String lookupKey) throws IOException {
- Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
- AssetFileDescriptor fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r");
- return fd.createInputStream();
- }
-
- private Cursor getLocalContacts(boolean include_hidden_contacts) {
- return getContext().getContentResolver().query(
- ContactsContract.Contacts.CONTENT_URI,
- new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.LOOKUP_KEY},
- ContactsContract.Contacts.IN_VISIBLE_GROUP + " = ?",
- new String[]{ (include_hidden_contacts?"0":"1")},
- ContactsContract.Contacts._ID + " DESC");
- }
-
}
import android.os.IBinder;
public class ContactSyncService extends Service {
- private static final Object syncAdapterLock = new Object();
- private static AbstractOwnCloudSyncAdapter mSyncAdapter = null;
-
- @Override
- public void onCreate() {
- synchronized (syncAdapterLock) {
- if (mSyncAdapter == null) {
- mSyncAdapter = new ContactSyncAdapter(getApplicationContext(), true);
- }
- }
- }
-
- @Override
- public IBinder onBind(Intent arg0) {
- return mSyncAdapter.getSyncAdapterBinder();
- }
+ private static final Object syncAdapterLock = new Object();
+ private static AbstractOwnCloudSyncAdapter mSyncAdapter = null;
+
+ @Override
+ public void onCreate() {
+ synchronized (syncAdapterLock) {
+ if (mSyncAdapter == null) {
+ mSyncAdapter = new ContactSyncAdapter(getApplicationContext(),
+ true);
+ }
+ }
+ }
+
+ @Override
+ public IBinder onBind(Intent arg0) {
+ return mSyncAdapter.getSyncAdapterBinder();
+ }
}
*/\r
public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {\r
\r
- public FileSyncAdapter(Context context, boolean autoInitialize) {\r
- super(context, autoInitialize);\r
- }\r
- \r
- @Override\r
- public synchronized void onPerformSync(\r
- Account account, \r
- Bundle extras, \r
- String authority, \r
- ContentProviderClient provider, \r
- SyncResult syncResult) {\r
+ public FileSyncAdapter(Context context, boolean autoInitialize) {\r
+ super(context, autoInitialize);\r
+ }\r
+\r
+ @Override\r
+ public synchronized void onPerformSync(Account account, Bundle extras,\r
+ String authority, ContentProviderClient provider,\r
+ SyncResult syncResult) {\r
+\r
+ this.setAccount(account);\r
+ this.setContentProvider(provider);\r
+ this.setStorageManager(new FileDataStorageManager(account,\r
+ getContentProvider()));\r
+\r
+ Log.d("ASD", "syncing owncloud account " + account.name);\r
+\r
+ Intent i = new Intent(FileSyncService.SYNC_MESSAGE);\r
+ i.putExtra(FileSyncService.IN_PROGRESS, true);\r
+ i.putExtra(FileSyncService.ACCOUNT_NAME, account.name);\r
+ getContext().sendStickyBroadcast(i);\r
\r
- this.setAccount(account);\r
- this.setContentProvider(provider);\r
- this.setStorageManager(new FileDataStorageManager(account, getContentProvider()));\r
+ PropFindMethod query;\r
+ try {\r
+ Log.e("ASD", getUri().toString());\r
+ query = new PropFindMethod(getUri().toString() + "/");\r
+ getClient().executeMethod(query);\r
+ MultiStatus resp = null;\r
+ resp = query.getResponseBodyAsMultiStatus();\r
\r
- Log.d("ASD", "syncing owncloud account " + account.name);\r
- \r
- Intent i = new Intent(FileSyncService.SYNC_MESSAGE);\r
- i.putExtra(FileSyncService.IN_PROGRESS, true);\r
- i.putExtra(FileSyncService.ACCOUNT_NAME, account.name);\r
- getContext().sendStickyBroadcast(i);\r
- \r
- PropFindMethod query;\r
- try {\r
- Log.e("ASD", getUri().toString());\r
- query = new PropFindMethod(getUri().toString()+"/");\r
- getClient().executeMethod(query);\r
- MultiStatus resp = null;\r
- resp = query.getResponseBodyAsMultiStatus();\r
- \r
- if (resp.getResponses().length > 0) {\r
- WebdavEntry we = new WebdavEntry(resp.getResponses()[0]);\r
- OCFile file = fillOCFile(we);\r
- file.setParentId(0);\r
- getStorageManager().saveFile(file);\r
- fetchData(getUri().toString(), syncResult, file.getFileId());\r
+ if (resp.getResponses().length > 0) {\r
+ WebdavEntry we = new WebdavEntry(resp.getResponses()[0]);\r
+ OCFile file = fillOCFile(we);\r
+ file.setParentId(0);\r
+ getStorageManager().saveFile(file);\r
+ fetchData(getUri().toString(), syncResult, file.getFileId());\r
+ }\r
+ } catch (OperationCanceledException e) {\r
+ e.printStackTrace();\r
+ } catch (AuthenticatorException e) {\r
+ syncResult.stats.numAuthExceptions++;\r
+ e.printStackTrace();\r
+ } catch (IOException e) {\r
+ syncResult.stats.numIoExceptions++;\r
+ e.printStackTrace();\r
+ } catch (DavException e) {\r
+ syncResult.stats.numIoExceptions++;\r
+ e.printStackTrace();\r
}\r
- } catch (OperationCanceledException e) {\r
- e.printStackTrace();\r
- } catch (AuthenticatorException e) {\r
- syncResult.stats.numAuthExceptions++;\r
- e.printStackTrace();\r
- } catch (IOException e) {\r
- syncResult.stats.numIoExceptions++;\r
- e.printStackTrace();\r
- } catch (DavException e) {\r
- syncResult.stats.numIoExceptions++;\r
- e.printStackTrace();\r
- }\r
- i.putExtra(FileSyncService.IN_PROGRESS, false);\r
- getContext().sendStickyBroadcast(i);\r
- }\r
+ i.putExtra(FileSyncService.IN_PROGRESS, false);\r
+ getContext().sendStickyBroadcast(i);\r
+ }\r
\r
- private void fetchData(String uri, SyncResult syncResult, long parentId) {\r
- try {\r
- PropFindMethod query = new PropFindMethod(uri);\r
- getClient().executeMethod(query);\r
- MultiStatus resp = null;\r
- resp = query.getResponseBodyAsMultiStatus();\r
- for (int i = 1; i < resp.getResponses().length; ++i) {\r
- WebdavEntry we = new WebdavEntry(resp.getResponses()[i]);\r
- OCFile file = fillOCFile(we);\r
- file.setParentId(parentId);\r
- getStorageManager().saveFile(file);\r
- if (parentId == 0) parentId = file.getFileId();\r
- if (we.contentType().equals("DIR"))\r
- fetchData(getUri().toString() + we.path(), syncResult, file.getFileId());\r
- }\r
- } catch (OperationCanceledException e) {\r
- e.printStackTrace();\r
- } catch (AuthenticatorException e) {\r
- syncResult.stats.numAuthExceptions++;\r
- e.printStackTrace();\r
- } catch (IOException e) {\r
- syncResult.stats.numIoExceptions++;\r
- e.printStackTrace();\r
- } catch (DavException e) {\r
- syncResult.stats.numIoExceptions++;\r
- e.printStackTrace();\r
+ private void fetchData(String uri, SyncResult syncResult, long parentId) {\r
+ try {\r
+ PropFindMethod query = new PropFindMethod(uri);\r
+ getClient().executeMethod(query);\r
+ MultiStatus resp = null;\r
+ resp = query.getResponseBodyAsMultiStatus();\r
+ for (int i = 1; i < resp.getResponses().length; ++i) {\r
+ WebdavEntry we = new WebdavEntry(resp.getResponses()[i]);\r
+ OCFile file = fillOCFile(we);\r
+ file.setParentId(parentId);\r
+ getStorageManager().saveFile(file);\r
+ if (parentId == 0)\r
+ parentId = file.getFileId();\r
+ if (we.contentType().equals("DIR"))\r
+ fetchData(getUri().toString() + we.path(), syncResult,\r
+ file.getFileId());\r
+ }\r
+ } catch (OperationCanceledException e) {\r
+ e.printStackTrace();\r
+ } catch (AuthenticatorException e) {\r
+ syncResult.stats.numAuthExceptions++;\r
+ e.printStackTrace();\r
+ } catch (IOException e) {\r
+ syncResult.stats.numIoExceptions++;\r
+ e.printStackTrace();\r
+ } catch (DavException e) {\r
+ syncResult.stats.numIoExceptions++;\r
+ e.printStackTrace();\r
+ }\r
}\r
- }\r
- \r
- private OCFile fillOCFile(WebdavEntry we) {\r
- OCFile file = new OCFile(we.path());\r
- file.setCreationTimestamp(we.createTimestamp());\r
- file.setFileLength(we.contentLength());\r
- file.setMimetype(we.contentType());\r
- file.setModificationTimestamp(we.modifiedTimesamp());\r
- return file;\r
- }\r
- \r
+\r
+ private OCFile fillOCFile(WebdavEntry we) {\r
+ OCFile file = new OCFile(we.path());\r
+ file.setCreationTimestamp(we.createTimestamp());\r
+ file.setFileLength(we.contentLength());\r
+ file.setMimetype(we.contentType());\r
+ file.setModificationTimestamp(we.modifiedTimesamp());\r
+ return file;\r
+ }\r
+\r
}\r
import android.os.IBinder;\r
\r
/**\r
- * Background service for syncing files to our\r
- * local Database\r
+ * Background service for syncing files to our local Database\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class FileSyncService extends Service {\r
- public static final String SYNC_MESSAGE = "eu.alefzero.owncloud.files.ACCOUNT_SYNC";\r
- public static final String IN_PROGRESS = "sync_in_progress";\r
- public static final String ACCOUNT_NAME = "account_name";\r
- \r
- private static final Object syncAdapterLock = new Object();\r
- private static AbstractOwnCloudSyncAdapter concretSyncAdapter = null;\r
+ public static final String SYNC_MESSAGE = "eu.alefzero.owncloud.files.ACCOUNT_SYNC";\r
+ public static final String IN_PROGRESS = "sync_in_progress";\r
+ public static final String ACCOUNT_NAME = "account_name";\r
+\r
+ private static final Object syncAdapterLock = new Object();\r
+ private static AbstractOwnCloudSyncAdapter concretSyncAdapter = null;\r
\r
- /*\r
- * {@inheritDoc}\r
- */\r
- @Override\r
- public void onCreate() {\r
- synchronized (syncAdapterLock) {\r
- if (concretSyncAdapter == null)\r
- concretSyncAdapter = new FileSyncAdapter(getApplicationContext(), true);\r
+ /*\r
+ * {@inheritDoc}\r
+ */\r
+ @Override\r
+ public void onCreate() {\r
+ synchronized (syncAdapterLock) {\r
+ if (concretSyncAdapter == null)\r
+ concretSyncAdapter = new FileSyncAdapter(\r
+ getApplicationContext(), true);\r
+ }\r
}\r
- }\r
\r
- /*\r
- * {@inheritDoc}\r
- */\r
- @Override\r
- public IBinder onBind(Intent intent) {\r
- return concretSyncAdapter.getSyncAdapterBinder();\r
- }\r
+ /*\r
+ * {@inheritDoc}\r
+ */\r
+ @Override\r
+ public IBinder onBind(Intent intent) {\r
+ return concretSyncAdapter.getSyncAdapterBinder();\r
+ }\r
}\r
import android.view.View.OnClickListener;\r
\r
/**\r
-* Represents an Item on the ActionBar.\r
-* @author Bartek Przybylski\r
-* \r
-*/\r
+ * Represents an Item on the ActionBar.\r
+ * \r
+ * @author Bartek Przybylski\r
+ * \r
+ */\r
public class ActionItem {\r
- private Drawable mIcon;\r
- private String mTitle;\r
- private OnClickListener mClickListener;\r
- \r
- public ActionItem() { }\r
- \r
- public void setTitle(String title) {\r
- mTitle = title;\r
- }\r
- \r
- public String getTitle() {\r
- return mTitle;\r
- }\r
- \r
- public void setIcon(Drawable icon) {\r
- mIcon = icon;\r
- }\r
- \r
- public Drawable getIcon() {\r
- return mIcon;\r
- }\r
- \r
- public void setOnClickListener(OnClickListener listener) {\r
- mClickListener = listener;\r
- }\r
- \r
- public OnClickListener getOnClickListerner() {\r
- return mClickListener;\r
- }\r
- \r
+ private Drawable mIcon;\r
+ private String mTitle;\r
+ private OnClickListener mClickListener;\r
+\r
+ public ActionItem() {\r
+ }\r
+\r
+ public void setTitle(String title) {\r
+ mTitle = title;\r
+ }\r
+\r
+ public String getTitle() {\r
+ return mTitle;\r
+ }\r
+\r
+ public void setIcon(Drawable icon) {\r
+ mIcon = icon;\r
+ }\r
+\r
+ public Drawable getIcon() {\r
+ return mIcon;\r
+ }\r
+\r
+ public void setOnClickListener(OnClickListener listener) {\r
+ mClickListener = listener;\r
+ }\r
+\r
+ public OnClickListener getOnClickListerner() {\r
+ return mClickListener;\r
+ }\r
+\r
}\r
\r
/**\r
* Represents a custom PopupWindows\r
+ * \r
* @author Lorensius. W. T\r
- *\r
+ * \r
*/\r
public class CustomPopup {\r
- protected final View mAnchor;\r
- protected final PopupWindow mWindow;\r
- private View root;\r
- private Drawable background = null;\r
- protected final WindowManager mWManager;\r
- \r
- public CustomPopup(View anchor) {\r
- mAnchor = anchor;\r
- mWindow = new PopupWindow(anchor.getContext());\r
- \r
- mWindow.setTouchInterceptor(new OnTouchListener() {\r
- \r
- public boolean onTouch(View v, MotionEvent event) {\r
- if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {\r
- CustomPopup.this.dismiss();\r
- return true;\r
+ protected final View mAnchor;\r
+ protected final PopupWindow mWindow;\r
+ private View root;\r
+ private Drawable background = null;\r
+ protected final WindowManager mWManager;\r
+\r
+ public CustomPopup(View anchor) {\r
+ mAnchor = anchor;\r
+ mWindow = new PopupWindow(anchor.getContext());\r
+\r
+ mWindow.setTouchInterceptor(new OnTouchListener() {\r
+\r
+ public boolean onTouch(View v, MotionEvent event) {\r
+ if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {\r
+ CustomPopup.this.dismiss();\r
+ return true;\r
+ }\r
+ return false;\r
+ }\r
+ });\r
+\r
+ mWManager = (WindowManager) anchor.getContext().getSystemService(\r
+ Context.WINDOW_SERVICE);\r
+ onCreate();\r
+ }\r
+\r
+ public void onCreate() {\r
+ }\r
+\r
+ public void onShow() {\r
+ }\r
+\r
+ public void preShow() {\r
+ if (root == null) {\r
+ throw new IllegalStateException(\r
+ "setContentView called with a view to display");\r
}\r
- return false;\r
- }\r
- });\r
- \r
- mWManager = (WindowManager) anchor.getContext().getSystemService(Context.WINDOW_SERVICE);\r
- onCreate();\r
- }\r
- \r
- \r
- public void onCreate() {}\r
- public void onShow() {}\r
- \r
- public void preShow() {\r
- if (root == null) {\r
- throw new IllegalStateException("setContentView called with a view to display");\r
+\r
+ onShow();\r
+\r
+ if (background == null) {\r
+ mWindow.setBackgroundDrawable(new BitmapDrawable());\r
+ } else {\r
+ mWindow.setBackgroundDrawable(background);\r
+ }\r
+\r
+ mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);\r
+ mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);\r
+ mWindow.setTouchable(true);\r
+ mWindow.setFocusable(true);\r
+ mWindow.setOutsideTouchable(true);\r
+\r
+ mWindow.setContentView(root);\r
+ }\r
+\r
+ public void setBackgroundDrawable(Drawable background) {\r
+ this.background = background;\r
+ }\r
+\r
+ public void setContentView(View root) {\r
+ this.root = root;\r
+ mWindow.setContentView(root);\r
+ }\r
+\r
+ public void setContentView(int layoutResId) {\r
+ LayoutInflater inflater = (LayoutInflater) mAnchor.getContext()\r
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\r
+ setContentView(inflater.inflate(layoutResId, null));\r
+ }\r
+\r
+ public void showDropDown() {\r
+ showDropDown(0, 0);\r
}\r
- \r
- onShow();\r
- \r
- if (background == null) {\r
- mWindow.setBackgroundDrawable(new BitmapDrawable());\r
- } else {\r
- mWindow.setBackgroundDrawable(background);\r
+\r
+ public void showDropDown(int x, int y) {\r
+ preShow();\r
+ mWindow.setAnimationStyle(android.R.style.Animation_Dialog);\r
+ mWindow.showAsDropDown(mAnchor, x, y);\r
}\r
- \r
- mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);\r
- mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);\r
- mWindow.setTouchable(true);\r
- mWindow.setFocusable(true);\r
- mWindow.setOutsideTouchable(true);\r
- \r
- mWindow.setContentView(root);\r
- }\r
- \r
- public void setBackgroundDrawable(Drawable background) {\r
- this.background = background;\r
- }\r
- \r
- public void setContentView(View root) {\r
- this.root = root;\r
- mWindow.setContentView(root);\r
- }\r
- \r
- public void setContentView(int layoutResId) {\r
- LayoutInflater inflater = \r
- (LayoutInflater) mAnchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\r
- setContentView(inflater.inflate(layoutResId, null));\r
- }\r
- \r
- public void showDropDown() {\r
- showDropDown(0, 0);\r
- }\r
- \r
- public void showDropDown(int x, int y) {\r
- preShow();\r
- mWindow.setAnimationStyle(android.R.style.Animation_Dialog);\r
- mWindow.showAsDropDown(mAnchor, x, y);\r
- }\r
- \r
- public void showLikeQuickAction() {\r
- showLikeQuickAction(0, 0);\r
- }\r
- \r
- public void showLikeQuickAction(int x, int y) {\r
- preShow();\r
- \r
- mWindow.setAnimationStyle(android.R.style.Animation_Dialog);\r
- int[] location = new int[2];\r
- mAnchor.getLocationOnScreen(location);\r
- \r
- Rect anchorRect = \r
- new Rect(location[0], location[1], location[0] + mAnchor.getWidth(), location[1] + mAnchor.getHeight());\r
- \r
- root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\r
- root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);\r
- \r
- int rootW = root.getWidth(), rootH = root.getHeight();\r
- int screenW = mWManager.getDefaultDisplay().getWidth();\r
- \r
- int xpos = ((screenW-rootW)/2) + x;\r
- int ypos = anchorRect.top - rootH + y;\r
- \r
- if (rootH > anchorRect.top) {\r
- ypos = anchorRect.bottom + y;\r
+\r
+ public void showLikeQuickAction() {\r
+ showLikeQuickAction(0, 0);\r
}\r
- mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xpos, ypos);\r
- }\r
- \r
- public void dismiss() {\r
- mWindow.dismiss();\r
- }\r
- \r
+\r
+ public void showLikeQuickAction(int x, int y) {\r
+ preShow();\r
+\r
+ mWindow.setAnimationStyle(android.R.style.Animation_Dialog);\r
+ int[] location = new int[2];\r
+ mAnchor.getLocationOnScreen(location);\r
+\r
+ Rect anchorRect = new Rect(location[0], location[1], location[0]\r
+ + mAnchor.getWidth(), location[1] + mAnchor.getHeight());\r
+\r
+ root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,\r
+ LayoutParams.WRAP_CONTENT));\r
+ root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);\r
+\r
+ int rootW = root.getWidth(), rootH = root.getHeight();\r
+ int screenW = mWManager.getDefaultDisplay().getWidth();\r
+\r
+ int xpos = ((screenW - rootW) / 2) + x;\r
+ int ypos = anchorRect.top - rootH + y;\r
+\r
+ if (rootH > anchorRect.top) {\r
+ ypos = anchorRect.bottom + y;\r
+ }\r
+ mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xpos, ypos);\r
+ }\r
+\r
+ public void dismiss() {\r
+ mWindow.dismiss();\r
+ }\r
+\r
}\r
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
-public class FragmentListView extends SherlockFragment
- implements OnItemClickListener,
- OnItemLongClickListener {
- ListView mList;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- mList = new ListView(getActivity());
- mList.setOnItemClickListener(this);
- mList.setOnItemLongClickListener(this);
- super.onCreate(savedInstanceState);
- }
-
- public void setListAdapter(ListAdapter listAdapter) {
- mList.setAdapter(listAdapter);
- mList.invalidate();
- }
-
- public ListView getListView() {
- return mList;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return mList;
- //return super.onCreateView(inflater, container, savedInstanceState);
- }
-
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {}
-
- @Override
- public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
- return false;
- }
-
-
-
+public class FragmentListView extends SherlockFragment implements
+ OnItemClickListener, OnItemLongClickListener {
+ ListView mList;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ mList = new ListView(getActivity());
+ mList.setOnItemClickListener(this);
+ mList.setOnItemLongClickListener(this);
+ super.onCreate(savedInstanceState);
+ }
+
+ public void setListAdapter(ListAdapter listAdapter) {
+ mList.setAdapter(listAdapter);
+ mList.invalidate();
+ }
+
+ public ListView getListView() {
+ return mList;
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ return mList;
+ // return super.onCreateView(inflater, container, savedInstanceState);
+ }
+
+ public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
+ }
+
+ @Override
+ public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
+ long arg3) {
+ return false;
+ }
+
}
import eu.alefzero.owncloud.R;\r
\r
/**\r
- * Popup window, shows action list as icon and text like the one in Gallery3D app. \r
+ * Popup window, shows action list as icon and text like the one in Gallery3D\r
+ * app.\r
* \r
* @author Lorensius. W. T\r
*/\r
public class QuickAction extends CustomPopup {\r
- private final View root;\r
- private final ImageView mArrowUp;\r
- private final ImageView mArrowDown;\r
- private final LayoutInflater inflater;\r
- private final Context context;\r
- \r
- protected static final int ANIM_GROW_FROM_LEFT = 1;\r
- protected static final int ANIM_GROW_FROM_RIGHT = 2;\r
- protected static final int ANIM_GROW_FROM_CENTER = 3;\r
- protected static final int ANIM_REFLECT = 4;\r
- protected static final int ANIM_AUTO = 5;\r
-\r
- private int animStyle;\r
- private ViewGroup mTrack;\r
- private ScrollView scroller;\r
- private ArrayList<ActionItem> actionList;\r
- \r
- /**\r
- * Constructor\r
- * \r
- * @param anchor {@link View} on where the popup window should be displayed\r
- */\r
- public QuickAction(View anchor) {\r
- super(anchor);\r
- \r
- actionList = new ArrayList<ActionItem>();\r
- context = anchor.getContext();\r
- inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\r
- \r
- root = (ViewGroup) inflater.inflate(R.layout.popup, null);\r
- \r
- mArrowDown = (ImageView) root.findViewById(R.id.arrow_down);\r
- mArrowUp = (ImageView) root.findViewById(R.id.arrow_up);\r
- \r
- setContentView(root);\r
- \r
- mTrack = (ViewGroup) root.findViewById(R.id.tracks);\r
- scroller = (ScrollView) root.findViewById(R.id.scroller);\r
- animStyle = ANIM_AUTO;\r
- }\r
-\r
- /**\r
- * Set animation style\r
- * \r
- * @param animStyle animation style, default is set to ANIM_AUTO\r
- */\r
- public void setAnimStyle(int animStyle) {\r
- this.animStyle = animStyle;\r
- }\r
-\r
- /**\r
- * Add action item\r
- * \r
- * @param action {@link ActionItem} object\r
- */\r
- public void addActionItem(ActionItem action) {\r
- actionList.add(action); \r
- }\r
- \r
- /**\r
- * Show popup window. Popup is automatically positioned, on top or bottom of anchor view.\r
- * \r
- */\r
- public void show () {\r
- preShow();\r
- \r
- int xPos, yPos;\r
- \r
- int[] location = new int[2];\r
- \r
- mAnchor.getLocationOnScreen(location);\r
-\r
- Rect anchorRect = new Rect(location[0], location[1], location[0] + mAnchor.getWidth(), location[1] \r
- + mAnchor.getHeight());\r
-\r
- createActionList();\r
- \r
- root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));\r
- root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);\r
- \r
- int rootHeight = root.getMeasuredHeight();\r
- int rootWidth = root.getMeasuredWidth();\r
- \r
- int screenWidth = mWManager.getDefaultDisplay().getWidth();\r
- int screenHeight = mWManager.getDefaultDisplay().getHeight();\r
- \r
- //automatically get X coord of popup (top left)\r
- if ((anchorRect.left + rootWidth) > screenWidth) {\r
- xPos = anchorRect.left - (rootWidth-mAnchor.getWidth());\r
- } else {\r
- if (mAnchor.getWidth() > rootWidth) {\r
- xPos = anchorRect.centerX() - (rootWidth/2);\r
- } else {\r
- xPos = anchorRect.left;\r
- }\r
- }\r
- \r
- int dyTop = anchorRect.top;\r
- int dyBottom = screenHeight - anchorRect.bottom;\r
-\r
- boolean onTop = (dyTop > dyBottom) ? true : false;\r
-\r
- if (onTop) {\r
- if (rootHeight > dyTop) {\r
- yPos = 15;\r
- LayoutParams l = scroller.getLayoutParams();\r
- l.height = dyTop - mAnchor.getHeight();\r
- } else {\r
- yPos = anchorRect.top - rootHeight;\r
- }\r
- } else {\r
- yPos = anchorRect.bottom;\r
- \r
- if (rootHeight > dyBottom) { \r
- LayoutParams l = scroller.getLayoutParams();\r
- l.height = dyBottom;\r
- }\r
- }\r
- \r
- showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), anchorRect.centerX()-xPos);\r
- \r
- setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);\r
- \r
- mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xPos, yPos);\r
- }\r
- \r
- /**\r
- * Set animation style\r
- * \r
- * @param screenWidth screen width\r
- * @param requestedX distance from left edge\r
- * @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor view\r
- * and vice versa\r
- */\r
- private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) {\r
- int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2;\r
-\r
- switch (animStyle) {\r
- case ANIM_GROW_FROM_LEFT:\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);\r
- break;\r
- \r
- case ANIM_GROW_FROM_RIGHT:\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);\r
- break;\r
- \r
- case ANIM_GROW_FROM_CENTER:\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);\r
- break;\r
- \r
- case ANIM_REFLECT:\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect : R.style.Animations_PopDownMenu_Reflect);\r
- break;\r
- \r
- case ANIM_AUTO:\r
- if (arrowPos <= screenWidth/4) {\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left);\r
- } else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) {\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center);\r
- } else {\r
- mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right);\r
- }\r
- \r
- break;\r
- }\r
- }\r
- \r
- /**\r
- * Create action list\r
- */\r
- private void createActionList() {\r
- View view;\r
- String title;\r
- Drawable icon;\r
- OnClickListener listener;\r
- \r
- for (int i = 0; i < actionList.size(); i++) {\r
- title = actionList.get(i).getTitle();\r
- icon = actionList.get(i).getIcon();\r
- listener = actionList.get(i).getOnClickListerner();\r
- \r
- view = getActionItem(title, icon, listener);\r
- \r
- view.setFocusable(true);\r
- view.setClickable(true);\r
- \r
- mTrack.addView(view);\r
- }\r
- }\r
- \r
- /**\r
- * Get action item {@link View}\r
- * \r
- * @param title action item title\r
- * @param icon {@link Drawable} action item icon\r
- * @param listener {@link View.OnClickListener} action item listener\r
- * @return action item {@link View}\r
- */\r
- private View getActionItem(String title, Drawable icon, OnClickListener listener) {\r
- LinearLayout container = (LinearLayout) inflater.inflate(R.layout.action_item, null);\r
- \r
- ImageView img = (ImageView) container.findViewById(R.id.icon);\r
- TextView text = (TextView) container.findViewById(R.id.title);\r
- \r
- if (icon != null) {\r
- img.setImageDrawable(icon);\r
- }\r
- \r
- if (title != null) { \r
- text.setText(title);\r
- }\r
- \r
- if (listener != null) {\r
- container.setOnClickListener(listener);\r
- }\r
-\r
- return container;\r
- }\r
- \r
- /**\r
- * Show arrow\r
- * \r
- * @param whichArrow arrow type resource id\r
- * @param requestedX distance from left screen\r
- */\r
- private void showArrow(int whichArrow, int requestedX) {\r
- final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown;\r
- final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp;\r
+ private final View root;\r
+ private final ImageView mArrowUp;\r
+ private final ImageView mArrowDown;\r
+ private final LayoutInflater inflater;\r
+ private final Context context;\r
+\r
+ protected static final int ANIM_GROW_FROM_LEFT = 1;\r
+ protected static final int ANIM_GROW_FROM_RIGHT = 2;\r
+ protected static final int ANIM_GROW_FROM_CENTER = 3;\r
+ protected static final int ANIM_REFLECT = 4;\r
+ protected static final int ANIM_AUTO = 5;\r
+\r
+ private int animStyle;\r
+ private ViewGroup mTrack;\r
+ private ScrollView scroller;\r
+ private ArrayList<ActionItem> actionList;\r
+\r
+ /**\r
+ * Constructor\r
+ * \r
+ * @param anchor\r
+ * {@link View} on where the popup window should be displayed\r
+ */\r
+ public QuickAction(View anchor) {\r
+ super(anchor);\r
+\r
+ actionList = new ArrayList<ActionItem>();\r
+ context = anchor.getContext();\r
+ inflater = (LayoutInflater) context\r
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\r
+\r
+ root = (ViewGroup) inflater.inflate(R.layout.popup, null);\r
+\r
+ mArrowDown = (ImageView) root.findViewById(R.id.arrow_down);\r
+ mArrowUp = (ImageView) root.findViewById(R.id.arrow_up);\r
+\r
+ setContentView(root);\r
+\r
+ mTrack = (ViewGroup) root.findViewById(R.id.tracks);\r
+ scroller = (ScrollView) root.findViewById(R.id.scroller);\r
+ animStyle = ANIM_AUTO;\r
+ }\r
+\r
+ /**\r
+ * Set animation style\r
+ * \r
+ * @param animStyle\r
+ * animation style, default is set to ANIM_AUTO\r
+ */\r
+ public void setAnimStyle(int animStyle) {\r
+ this.animStyle = animStyle;\r
+ }\r
+\r
+ /**\r
+ * Add action item\r
+ * \r
+ * @param action\r
+ * {@link ActionItem} object\r
+ */\r
+ public void addActionItem(ActionItem action) {\r
+ actionList.add(action);\r
+ }\r
+\r
+ /**\r
+ * Show popup window. Popup is automatically positioned, on top or bottom of\r
+ * anchor view.\r
+ * \r
+ */\r
+ public void show() {\r
+ preShow();\r
+\r
+ int xPos, yPos;\r
+\r
+ int[] location = new int[2];\r
+\r
+ mAnchor.getLocationOnScreen(location);\r
+\r
+ Rect anchorRect = new Rect(location[0], location[1], location[0]\r
+ + mAnchor.getWidth(), location[1] + mAnchor.getHeight());\r
+\r
+ createActionList();\r
+\r
+ root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,\r
+ LayoutParams.WRAP_CONTENT));\r
+ root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);\r
+\r
+ int rootHeight = root.getMeasuredHeight();\r
+ int rootWidth = root.getMeasuredWidth();\r
+\r
+ int screenWidth = mWManager.getDefaultDisplay().getWidth();\r
+ int screenHeight = mWManager.getDefaultDisplay().getHeight();\r
+\r
+ // automatically get X coord of popup (top left)\r
+ if ((anchorRect.left + rootWidth) > screenWidth) {\r
+ xPos = anchorRect.left - (rootWidth - mAnchor.getWidth());\r
+ } else {\r
+ if (mAnchor.getWidth() > rootWidth) {\r
+ xPos = anchorRect.centerX() - (rootWidth / 2);\r
+ } else {\r
+ xPos = anchorRect.left;\r
+ }\r
+ }\r
+\r
+ int dyTop = anchorRect.top;\r
+ int dyBottom = screenHeight - anchorRect.bottom;\r
+\r
+ boolean onTop = (dyTop > dyBottom) ? true : false;\r
+\r
+ if (onTop) {\r
+ if (rootHeight > dyTop) {\r
+ yPos = 15;\r
+ LayoutParams l = scroller.getLayoutParams();\r
+ l.height = dyTop - mAnchor.getHeight();\r
+ } else {\r
+ yPos = anchorRect.top - rootHeight;\r
+ }\r
+ } else {\r
+ yPos = anchorRect.bottom;\r
+\r
+ if (rootHeight > dyBottom) {\r
+ LayoutParams l = scroller.getLayoutParams();\r
+ l.height = dyBottom;\r
+ }\r
+ }\r
+\r
+ showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up),\r
+ anchorRect.centerX() - xPos);\r
+\r
+ setAnimationStyle(screenWidth, anchorRect.centerX(), onTop);\r
+\r
+ mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xPos, yPos);\r
+ }\r
+\r
+ /**\r
+ * Set animation style\r
+ * \r
+ * @param screenWidth\r
+ * screen width\r
+ * @param requestedX\r
+ * distance from left edge\r
+ * @param onTop\r
+ * flag to indicate where the popup should be displayed. Set TRUE\r
+ * if displayed on top of anchor view and vice versa\r
+ */\r
+ private void setAnimationStyle(int screenWidth, int requestedX,\r
+ boolean onTop) {\r
+ int arrowPos = requestedX - mArrowUp.getMeasuredWidth() / 2;\r
+\r
+ switch (animStyle) {\r
+ case ANIM_GROW_FROM_LEFT:\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left\r
+ : R.style.Animations_PopDownMenu_Left);\r
+ break;\r
+\r
+ case ANIM_GROW_FROM_RIGHT:\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right\r
+ : R.style.Animations_PopDownMenu_Right);\r
+ break;\r
+\r
+ case ANIM_GROW_FROM_CENTER:\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center\r
+ : R.style.Animations_PopDownMenu_Center);\r
+ break;\r
+\r
+ case ANIM_REFLECT:\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Reflect\r
+ : R.style.Animations_PopDownMenu_Reflect);\r
+ break;\r
+\r
+ case ANIM_AUTO:\r
+ if (arrowPos <= screenWidth / 4) {\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left\r
+ : R.style.Animations_PopDownMenu_Left);\r
+ } else if (arrowPos > screenWidth / 4\r
+ && arrowPos < 3 * (screenWidth / 4)) {\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center\r
+ : R.style.Animations_PopDownMenu_Center);\r
+ } else {\r
+ mWindow.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right\r
+ : R.style.Animations_PopDownMenu_Right);\r
+ }\r
+\r
+ break;\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Create action list\r
+ */\r
+ private void createActionList() {\r
+ View view;\r
+ String title;\r
+ Drawable icon;\r
+ OnClickListener listener;\r
+\r
+ for (int i = 0; i < actionList.size(); i++) {\r
+ title = actionList.get(i).getTitle();\r
+ icon = actionList.get(i).getIcon();\r
+ listener = actionList.get(i).getOnClickListerner();\r
+\r
+ view = getActionItem(title, icon, listener);\r
+\r
+ view.setFocusable(true);\r
+ view.setClickable(true);\r
+\r
+ mTrack.addView(view);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Get action item {@link View}\r
+ * \r
+ * @param title\r
+ * action item title\r
+ * @param icon\r
+ * {@link Drawable} action item icon\r
+ * @param listener\r
+ * {@link View.OnClickListener} action item listener\r
+ * @return action item {@link View}\r
+ */\r
+ private View getActionItem(String title, Drawable icon,\r
+ OnClickListener listener) {\r
+ LinearLayout container = (LinearLayout) inflater.inflate(\r
+ R.layout.action_item, null);\r
+\r
+ ImageView img = (ImageView) container.findViewById(R.id.icon);\r
+ TextView text = (TextView) container.findViewById(R.id.title);\r
+\r
+ if (icon != null) {\r
+ img.setImageDrawable(icon);\r
+ }\r
+\r
+ if (title != null) {\r
+ text.setText(title);\r
+ }\r
+\r
+ if (listener != null) {\r
+ container.setOnClickListener(listener);\r
+ }\r
+\r
+ return container;\r
+ }\r
+\r
+ /**\r
+ * Show arrow\r
+ * \r
+ * @param whichArrow\r
+ * arrow type resource id\r
+ * @param requestedX\r
+ * distance from left screen\r
+ */\r
+ private void showArrow(int whichArrow, int requestedX) {\r
+ final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp\r
+ : mArrowDown;\r
+ final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown\r
+ : mArrowUp;\r
\r
final int arrowWidth = mArrowUp.getMeasuredWidth();\r
\r
showArrow.setVisibility(View.VISIBLE);\r
- \r
- ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams();\r
- \r
+\r
+ ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams) showArrow\r
+ .getLayoutParams();\r
+\r
param.leftMargin = requestedX - arrowWidth / 2;\r
- \r
+\r
hideArrow.setVisibility(View.INVISIBLE);\r
}\r
}
\ No newline at end of file
import eu.alefzero.owncloud.AccountUtils;
import eu.alefzero.owncloud.R;
-public class AccountSelectActivity extends SherlockListActivity
- implements AccountManagerCallback<Boolean> {
-
- private final Handler mHandler = new Handler();
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- ActionBar action_bar = getSupportActionBar();
- action_bar.setDisplayShowTitleEnabled(true);
- action_bar.setDisplayHomeAsUpEnabled(false);
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- populateAccountList();
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getSherlock().getMenuInflater();
- inflater.inflate(eu.alefzero.owncloud.R.menu.account_picker, menu);
- return true;
- }
-
- @Override
- public void onCreateContextMenu(ContextMenu menu, View v,
- ContextMenuInfo menuInfo) {
- getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
- super.onCreateContextMenu(menu, v, menuInfo);
- }
-
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) {
- String accountName = ((TextView)v.findViewById(android.R.id.text1)).getText().toString();
- AccountUtils.setCurrentOwnCloudAccount(this, accountName);
- Intent i = new Intent(this, FileDisplayActivity.class);
- startActivity(i);
- finish();
- }
-
- @Override
- public boolean onMenuItemSelected(int featureId, MenuItem item) {
- if (item.getItemId() == R.id.createAccount) {
- Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
- intent.putExtra("authorities",
- new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
- startActivity(intent);
- return true;
+public class AccountSelectActivity extends SherlockListActivity implements
+ AccountManagerCallback<Boolean> {
+
+ private final Handler mHandler = new Handler();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ ActionBar action_bar = getSupportActionBar();
+ action_bar.setDisplayShowTitleEnabled(true);
+ action_bar.setDisplayHomeAsUpEnabled(false);
}
- return false;
- }
-
- @Override
- public boolean onContextItemSelected(android.view.MenuItem item) {
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
- int index = info.position;
- HashMap<String, String> map = (HashMap<String, String>)getListAdapter().getItem(index);
- String accountName = map.get("NAME");
- AccountManager am = (AccountManager)getSystemService(ACCOUNT_SERVICE);
- Account accounts[] = am.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
- for (Account a : accounts) {
- if (a.name.equals(accountName)) {
- am.removeAccount(a, this, mHandler);
- }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ populateAccountList();
}
-
- return false;
- }
-
-
- private void populateAccountList() {
- AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
- Account accounts[] = am.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
- LinkedList< HashMap<String, String>> ll = new LinkedList<HashMap<String,String>>();
- for (Account a : accounts) {
- HashMap<String, String> h = new HashMap<String, String>();
- h.put("NAME", a.name);
- h.put("VER", "ownCloud version: " + am.getUserData(a, AccountAuthenticator.KEY_OC_VERSION));
- ll.add(h);
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ MenuInflater inflater = getSherlock().getMenuInflater();
+ inflater.inflate(eu.alefzero.owncloud.R.menu.account_picker, menu);
+ return true;
}
-
- setListAdapter(new AccountCheckedSimpleAdepter(this,
- ll,
- android.R.layout.simple_list_item_single_choice,
- new String[]{"NAME"},
- new int[]{android.R.id.text1}));
- registerForContextMenu(getListView());
- }
-
- @Override
- public void run(AccountManagerFuture<Boolean> future) {
- if (future.isDone()) {
- Account a = AccountUtils.getCurrentOwnCloudAccount(this);
- String accountName = "";
- if (a == null) {
- Account[] accounts = AccountManager.get(this).getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
- if (accounts.length != 0)
- accountName = accounts[0].name;
+
+ @Override
+ public void onCreateContextMenu(ContextMenu menu, View v,
+ ContextMenuInfo menuInfo) {
+ getMenuInflater().inflate(R.menu.account_picker_long_click, menu);
+ super.onCreateContextMenu(menu, v, menuInfo);
+ }
+
+ @Override
+ protected void onListItemClick(ListView l, View v, int position, long id) {
+ String accountName = ((TextView) v.findViewById(android.R.id.text1))
+ .getText().toString();
AccountUtils.setCurrentOwnCloudAccount(this, accountName);
- }
- populateAccountList();
+ Intent i = new Intent(this, FileDisplayActivity.class);
+ startActivity(i);
+ finish();
+ }
+
+ @Override
+ public boolean onMenuItemSelected(int featureId, MenuItem item) {
+ if (item.getItemId() == R.id.createAccount) {
+ Intent intent = new Intent(
+ android.provider.Settings.ACTION_ADD_ACCOUNT);
+ intent.putExtra("authorities",
+ new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
+ startActivity(intent);
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public boolean onContextItemSelected(android.view.MenuItem item) {
+ AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
+ .getMenuInfo();
+ int index = info.position;
+ HashMap<String, String> map = (HashMap<String, String>) getListAdapter()
+ .getItem(index);
+ String accountName = map.get("NAME");
+ AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
+ Account accounts[] = am
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+ for (Account a : accounts) {
+ if (a.name.equals(accountName)) {
+ am.removeAccount(a, this, mHandler);
+ }
+ }
+
+ return false;
}
- }
-
- private class AccountCheckedSimpleAdepter extends SimpleAdapter {
- private Account mCurrentAccount;
- private List<? extends Map<String, ?>> mPrivateData;
-
- public AccountCheckedSimpleAdepter(Context context,
- List<? extends Map<String, ?>> data,
- int resource,
- String[] from,
- int[] to) {
- super(context, data, resource, from, to);
- mCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(AccountSelectActivity.this);
- mPrivateData = data;
+
+ private void populateAccountList() {
+ AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
+ Account accounts[] = am
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+ LinkedList<HashMap<String, String>> ll = new LinkedList<HashMap<String, String>>();
+ for (Account a : accounts) {
+ HashMap<String, String> h = new HashMap<String, String>();
+ h.put("NAME", a.name);
+ h.put("VER",
+ "ownCloud version: "
+ + am.getUserData(a,
+ AccountAuthenticator.KEY_OC_VERSION));
+ ll.add(h);
+ }
+
+ setListAdapter(new AccountCheckedSimpleAdepter(this, ll,
+ android.R.layout.simple_list_item_single_choice,
+ new String[] { "NAME" }, new int[] { android.R.id.text1 }));
+ registerForContextMenu(getListView());
}
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- View v = super.getView(position, convertView, parent);
- CheckedTextView ctv = (CheckedTextView) v.findViewById(android.R.id.text1);
- if (mPrivateData.get(position).get("NAME").equals(mCurrentAccount.name)) {
- ctv.setChecked(true);
+
+ @Override
+ public void run(AccountManagerFuture<Boolean> future) {
+ if (future.isDone()) {
+ Account a = AccountUtils.getCurrentOwnCloudAccount(this);
+ String accountName = "";
+ if (a == null) {
+ Account[] accounts = AccountManager.get(this)
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
+ if (accounts.length != 0)
+ accountName = accounts[0].name;
+ AccountUtils.setCurrentOwnCloudAccount(this, accountName);
+ }
+ populateAccountList();
+ }
}
- return v;
- }
-
-
- }
-}
+ private class AccountCheckedSimpleAdepter extends SimpleAdapter {
+ private Account mCurrentAccount;
+ private List<? extends Map<String, ?>> mPrivateData;
+ public AccountCheckedSimpleAdepter(Context context,
+ List<? extends Map<String, ?>> data, int resource,
+ String[] from, int[] to) {
+ super(context, data, resource, from, to);
+ mCurrentAccount = AccountUtils
+ .getCurrentOwnCloudAccount(AccountSelectActivity.this);
+ mPrivateData = data;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ View v = super.getView(position, convertView, parent);
+ CheckedTextView ctv = (CheckedTextView) v
+ .findViewById(android.R.id.text1);
+ if (mPrivateData.get(position).get("NAME")
+ .equals(mCurrentAccount.name)) {
+ ctv.setChecked(true);
+ }
+ return v;
+ }
+
+ }
+
+}
* \r
*/\r
public class AuthenticatorActivity extends AccountAuthenticatorActivity\r
- implements OnAuthenticationResultListener,\r
- OnConnectCheckListener,\r
- OnFocusChangeListener,\r
- OnClickListener {\r
- private static final int DIALOG_LOGIN_PROGRESS = 0;\r
- \r
- private static final String TAG = "AuthActivity";\r
-\r
- private Thread mAuthThread;\r
- private AuthenticationRunnable mAuthRunnable;\r
- private ConnectionCheckerRunnable mConnChkRunnable;\r
- private final Handler mHandler = new Handler();\r
- private String mBaseUrl;\r
- \r
- private static final String STATUS_TEXT = "STATUS_TEXT"; \r
- private static final String STATUS_ICON = "STATUS_ICON";\r
- private static final String STATUS_CORRECT = "STATUS_CORRECT";\r
- private static final String IS_SSL_CONN = "IS_SSL_CONN";\r
- private int mStatusText, mStatusIcon;\r
- private boolean mStatusCorrect, mIsSslConn;\r
-\r
- public static final String PARAM_USERNAME = "param_Username";\r
- public static final String PARAM_HOSTNAME = "param_Hostname";\r
-\r
- @Override\r
- protected void onCreate(Bundle savedInstanceState) {\r
- super.onCreate(savedInstanceState);\r
- getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
- setContentView(R.layout.account_setup);\r
- ImageView iv = (ImageView) findViewById(R.id.refreshButton);\r
- ImageView iv2 = (ImageView) findViewById(R.id.viewPassword);\r
- TextView tv = (TextView) findViewById(R.id.host_URL);\r
- TextView tv2 = (TextView) findViewById(R.id.account_password);\r
- \r
- if (savedInstanceState != null) {\r
- mStatusIcon = savedInstanceState.getInt(STATUS_ICON);\r
- mStatusText = savedInstanceState.getInt(STATUS_TEXT);\r
- mStatusCorrect = savedInstanceState.getBoolean(STATUS_CORRECT);\r
- mIsSslConn = savedInstanceState.getBoolean(IS_SSL_CONN);\r
- setResultIconAndText(mStatusIcon, mStatusText);\r
- findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);\r
- if (!mStatusCorrect)\r
- iv.setVisibility(View.VISIBLE);\r
- else\r
- iv.setVisibility(View.INVISIBLE);\r
- \r
- } else {\r
- mStatusText = mStatusIcon = 0;\r
- mStatusCorrect = false;\r
- mIsSslConn = false;\r
+ implements OnAuthenticationResultListener, OnConnectCheckListener,\r
+ OnFocusChangeListener, OnClickListener {\r
+ private static final int DIALOG_LOGIN_PROGRESS = 0;\r
+\r
+ private static final String TAG = "AuthActivity";\r
+\r
+ private Thread mAuthThread;\r
+ private AuthenticationRunnable mAuthRunnable;\r
+ private ConnectionCheckerRunnable mConnChkRunnable;\r
+ private final Handler mHandler = new Handler();\r
+ private String mBaseUrl;\r
+\r
+ private static final String STATUS_TEXT = "STATUS_TEXT";\r
+ private static final String STATUS_ICON = "STATUS_ICON";\r
+ private static final String STATUS_CORRECT = "STATUS_CORRECT";\r
+ private static final String IS_SSL_CONN = "IS_SSL_CONN";\r
+ private int mStatusText, mStatusIcon;\r
+ private boolean mStatusCorrect, mIsSslConn;\r
+\r
+ public static final String PARAM_USERNAME = "param_Username";\r
+ public static final String PARAM_HOSTNAME = "param_Hostname";\r
+\r
+ @Override\r
+ protected void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
+ setContentView(R.layout.account_setup);\r
+ ImageView iv = (ImageView) findViewById(R.id.refreshButton);\r
+ ImageView iv2 = (ImageView) findViewById(R.id.viewPassword);\r
+ TextView tv = (TextView) findViewById(R.id.host_URL);\r
+ TextView tv2 = (TextView) findViewById(R.id.account_password);\r
+\r
+ if (savedInstanceState != null) {\r
+ mStatusIcon = savedInstanceState.getInt(STATUS_ICON);\r
+ mStatusText = savedInstanceState.getInt(STATUS_TEXT);\r
+ mStatusCorrect = savedInstanceState.getBoolean(STATUS_CORRECT);\r
+ mIsSslConn = savedInstanceState.getBoolean(IS_SSL_CONN);\r
+ setResultIconAndText(mStatusIcon, mStatusText);\r
+ findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);\r
+ if (!mStatusCorrect)\r
+ iv.setVisibility(View.VISIBLE);\r
+ else\r
+ iv.setVisibility(View.INVISIBLE);\r
+\r
+ } else {\r
+ mStatusText = mStatusIcon = 0;\r
+ mStatusCorrect = false;\r
+ mIsSslConn = false;\r
+ }\r
+ iv.setOnClickListener(this);\r
+ iv2.setOnClickListener(this);\r
+ tv.setOnFocusChangeListener(this);\r
+ tv2.setOnFocusChangeListener(this);\r
}\r
- iv.setOnClickListener(this);\r
- iv2.setOnClickListener(this);\r
- tv.setOnFocusChangeListener(this);\r
- tv2.setOnFocusChangeListener(this);\r
- }\r
-\r
- @Override\r
- protected void onSaveInstanceState(Bundle outState) {\r
- outState.putInt(STATUS_ICON, mStatusIcon);\r
- outState.putInt(STATUS_TEXT, mStatusText);\r
- outState.putBoolean(STATUS_CORRECT, mStatusCorrect);\r
- super.onSaveInstanceState(outState);\r
- }\r
-\r
- @Override\r
- protected Dialog onCreateDialog(int id) {\r
- Dialog dialog = null;\r
- switch (id) {\r
- case DIALOG_LOGIN_PROGRESS : {\r
- ProgressDialog working_dialog = new ProgressDialog(this);\r
- working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));\r
- working_dialog.setIndeterminate(true);\r
- working_dialog.setCancelable(true);\r
- working_dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {\r
- @Override\r
- public void onCancel(DialogInterface dialog) {\r
- Log.i(TAG, "Login canceled");\r
- if (mAuthThread != null) {\r
- mAuthThread.interrupt();\r
- finish();\r
- }\r
- }\r
- });\r
- dialog = working_dialog;\r
- break;\r
- }\r
- default :\r
- Log.e(TAG, "Incorrect dialog called with id = " + id);\r
+\r
+ @Override\r
+ protected void onSaveInstanceState(Bundle outState) {\r
+ outState.putInt(STATUS_ICON, mStatusIcon);\r
+ outState.putInt(STATUS_TEXT, mStatusText);\r
+ outState.putBoolean(STATUS_CORRECT, mStatusCorrect);\r
+ super.onSaveInstanceState(outState);\r
}\r
- return dialog;\r
- }\r
-\r
- public void onAuthenticationResult(boolean success, String message) {\r
- if (success) {\r
- TextView username_text = (TextView) findViewById(R.id.account_username), password_text = (TextView) findViewById(R.id.account_password);\r
-\r
- URL url;\r
- try {\r
- url = new URL(message);\r
- } catch (MalformedURLException e) {\r
- // should never happen\r
- Log.e(getClass().getName(), "Malformed URL: " + message);\r
- return;\r
- }\r
-\r
- String username = username_text.getText().toString().trim();\r
- String accountName = username + "@" + url.getHost();\r
- Account account = new Account(accountName,\r
- AccountAuthenticator.ACCOUNT_TYPE);\r
- AccountManager accManager = AccountManager.get(this);\r
- accManager.addAccountExplicitly(account, password_text.getText()\r
- .toString(), null);\r
-\r
- // Add this account as default in the preferences, if there is none\r
- // already\r
- Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
- if (defaultAccount == null) {\r
- SharedPreferences.Editor editor = PreferenceManager\r
- .getDefaultSharedPreferences(this).edit();\r
- editor.putString("select_oc_account", accountName);\r
- editor.commit();\r
- }\r
-\r
- final Intent intent = new Intent();\r
- intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);\r
- intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);\r
- intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE);\r
- intent.putExtra(AccountManager.KEY_USERDATA, username);\r
-\r
- accManager.setUserData(account,\r
- AccountAuthenticator.KEY_OC_URL,\r
- url.toString());\r
- accManager.setUserData(account,\r
- AccountAuthenticator.KEY_OC_VERSION,\r
- mConnChkRunnable.getDiscoveredVersion().toString());\r
- accManager.setUserData(account,\r
- AccountAuthenticator.KEY_OC_BASE_URL,\r
- mBaseUrl);\r
-\r
- setAccountAuthenticatorResult(intent.getExtras());\r
- setResult(RESULT_OK, intent);\r
- Bundle bundle = new Bundle();\r
- bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
- getContentResolver().startSync(ProviderTableMeta.CONTENT_URI, bundle);\r
-\r
- /*if (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion.owncloud_v2) >= 0) {\r
- Intent i = new Intent(this, ExtensionsAvailableActivity.class);\r
- startActivity(i);\r
- }*/\r
-\r
- finish();\r
- } else {\r
- dismissDialog(DIALOG_LOGIN_PROGRESS);\r
- TextView tv = (TextView) findViewById(R.id.account_username);\r
- tv.setError(message);\r
+\r
+ @Override\r
+ protected Dialog onCreateDialog(int id) {\r
+ Dialog dialog = null;\r
+ switch (id) {\r
+ case DIALOG_LOGIN_PROGRESS: {\r
+ ProgressDialog working_dialog = new ProgressDialog(this);\r
+ working_dialog.setMessage(getResources().getString(\r
+ R.string.auth_trying_to_login));\r
+ working_dialog.setIndeterminate(true);\r
+ working_dialog.setCancelable(true);\r
+ working_dialog\r
+ .setOnCancelListener(new DialogInterface.OnCancelListener() {\r
+ @Override\r
+ public void onCancel(DialogInterface dialog) {\r
+ Log.i(TAG, "Login canceled");\r
+ if (mAuthThread != null) {\r
+ mAuthThread.interrupt();\r
+ finish();\r
+ }\r
+ }\r
+ });\r
+ dialog = working_dialog;\r
+ break;\r
+ }\r
+ default:\r
+ Log.e(TAG, "Incorrect dialog called with id = " + id);\r
+ }\r
+ return dialog;\r
}\r
- }\r
-\r
- public void onOkClick(View view) {\r
- String prefix = "";\r
- String url = ((TextView) findViewById(R.id.host_URL)).getText().toString();\r
- if (mIsSslConn) {\r
- prefix = "https://";\r
- } else {\r
- prefix = "http://";\r
+\r
+ public void onAuthenticationResult(boolean success, String message) {\r
+ if (success) {\r
+ TextView username_text = (TextView) findViewById(R.id.account_username), password_text = (TextView) findViewById(R.id.account_password);\r
+\r
+ URL url;\r
+ try {\r
+ url = new URL(message);\r
+ } catch (MalformedURLException e) {\r
+ // should never happen\r
+ Log.e(getClass().getName(), "Malformed URL: " + message);\r
+ return;\r
+ }\r
+\r
+ String username = username_text.getText().toString().trim();\r
+ String accountName = username + "@" + url.getHost();\r
+ Account account = new Account(accountName,\r
+ AccountAuthenticator.ACCOUNT_TYPE);\r
+ AccountManager accManager = AccountManager.get(this);\r
+ accManager.addAccountExplicitly(account, password_text.getText()\r
+ .toString(), null);\r
+\r
+ // Add this account as default in the preferences, if there is none\r
+ // already\r
+ Account defaultAccount = AccountUtils\r
+ .getCurrentOwnCloudAccount(this);\r
+ if (defaultAccount == null) {\r
+ SharedPreferences.Editor editor = PreferenceManager\r
+ .getDefaultSharedPreferences(this).edit();\r
+ editor.putString("select_oc_account", accountName);\r
+ editor.commit();\r
+ }\r
+\r
+ final Intent intent = new Intent();\r
+ intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,\r
+ AccountAuthenticator.ACCOUNT_TYPE);\r
+ intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);\r
+ intent.putExtra(AccountManager.KEY_AUTHTOKEN,\r
+ AccountAuthenticator.ACCOUNT_TYPE);\r
+ intent.putExtra(AccountManager.KEY_USERDATA, username);\r
+\r
+ accManager.setUserData(account, AccountAuthenticator.KEY_OC_URL,\r
+ url.toString());\r
+ accManager.setUserData(account,\r
+ AccountAuthenticator.KEY_OC_VERSION, mConnChkRunnable\r
+ .getDiscoveredVersion().toString());\r
+ accManager.setUserData(account,\r
+ AccountAuthenticator.KEY_OC_BASE_URL, mBaseUrl);\r
+\r
+ setAccountAuthenticatorResult(intent.getExtras());\r
+ setResult(RESULT_OK, intent);\r
+ Bundle bundle = new Bundle();\r
+ bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+ getContentResolver().startSync(ProviderTableMeta.CONTENT_URI,\r
+ bundle);\r
+\r
+ /*\r
+ * if\r
+ * (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion\r
+ * .owncloud_v2) >= 0) { Intent i = new Intent(this,\r
+ * ExtensionsAvailableActivity.class); startActivity(i); }\r
+ */\r
+\r
+ finish();\r
+ } else {\r
+ dismissDialog(DIALOG_LOGIN_PROGRESS);\r
+ TextView tv = (TextView) findViewById(R.id.account_username);\r
+ tv.setError(message);\r
+ }\r
}\r
- if (url.toLowerCase().startsWith("http://") || url.toLowerCase().startsWith("https://")) {\r
- prefix = "";\r
+\r
+ public void onOkClick(View view) {\r
+ String prefix = "";\r
+ String url = ((TextView) findViewById(R.id.host_URL)).getText()\r
+ .toString();\r
+ if (mIsSslConn) {\r
+ prefix = "https://";\r
+ } else {\r
+ prefix = "http://";\r
+ }\r
+ if (url.toLowerCase().startsWith("http://")\r
+ || url.toLowerCase().startsWith("https://")) {\r
+ prefix = "";\r
+ }\r
+ continueConnection(prefix);\r
}\r
- continueConnection(prefix);\r
- }\r
- \r
- private void continueConnection(String prefix) {\r
- String url = ((TextView) findViewById(R.id.host_URL)).getText().toString();\r
- String username = ((TextView) findViewById(R.id.account_username)).getText().toString();\r
- String password = ((TextView) findViewById(R.id.account_password)).getText().toString();\r
- if (url.endsWith("/"))\r
- url = url.substring(0, url.length()-1);\r
-\r
- URL uri = null;\r
- String webdav_path = AccountUtils.getWebdavPath(mConnChkRunnable.getDiscoveredVersion());\r
-\r
- try {\r
- mBaseUrl = prefix + url;\r
- String url_str = prefix + url + webdav_path;\r
- uri = new URL(url_str);\r
- } catch (MalformedURLException e) {\r
- // should not happend\r
- e.printStackTrace();\r
+\r
+ private void continueConnection(String prefix) {\r
+ String url = ((TextView) findViewById(R.id.host_URL)).getText()\r
+ .toString();\r
+ String username = ((TextView) findViewById(R.id.account_username))\r
+ .getText().toString();\r
+ String password = ((TextView) findViewById(R.id.account_password))\r
+ .getText().toString();\r
+ if (url.endsWith("/"))\r
+ url = url.substring(0, url.length() - 1);\r
+\r
+ URL uri = null;\r
+ String webdav_path = AccountUtils.getWebdavPath(mConnChkRunnable\r
+ .getDiscoveredVersion());\r
+\r
+ try {\r
+ mBaseUrl = prefix + url;\r
+ String url_str = prefix + url + webdav_path;\r
+ uri = new URL(url_str);\r
+ } catch (MalformedURLException e) {\r
+ // should not happend\r
+ e.printStackTrace();\r
+ }\r
+\r
+ showDialog(DIALOG_LOGIN_PROGRESS);\r
+ mAuthRunnable = new AuthenticationRunnable(uri, username, password);\r
+ mAuthRunnable.setOnAuthenticationResultListener(this, mHandler);\r
+ mAuthThread = new Thread(mAuthRunnable);\r
+ mAuthThread.start();\r
}\r
\r
- showDialog(DIALOG_LOGIN_PROGRESS);\r
- mAuthRunnable = new AuthenticationRunnable(uri, username, password);\r
- mAuthRunnable.setOnAuthenticationResultListener(this, mHandler);\r
- mAuthThread = new Thread(mAuthRunnable);\r
- mAuthThread.start();\r
- }\r
- \r
- @Override\r
- public void onConnectionCheckResult(ResultType type) {\r
- mStatusText = mStatusIcon = 0;\r
- mStatusCorrect = false;\r
- String t_url = ((TextView) findViewById(R.id.host_URL)).getText().toString().toLowerCase();\r
-\r
- switch (type) {\r
- case OK:\r
- // ugly as hell\r
- if (t_url.startsWith("http://") || t_url.startsWith("https://")) {\r
- mIsSslConn = t_url.startsWith("http://") ? false : true;\r
- mStatusIcon = R.drawable.ic_ok;\r
- mStatusText = R.string.auth_connection_established;\r
- mStatusCorrect = true;\r
- } else {\r
- mIsSslConn = true;\r
- mStatusIcon = android.R.drawable.ic_secure;\r
- mStatusText = R.string.auth_secure_connection;\r
- mStatusCorrect = true; \r
+ @Override\r
+ public void onConnectionCheckResult(ResultType type) {\r
+ mStatusText = mStatusIcon = 0;\r
+ mStatusCorrect = false;\r
+ String t_url = ((TextView) findViewById(R.id.host_URL)).getText()\r
+ .toString().toLowerCase();\r
+\r
+ switch (type) {\r
+ case OK:\r
+ // ugly as hell\r
+ if (t_url.startsWith("http://") || t_url.startsWith("https://")) {\r
+ mIsSslConn = t_url.startsWith("http://") ? false : true;\r
+ mStatusIcon = R.drawable.ic_ok;\r
+ mStatusText = R.string.auth_connection_established;\r
+ mStatusCorrect = true;\r
+ } else {\r
+ mIsSslConn = true;\r
+ mStatusIcon = android.R.drawable.ic_secure;\r
+ mStatusText = R.string.auth_secure_connection;\r
+ mStatusCorrect = true;\r
+ }\r
+ break;\r
+ case OK_NO_SSL:\r
+ mStatusIcon = android.R.drawable.ic_secure;\r
+ mStatusText = R.string.auth_nossl_plain_ok_title;\r
+ mStatusCorrect = true;\r
+ mIsSslConn = false;\r
+ break;\r
+ case TIMEOUT:\r
+ case INORRECT_ADDRESS:\r
+ case SSL_INIT_ERROR:\r
+ case HOST_NOT_AVAILABLE:\r
+ mStatusIcon = R.drawable.common_error;\r
+ mStatusText = R.string.auth_unknow_host_title;\r
+ break;\r
+ case NO_NETWORK_CONNECTION:\r
+ mStatusIcon = R.drawable.no_network;\r
+ mStatusText = R.string.auth_no_net_conn_title;\r
+ break;\r
+ case INSTANCE_NOT_CONFIGURED:\r
+ mStatusIcon = R.drawable.common_error;\r
+ mStatusText = R.string.auth_not_configured_title;\r
+ break;\r
+ case UNKNOWN_ERROR:\r
+ mStatusIcon = R.drawable.common_error;\r
+ mStatusText = R.string.auth_unknow_error;\r
+ break;\r
+ case FILE_NOT_FOUND:\r
+ mStatusIcon = R.drawable.common_error;\r
+ mStatusText = R.string.auth_incorrect_path_title;\r
+ break;\r
+ default:\r
+ Log.e(TAG, "Incorrect connection checker result type: " + type);\r
}\r
- break;\r
- case OK_NO_SSL:\r
- mStatusIcon = android.R.drawable.ic_secure;\r
- mStatusText = R.string.auth_nossl_plain_ok_title;\r
- mStatusCorrect = true;\r
- mIsSslConn = false;\r
- break;\r
- case TIMEOUT:\r
- case INORRECT_ADDRESS:\r
- case SSL_INIT_ERROR:\r
- case HOST_NOT_AVAILABLE:\r
- mStatusIcon = R.drawable.common_error;\r
- mStatusText = R.string.auth_unknow_host_title;\r
- break;\r
- case NO_NETWORK_CONNECTION:\r
- mStatusIcon = R.drawable.no_network;\r
- mStatusText = R.string.auth_no_net_conn_title;\r
- break;\r
- case INSTANCE_NOT_CONFIGURED:\r
- mStatusIcon = R.drawable.common_error;\r
- mStatusText = R.string.auth_not_configured_title;\r
- break;\r
- case UNKNOWN_ERROR:\r
- mStatusIcon = R.drawable.common_error;\r
- mStatusText = R.string.auth_unknow_error;\r
- break;\r
- case FILE_NOT_FOUND:\r
- mStatusIcon = R.drawable.common_error;\r
- mStatusText = R.string.auth_incorrect_path_title;\r
- break;\r
- default:\r
- Log.e(TAG, "Incorrect connection checker result type: " + type);\r
+ setResultIconAndText(mStatusIcon, mStatusText);\r
+ if (!mStatusCorrect)\r
+ findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);\r
+ else\r
+ findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);\r
+ findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);\r
}\r
- setResultIconAndText(mStatusIcon, mStatusText);\r
- if (!mStatusCorrect)\r
- findViewById(R.id.refreshButton).setVisibility(View.VISIBLE);\r
- else\r
- findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);\r
- findViewById(R.id.buttonOK).setEnabled(mStatusCorrect);\r
- }\r
-\r
- @Override\r
- public void onFocusChange(View view, boolean hasFocus) {\r
- if (view.getId() == R.id.host_URL) {\r
- if (!hasFocus) {\r
- TextView tv = ((TextView)findViewById(R.id.host_URL));\r
- String uri = tv.getText().toString();\r
- if (uri.length() != 0) {\r
- setResultIconAndText(R.drawable.progress_small, R.string.auth_testing_connection);\r
- mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);\r
- mConnChkRunnable.setListener(this, mHandler);\r
- mAuthThread = new Thread(mConnChkRunnable);\r
- mAuthThread.start();\r
- } else {\r
- findViewById(R.id.refreshButton).setVisibility(View.INVISIBLE);\r
- setResultIconAndText(0, 0);\r
+\r
+ @Override\r
+ public void onFocusChange(View view, boolean hasFocus) {\r
+ if (view.getId() == R.id.host_URL) {\r
+ if (!hasFocus) {\r
+ TextView tv = ((TextView) findViewById(R.id.host_URL));\r
+ String uri = tv.getText().toString();\r
+ if (uri.length() != 0) {\r
+ setResultIconAndText(R.drawable.progress_small,\r
+ R.string.auth_testing_connection);\r
+ mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);\r
+ mConnChkRunnable.setListener(this, mHandler);\r
+ mAuthThread = new Thread(mConnChkRunnable);\r
+ mAuthThread.start();\r
+ } else {\r
+ findViewById(R.id.refreshButton).setVisibility(\r
+ View.INVISIBLE);\r
+ setResultIconAndText(0, 0);\r
+ }\r
+ }\r
+ } else if (view.getId() == R.id.account_password) {\r
+ ImageView iv = (ImageView) findViewById(R.id.viewPassword);\r
+ if (hasFocus) {\r
+ iv.setVisibility(View.VISIBLE);\r
+ } else {\r
+ TextView v = (TextView) findViewById(R.id.account_password);\r
+ int input_type = InputType.TYPE_CLASS_TEXT\r
+ | InputType.TYPE_TEXT_VARIATION_PASSWORD;\r
+ v.setInputType(input_type);\r
+ iv.setVisibility(View.INVISIBLE);\r
+ }\r
}\r
- }\r
- } else if (view.getId() == R.id.account_password) {\r
- ImageView iv = (ImageView) findViewById(R.id.viewPassword);\r
- if (hasFocus) {\r
- iv.setVisibility(View.VISIBLE);\r
- } else {\r
- TextView v = (TextView) findViewById(R.id.account_password);\r
- int input_type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD; \r
- v.setInputType(input_type);\r
- iv.setVisibility(View.INVISIBLE);\r
- }\r
}\r
- }\r
- \r
- private void setResultIconAndText(int drawable_id, int text_id) {\r
- ImageView iv = (ImageView) findViewById(R.id.action_indicator);\r
- TextView tv = (TextView) findViewById(R.id.status_text);\r
- \r
- if (drawable_id == 0 && text_id == 0) {\r
- iv.setVisibility(View.INVISIBLE);\r
- tv.setVisibility(View.INVISIBLE);\r
- } else {\r
- iv.setImageResource(drawable_id);\r
- tv.setText(text_id);\r
- iv.setVisibility(View.VISIBLE);\r
- tv.setVisibility(View.VISIBLE);\r
+\r
+ private void setResultIconAndText(int drawable_id, int text_id) {\r
+ ImageView iv = (ImageView) findViewById(R.id.action_indicator);\r
+ TextView tv = (TextView) findViewById(R.id.status_text);\r
+\r
+ if (drawable_id == 0 && text_id == 0) {\r
+ iv.setVisibility(View.INVISIBLE);\r
+ tv.setVisibility(View.INVISIBLE);\r
+ } else {\r
+ iv.setImageResource(drawable_id);\r
+ tv.setText(text_id);\r
+ iv.setVisibility(View.VISIBLE);\r
+ tv.setVisibility(View.VISIBLE);\r
+ }\r
}\r
- }\r
-\r
- @Override\r
- public void onClick(View v) {\r
- if (v.getId() == R.id.refreshButton) {\r
- onFocusChange(findViewById(R.id.host_URL), false);\r
- } else if (v.getId() == R.id.viewPassword) {\r
- TextView view = (TextView) findViewById(R.id.account_password);\r
- int input_type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;\r
- view.setInputType(input_type);\r
+\r
+ @Override\r
+ public void onClick(View v) {\r
+ if (v.getId() == R.id.refreshButton) {\r
+ onFocusChange(findViewById(R.id.host_URL), false);\r
+ } else if (v.getId() == R.id.viewPassword) {\r
+ TextView view = (TextView) findViewById(R.id.account_password);\r
+ int input_type = InputType.TYPE_CLASS_TEXT\r
+ | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;\r
+ view.setInputType(input_type);\r
+ }\r
}\r
- }\r
}\r
*/\r
package eu.alefzero.owncloud.ui.activity;\r
\r
-\r
import android.os.Bundle;\r
import android.support.v4.app.FragmentTransaction;\r
import android.view.Window;\r
import eu.alefzero.owncloud.ui.fragment.FileDetailFragment;\r
\r
/**\r
- * This activity displays the details of a file like\r
- * its name, its size and so on.\r
+ * This activity displays the details of a file like its name, its size and so\r
+ * on.\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class FileDetailActivity extends SherlockFragmentActivity {\r
- private FileDetailFragment mFileDetail;\r
- \r
-@Override\r
-protected void onCreate(Bundle savedInstanceState) {\r
- // TODO Auto-generated method stub\r
- super.onCreate(savedInstanceState);\r
- getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
- setContentView(R.layout.file_activity_details);\r
- \r
- mFileDetail = new FileDetailFragment();\r
- FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\r
- ft.add(R.id.fileDetail, mFileDetail);\r
- ft.commit();\r
- \r
-}\r
+ private FileDetailFragment mFileDetail;\r
+\r
+ @Override\r
+ protected void onCreate(Bundle savedInstanceState) {\r
+ // TODO Auto-generated method stub\r
+ super.onCreate(savedInstanceState);\r
+ getWindow().requestFeature(Window.FEATURE_NO_TITLE);\r
+ setContentView(R.layout.file_activity_details);\r
+\r
+ mFileDetail = new FileDetailFragment();\r
+ FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\r
+ ft.add(R.id.fileDetail, mFileDetail);\r
+ ft.commit();\r
+\r
+ }\r
\r
}\r
*/\r
\r
public class FileDisplayActivity extends SherlockFragmentActivity implements\r
- OnNavigationListener, OnClickListener {\r
- private ArrayAdapter<String> mDirectories;\r
- private DataStorageManager mStorageManager;\r
-\r
- private SyncBroadcastReceiver syncBroadcastRevceiver;\r
- \r
- private static final int DIALOG_SETUP_ACCOUNT = 0;\r
- private static final int DIALOG_CREATE_DIR = 1;\r
- \r
- private static final int REQUEST_ACCOUNT_SETUP = 0;\r
- private static final int ACTION_SELECT_FILE = 1;\r
-\r
- public void pushPath(String path) {\r
- mDirectories.insert(path, 0);\r
- }\r
-\r
- public boolean popPath() {\r
- mDirectories.remove(mDirectories.getItem(0));\r
- return !mDirectories.isEmpty();\r
- }\r
-\r
- @Override\r
- protected Dialog onCreateDialog(int id) {\r
- Dialog dialog;\r
- AlertDialog.Builder builder;\r
- switch(id){\r
- case DIALOG_SETUP_ACCOUNT:\r
- builder = new AlertDialog.Builder(this);\r
- builder.setTitle(R.string.main_tit_accsetup);\r
- builder.setMessage(R.string.main_wrn_accsetup);\r
- builder.setCancelable(false);\r
- builder.setPositiveButton(android.R.string.ok, this);\r
- builder.setNegativeButton(android.R.string.cancel, this);\r
- dialog = builder.create();\r
- break;\r
- case DIALOG_CREATE_DIR:\r
- {\r
- builder = new Builder(this);\r
- final EditText dirName = new EditText(getBaseContext());\r
- final Account a = AccountUtils.getCurrentOwnCloudAccount(this);\r
- builder.setView(dirName);\r
- builder.setTitle(R.string.uploader_info_dirname);\r
- int typed_color = getResources().getColor(R.color.setup_text_typed);\r
- dirName.setTextColor(typed_color);\r
-\r
- builder.setPositiveButton(android.R.string.ok, new OnClickListener() {\r
- public void onClick(DialogInterface dialog, int which) {\r
- String s = dirName.getText().toString();\r
- if (s.trim().length() == 0) {\r
- dialog.cancel();\r
+ OnNavigationListener, OnClickListener {\r
+ private ArrayAdapter<String> mDirectories;\r
+ private DataStorageManager mStorageManager;\r
+\r
+ private SyncBroadcastReceiver syncBroadcastRevceiver;\r
+\r
+ private static final int DIALOG_SETUP_ACCOUNT = 0;\r
+ private static final int DIALOG_CREATE_DIR = 1;\r
+\r
+ private static final int REQUEST_ACCOUNT_SETUP = 0;\r
+ private static final int ACTION_SELECT_FILE = 1;\r
+\r
+ public void pushPath(String path) {\r
+ mDirectories.insert(path, 0);\r
+ }\r
+\r
+ public boolean popPath() {\r
+ mDirectories.remove(mDirectories.getItem(0));\r
+ return !mDirectories.isEmpty();\r
+ }\r
+\r
+ @Override\r
+ protected Dialog onCreateDialog(int id) {\r
+ Dialog dialog;\r
+ AlertDialog.Builder builder;\r
+ switch (id) {\r
+ case DIALOG_SETUP_ACCOUNT:\r
+ builder = new AlertDialog.Builder(this);\r
+ builder.setTitle(R.string.main_tit_accsetup);\r
+ builder.setMessage(R.string.main_wrn_accsetup);\r
+ builder.setCancelable(false);\r
+ builder.setPositiveButton(android.R.string.ok, this);\r
+ builder.setNegativeButton(android.R.string.cancel, this);\r
+ dialog = builder.create();\r
+ break;\r
+ case DIALOG_CREATE_DIR: {\r
+ builder = new Builder(this);\r
+ final EditText dirName = new EditText(getBaseContext());\r
+ final Account a = AccountUtils.getCurrentOwnCloudAccount(this);\r
+ builder.setView(dirName);\r
+ builder.setTitle(R.string.uploader_info_dirname);\r
+ int typed_color = getResources().getColor(R.color.setup_text_typed);\r
+ dirName.setTextColor(typed_color);\r
+\r
+ builder.setPositiveButton(android.R.string.ok,\r
+ new OnClickListener() {\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ String s = dirName.getText().toString();\r
+ if (s.trim().length() == 0) {\r
+ dialog.cancel();\r
+ return;\r
+ }\r
+\r
+ String path = "";\r
+ for (int i = mDirectories.getCount() - 2; i >= 0; --i) {\r
+ path += "/" + mDirectories.getItem(i);\r
+ }\r
+ OCFile parent = mStorageManager.getFileByPath(path\r
+ + "/");\r
+ path += s + "/";\r
+ Thread thread = new Thread(new DirectoryCreator(\r
+ path, a));\r
+ thread.start();\r
+\r
+ OCFile new_file = new OCFile(path);\r
+ new_file.setMimetype("DIR");\r
+ new_file.setParentId(parent.getParentId());\r
+ mStorageManager.saveFile(new_file);\r
+\r
+ dialog.dismiss();\r
+ }\r
+ });\r
+ builder.setNegativeButton(R.string.common_cancel,\r
+ new OnClickListener() {\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ dialog.cancel();\r
+ }\r
+ });\r
+ dialog = builder.create();\r
+ break;\r
+ }\r
+ default:\r
+ dialog = null;\r
+ }\r
+\r
+ return dialog;\r
+ }\r
+\r
+ @Override\r
+ public void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+\r
+ if (!accountsAreSetup()) {\r
+ showDialog(DIALOG_SETUP_ACCOUNT);\r
+ return;\r
+ }\r
+\r
+ requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);\r
+ setProgressBarIndeterminateVisibility(false);\r
+ // if (getSupportFragmentManager().findFragmentById(R.id.fileList) ==\r
+ // null)\r
+ setContentView(R.layout.files);\r
+\r
+ }\r
+\r
+ @Override\r
+ public boolean onOptionsItemSelected(MenuItem item) {\r
+ boolean retval = true;\r
+ switch (item.getItemId()) {\r
+ case R.id.settingsItem: {\r
+ Intent i = new Intent(this, Preferences.class);\r
+ startActivity(i);\r
+ break;\r
+ }\r
+ case R.id.createDirectoryItem: {\r
+ showDialog(DIALOG_CREATE_DIR);\r
+ break;\r
+ }\r
+ case R.id.startSync: {\r
+ Bundle bundle = new Bundle();\r
+ bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+ ContentResolver.requestSync(\r
+ AccountUtils.getCurrentOwnCloudAccount(this),\r
+ "org.owncloud", bundle);\r
+ break;\r
+ }\r
+ case R.id.action_upload: {\r
+ Intent action = new Intent(Intent.ACTION_GET_CONTENT);\r
+ action = action.setType("*/*")\r
+ .addCategory(Intent.CATEGORY_OPENABLE);\r
+ startActivityForResult(\r
+ Intent.createChooser(action, "Upload file from..."),\r
+ ACTION_SELECT_FILE);\r
+ break;\r
+ }\r
+\r
+ case android.R.id.home: {\r
+ Intent i = new Intent(this, AccountSelectActivity.class);\r
+ startActivity(i);\r
+ finish();\r
+ break;\r
+ }\r
+ default:\r
+ retval = false;\r
+ }\r
+ return retval;\r
+ }\r
+\r
+ @Override\r
+ public void onBackPressed() {\r
+ if (mDirectories.getCount() == 1) {\r
+ finish();\r
return;\r
- }\r
-\r
- String path = "";\r
- for (int i = mDirectories.getCount() - 2; i >= 0; --i) {\r
- path += "/" + mDirectories.getItem(i);\r
- }\r
- OCFile parent = mStorageManager.getFileByPath(path + "/");\r
- path += s + "/";\r
- Thread thread = new Thread(new DirectoryCreator(path, a));\r
- thread.start();\r
- \r
- OCFile new_file = new OCFile(path);\r
- new_file.setMimetype("DIR");\r
- new_file.setParentId(parent.getParentId());\r
- mStorageManager.saveFile(new_file);\r
-\r
- dialog.dismiss();\r
}\r
- });\r
- builder.setNegativeButton(R.string.common_cancel,\r
- new OnClickListener() {\r
- public void onClick(DialogInterface dialog, int which) {\r
- dialog.cancel();\r
+ popPath();\r
+ ((FileListFragment) getSupportFragmentManager().findFragmentById(\r
+ R.id.fileList)).onNavigateUp();\r
+ }\r
+\r
+ @Override\r
+ public boolean onCreateOptionsMenu(Menu menu) {\r
+ MenuInflater inflater = getSherlock().getMenuInflater();\r
+ inflater.inflate(R.menu.menu, menu);\r
+ return true;\r
+ }\r
+\r
+ @Override\r
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {\r
+ super.onRestoreInstanceState(savedInstanceState);\r
+ // Check, if there are ownCloud accounts\r
+ if (!accountsAreSetup()) {\r
+ showDialog(DIALOG_SETUP_ACCOUNT);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ protected void onResume() {\r
+ super.onResume();\r
+ if (!accountsAreSetup()) {\r
+ showDialog(DIALOG_SETUP_ACCOUNT);\r
+ return;\r
+ }\r
+\r
+ IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);\r
+ syncBroadcastRevceiver = new SyncBroadcastReceiver();\r
+ registerReceiver(syncBroadcastRevceiver, f);\r
+\r
+ mDirectories = new CustomArrayAdapter<String>(this,\r
+ R.layout.sherlock_spinner_dropdown_item);\r
+ mDirectories.add("/");\r
+\r
+ mStorageManager = new FileDataStorageManager(\r
+ AccountUtils.getCurrentOwnCloudAccount(this),\r
+ getContentResolver());\r
+ ActionBar action_bar = getSupportActionBar();\r
+ action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);\r
+ action_bar.setDisplayShowTitleEnabled(false);\r
+ action_bar.setListNavigationCallbacks(mDirectories, this);\r
+ action_bar.setDisplayHomeAsUpEnabled(true);\r
+ }\r
+\r
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {\r
+ Log.e("ASD", requestCode + " " + resultCode);\r
+ if (resultCode == RESULT_OK) {\r
+ if (requestCode == ACTION_SELECT_FILE) {\r
+ Uri selectedImageUri = data.getData();\r
+\r
+ String filemanagerstring = selectedImageUri.getPath();\r
+ String selectedImagePath = getPath(selectedImageUri);\r
+ String filepath;\r
+\r
+ if (selectedImagePath != null)\r
+ filepath = selectedImagePath;\r
+ else\r
+ filepath = filemanagerstring;\r
+\r
+ if (filepath == null) {\r
+ Log.e("FileDisplay", "Couldnt resolve path to file");\r
+ return;\r
+ }\r
+\r
+ Intent i = new Intent(this, FileUploader.class);\r
+ i.putExtra(FileUploader.KEY_ACCOUNT,\r
+ AccountUtils.getCurrentOwnCloudAccount(this));\r
+ String remotepath = new String();\r
+ for (int j = mDirectories.getCount() - 2; j >= 0; --j) {\r
+ remotepath += "/" + mDirectories.getItem(j);\r
+ }\r
+ if (!remotepath.endsWith("/"))\r
+ remotepath += "/";\r
+ remotepath += new File(filepath).getName();\r
+ Log.e("ASD", remotepath + "");\r
+\r
+ i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);\r
+ i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);\r
+ i.putExtra(FileUploader.KEY_UPLOAD_TYPE,\r
+ FileUploader.UPLOAD_SINGLE_FILE);\r
+ startService(i);\r
}\r
- });\r
- dialog = builder.create();\r
- break;\r
+ }\r
}\r
- default: \r
- dialog = null;\r
+\r
+ public String getPath(Uri uri) {\r
+ String[] projection = { MediaStore.Images.Media.DATA };\r
+ Cursor cursor = managedQuery(uri, projection, null, null, null);\r
+ if (cursor != null) {\r
+ int column_index = cursor\r
+ .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\r
+ cursor.moveToFirst();\r
+ return cursor.getString(column_index);\r
+ } else\r
+ return null;\r
}\r
- \r
- return dialog;\r
- }\r
\r
- @Override\r
- public void onCreate(Bundle savedInstanceState) {\r
- super.onCreate(savedInstanceState);\r
+ @Override\r
+ protected void onPause() {\r
+ super.onPause();\r
+ if (syncBroadcastRevceiver != null) {\r
+ unregisterReceiver(syncBroadcastRevceiver);\r
+ syncBroadcastRevceiver = null;\r
+ }\r
\r
- if(!accountsAreSetup()){\r
- showDialog(DIALOG_SETUP_ACCOUNT);\r
- return;\r
}\r
- \r
- requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);\r
- setProgressBarIndeterminateVisibility(false);\r
- //if (getSupportFragmentManager().findFragmentById(R.id.fileList) == null)\r
- setContentView(R.layout.files);\r
- \r
- }\r
-\r
- @Override\r
- public boolean onOptionsItemSelected(MenuItem item) {\r
- boolean retval = true;\r
- switch (item.getItemId()) {\r
- case R.id.settingsItem: {\r
- Intent i = new Intent(this, Preferences.class);\r
- startActivity(i);\r
- break;\r
- }\r
- case R.id.createDirectoryItem: {\r
- showDialog(DIALOG_CREATE_DIR);\r
- break;\r
- }\r
- case R.id.startSync: {\r
- Bundle bundle = new Bundle();\r
- bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
- ContentResolver.requestSync(AccountUtils.getCurrentOwnCloudAccount(this),\r
- "org.owncloud",\r
- bundle);\r
- break;\r
- }\r
- case R.id.action_upload: {\r
- Intent action = new Intent(Intent.ACTION_GET_CONTENT); \r
- action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE); \r
- startActivityForResult(Intent.createChooser(action, "Upload file from..."), ACTION_SELECT_FILE);\r
- break;\r
- }\r
- \r
- case android.R.id.home: {\r
- Intent i = new Intent(this, AccountSelectActivity.class);\r
- startActivity(i);\r
- finish();\r
- break;\r
- }\r
- default:\r
- retval = false;\r
- }\r
- return retval;\r
- }\r
- \r
- @Override\r
- public void onBackPressed(){\r
- if(mDirectories.getCount() == 1) {\r
- finish();\r
- return;\r
- }\r
- popPath();\r
- ((FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList))\r
- .onNavigateUp();\r
- }\r
-\r
- @Override\r
- public boolean onCreateOptionsMenu(Menu menu) {\r
- MenuInflater inflater = getSherlock().getMenuInflater();\r
- inflater.inflate(R.menu.menu, menu);\r
- return true;\r
- }\r
-\r
- @Override\r
- protected void onRestoreInstanceState(Bundle savedInstanceState) {\r
- super.onRestoreInstanceState(savedInstanceState);\r
- // Check, if there are ownCloud accounts\r
- if(!accountsAreSetup()){\r
- showDialog(DIALOG_SETUP_ACCOUNT);\r
- }\r
- }\r
-\r
- \r
- @Override\r
- protected void onResume() {\r
- super.onResume();\r
- if(!accountsAreSetup()){\r
- showDialog(DIALOG_SETUP_ACCOUNT);\r
- return;\r
+\r
+ @Override\r
+ public boolean onNavigationItemSelected(int itemPosition, long itemId) {\r
+ int i = itemPosition;\r
+ while (i-- != 0) {\r
+ onBackPressed();\r
+ }\r
+ return true;\r
}\r
- \r
- IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);\r
- syncBroadcastRevceiver = new SyncBroadcastReceiver();\r
- registerReceiver(syncBroadcastRevceiver, f);\r
- \r
- mDirectories = new CustomArrayAdapter<String>(this,\r
- R.layout.sherlock_spinner_dropdown_item);\r
- mDirectories.add("/");\r
- \r
- mStorageManager = new FileDataStorageManager(AccountUtils.getCurrentOwnCloudAccount(this), getContentResolver());\r
- ActionBar action_bar = getSupportActionBar();\r
- action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);\r
- action_bar.setDisplayShowTitleEnabled(false);\r
- action_bar.setListNavigationCallbacks(mDirectories, this);\r
- action_bar.setDisplayHomeAsUpEnabled(true);\r
- }\r
- \r
- public void onActivityResult(int requestCode, int resultCode, Intent data) {\r
- Log.e("ASD", requestCode + " " + resultCode);\r
- if (resultCode == RESULT_OK) {\r
- if (requestCode == ACTION_SELECT_FILE) {\r
- Uri selectedImageUri = data.getData();\r
-\r
- String filemanagerstring = selectedImageUri.getPath();\r
- String selectedImagePath = getPath(selectedImageUri);\r
- String filepath;\r
-\r
- if(selectedImagePath!=null)\r
- filepath = selectedImagePath;\r
- else\r
- filepath = filemanagerstring;\r
- \r
- if (filepath == null) {\r
- Log.e("FileDisplay", "Couldnt resolve path to file");\r
- return;\r
- }\r
- \r
- Intent i = new Intent(this, FileUploader.class);\r
- i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));\r
- String remotepath = new String();\r
- for (int j = mDirectories.getCount() - 2; j >= 0; --j) {\r
- remotepath += "/" + mDirectories.getItem(j);\r
- }\r
- if (!remotepath.endsWith("/")) remotepath += "/";\r
- remotepath += new File(filepath).getName();\r
- Log.e("ASD", remotepath+"");\r
- \r
- i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);\r
- i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);\r
- i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);\r
- startService(i);\r
- }\r
- }\r
- }\r
- \r
- public String getPath(Uri uri) {\r
- String[] projection = { MediaStore.Images.Media.DATA };\r
- Cursor cursor = managedQuery(uri, projection, null, null, null);\r
- if(cursor!=null)\r
- {\r
- int column_index = cursor\r
- .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);\r
- cursor.moveToFirst();\r
- return cursor.getString(column_index);\r
- }\r
- else return null;\r
- }\r
- \r
- @Override\r
- protected void onPause() {\r
- super.onPause();\r
- if (syncBroadcastRevceiver != null) {\r
- unregisterReceiver(syncBroadcastRevceiver);\r
- syncBroadcastRevceiver = null;\r
- }\r
- \r
- }\r
- \r
- @Override\r
- public boolean onNavigationItemSelected(int itemPosition, long itemId) {\r
- int i = itemPosition;\r
- while (i-- != 0) {\r
- onBackPressed();\r
- }\r
- return true;\r
- }\r
-\r
- private class DirectoryCreator implements Runnable {\r
- private String mTargetPath;\r
- private Account mAccount;\r
- private AccountManager mAm;\r
-\r
- public DirectoryCreator(String targetPath, Account account) {\r
- mTargetPath = targetPath;\r
- mAccount = account;\r
- mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);\r
- }\r
-\r
- @Override\r
- public void run() {\r
- WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(\r
- mAccount, AccountAuthenticator.KEY_OC_URL)));\r
-\r
- String username = mAccount.name.substring(0,\r
- mAccount.name.lastIndexOf('@'));\r
- String password = mAm.getPassword(mAccount);\r
-\r
- wdc.setCredentials(username, password);\r
- wdc.allowUnsignedCertificates();\r
- wdc.createDirectory(mTargetPath);\r
- }\r
-\r
- }\r
-\r
- // Custom array adapter to override text colors\r
- private class CustomArrayAdapter<T> extends ArrayAdapter<T> {\r
- \r
- public CustomArrayAdapter(FileDisplayActivity ctx,\r
- int view) {\r
- super(ctx, view);\r
- }\r
-\r
- public View getView(int position, View convertView,\r
- ViewGroup parent) {\r
+\r
+ private class DirectoryCreator implements Runnable {\r
+ private String mTargetPath;\r
+ private Account mAccount;\r
+ private AccountManager mAm;\r
+\r
+ public DirectoryCreator(String targetPath, Account account) {\r
+ mTargetPath = targetPath;\r
+ mAccount = account;\r
+ mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);\r
+ }\r
+\r
+ @Override\r
+ public void run() {\r
+ WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(\r
+ mAccount, AccountAuthenticator.KEY_OC_URL)));\r
+\r
+ String username = mAccount.name.substring(0,\r
+ mAccount.name.lastIndexOf('@'));\r
+ String password = mAm.getPassword(mAccount);\r
+\r
+ wdc.setCredentials(username, password);\r
+ wdc.allowUnsignedCertificates();\r
+ wdc.createDirectory(mTargetPath);\r
+ }\r
+\r
+ }\r
+\r
+ // Custom array adapter to override text colors\r
+ private class CustomArrayAdapter<T> extends ArrayAdapter<T> {\r
+\r
+ public CustomArrayAdapter(FileDisplayActivity ctx, int view) {\r
+ super(ctx, view);\r
+ }\r
+\r
+ public View getView(int position, View convertView, ViewGroup parent) {\r
View v = super.getView(position, convertView, parent);\r
\r
- ((TextView) v).setTextColor(\r
- getResources()\r
- .getColorStateList(android.R.color.white));\r
+ ((TextView) v).setTextColor(getResources().getColorStateList(\r
+ android.R.color.white));\r
return v;\r
}\r
- \r
- public View getDropDownView(int position, View convertView,\r
+\r
+ public View getDropDownView(int position, View convertView,\r
ViewGroup parent) {\r
- View v = super.getDropDownView(position, convertView,\r
- parent);\r
+ View v = super.getDropDownView(position, convertView, parent);\r
\r
((TextView) v).setTextColor(getResources().getColorStateList(\r
- android.R.color.white));\r
+ android.R.color.white));\r
\r
return v;\r
}\r
\r
+ }\r
+\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ // In any case - we won't need it anymore\r
+ dialog.dismiss();\r
+ switch (which) {\r
+ case DialogInterface.BUTTON_POSITIVE:\r
+ Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
+ intent.putExtra("authorities",\r
+ new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
+ startActivity(intent);\r
+ break;\r
+ case DialogInterface.BUTTON_NEGATIVE:\r
+ finish();\r
+ }\r
+\r
+ }\r
+\r
+ /**\r
+ * Checks, whether or not there are any ownCloud accounts setup.\r
+ * \r
+ * @return true, if there is at least one account.\r
+ */\r
+ private boolean accountsAreSetup() {\r
+ AccountManager accMan = AccountManager.get(this);\r
+ Account[] accounts = accMan\r
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
+ return accounts.length > 0;\r
+ }\r
+\r
+ private class SyncBroadcastReceiver extends BroadcastReceiver {\r
+ /**\r
+ * {@link BroadcastReceiver} to enable syncing feedback in UI\r
+ */\r
+ @Override\r
+ public void onReceive(Context context, Intent intent) {\r
+ boolean inProgress = intent.getBooleanExtra(\r
+ FileSyncService.IN_PROGRESS, false);\r
+ String account_name = intent\r
+ .getStringExtra(FileSyncService.ACCOUNT_NAME);\r
+ Log.d("FileDisplay", "sync of account " + account_name\r
+ + " is in_progress: " + inProgress);\r
+ setProgressBarIndeterminateVisibility(inProgress);\r
+ if (!inProgress) {\r
+ FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager()\r
+ .findFragmentById(R.id.fileList);\r
+ if (fileListFramgent != null)\r
+ fileListFramgent.populateFileList();\r
+ }\r
+ }\r
\r
- \r
- }\r
- \r
- public void onClick(DialogInterface dialog, int which) {\r
- // In any case - we won't need it anymore\r
- dialog.dismiss();\r
- switch(which){\r
- case DialogInterface.BUTTON_POSITIVE:\r
- Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
- intent.putExtra("authorities",\r
- new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
- startActivity(intent);\r
- break;\r
- case DialogInterface.BUTTON_NEGATIVE:\r
- finish();\r
- }\r
- \r
- }\r
- \r
- /**\r
- * Checks, whether or not there are any ownCloud accounts \r
- * setup. \r
- * \r
- * @return true, if there is at least one account.\r
- */\r
- private boolean accountsAreSetup() {\r
- AccountManager accMan = AccountManager.get(this);\r
- Account[] accounts = accMan\r
- .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE); \r
- return accounts.length > 0;\r
- }\r
- \r
- private class SyncBroadcastReceiver extends BroadcastReceiver {\r
- /**\r
- * {@link BroadcastReceiver} to enable syncing feedback in UI\r
- */\r
- @Override\r
- public void onReceive(Context context, Intent intent) {\r
- boolean inProgress = intent.getBooleanExtra(FileSyncService.IN_PROGRESS, false);\r
- String account_name = intent.getStringExtra(FileSyncService.ACCOUNT_NAME);\r
- Log.d("FileDisplay", "sync of account " + account_name + " is in_progress: " + inProgress);\r
- setProgressBarIndeterminateVisibility(inProgress);\r
- if (!inProgress) {\r
- FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);\r
- if (fileListFramgent != null)\r
- fileListFramgent.populateFileList();\r
- }\r
}\r
- \r
- }\r
- \r
-}
+\r
+}\r
\r
/**\r
* This activity is used as a landing page when the user first opens this app.\r
+ * \r
* @author Lennart Rosam\r
* \r
*/\r
-public class LandingActivity extends SherlockFragmentActivity implements OnClickListener, OnItemClickListener {\r
-\r
- public static final int DIALOG_SETUP_ACCOUNT = 1;\r
- \r
- @Override\r
- protected void onCreate(Bundle savedInstanceState) {\r
- super.onCreate(savedInstanceState);\r
- setContentView(R.layout.main);\r
- \r
- // Fill the grid view of the landing screen with icons\r
- GridView landingScreenItems = (GridView) findViewById(R.id.homeScreenGrid);\r
- landingScreenItems.setAdapter(new LandingScreenAdapter(this));\r
- landingScreenItems.setOnItemClickListener(this);\r
- \r
- // Check, if there are ownCloud accounts\r
- if(!accountsAreSetup()){\r
- showDialog(DIALOG_SETUP_ACCOUNT);\r
- } else {\r
- // Start device tracking service \r
- Intent locationServiceIntent = new Intent();\r
- locationServiceIntent.setAction("eu.alefzero.owncloud.location.LocationLauncher");\r
- sendBroadcast(locationServiceIntent);\r
- }\r
-\r
- }\r
- \r
- @Override\r
- protected void onRestart() {\r
- super.onRestart();\r
- // Check, if there are ownCloud accounts\r
- if(!accountsAreSetup()){\r
- showDialog(DIALOG_SETUP_ACCOUNT);\r
- }\r
- }\r
-\r
- @Override\r
- protected void onRestoreInstanceState(Bundle savedInstanceState) {\r
- super.onRestoreInstanceState(savedInstanceState);\r
- // Check, if there are ownCloud accounts\r
- if(!accountsAreSetup()){\r
- showDialog(DIALOG_SETUP_ACCOUNT);\r
- }\r
- }\r
-\r
- @Override\r
- protected Dialog onCreateDialog(int id) {\r
- Dialog dialog;\r
- switch(id){\r
- case DIALOG_SETUP_ACCOUNT:\r
- AlertDialog.Builder builder = new AlertDialog.Builder(this);\r
- builder.setTitle(R.string.main_tit_accsetup);\r
- builder.setMessage(R.string.main_wrn_accsetup);\r
- builder.setCancelable(false);\r
- builder.setPositiveButton(R.string.common_ok, this);\r
- builder.setNegativeButton(R.string.common_cancel, this);\r
- dialog = builder.create();\r
- break;\r
- default: \r
- dialog = null;\r
- }\r
- \r
- return dialog;\r
- }\r
-\r
- public void onClick(DialogInterface dialog, int which) {\r
- // In any case - we won't need it anymore\r
- dialog.dismiss();\r
- switch(which){\r
- case DialogInterface.BUTTON_POSITIVE:\r
- Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
- intent.putExtra("authorities",\r
- new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
- startActivity(intent);\r
- break;\r
- case DialogInterface.BUTTON_NEGATIVE:\r
- finish();\r
- }\r
- \r
- }\r
- \r
- @Override\r
- /**\r
- * Start an activity based on the selection\r
- * the user made\r
- */\r
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\r
- Intent intent;\r
- intent = (Intent) parent.getAdapter().getItem(position);\r
- if(intent != null ){\r
- startActivity(intent);\r
- } else {\r
- // TODO: Implement all of this and make this text go away ;-)\r
- Toast toast = Toast.makeText(this, "Not yet implemented!", Toast.LENGTH_SHORT);\r
- toast.show();\r
- } \r
- }\r
- \r
- /**\r
- * Checks, whether or not there are any ownCloud accounts \r
- * setup. \r
- * \r
- * @return true, if there is at least one account.\r
- */\r
- private boolean accountsAreSetup() {\r
- AccountManager accMan = AccountManager.get(this);\r
- Account[] accounts = accMan\r
- .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE); \r
- return accounts.length > 0;\r
- }\r
-\r
- \r
+public class LandingActivity extends SherlockFragmentActivity implements\r
+ OnClickListener, OnItemClickListener {\r
+\r
+ public static final int DIALOG_SETUP_ACCOUNT = 1;\r
+\r
+ @Override\r
+ protected void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ setContentView(R.layout.main);\r
+\r
+ // Fill the grid view of the landing screen with icons\r
+ GridView landingScreenItems = (GridView) findViewById(R.id.homeScreenGrid);\r
+ landingScreenItems.setAdapter(new LandingScreenAdapter(this));\r
+ landingScreenItems.setOnItemClickListener(this);\r
+\r
+ // Check, if there are ownCloud accounts\r
+ if (!accountsAreSetup()) {\r
+ showDialog(DIALOG_SETUP_ACCOUNT);\r
+ } else {\r
+ // Start device tracking service\r
+ Intent locationServiceIntent = new Intent();\r
+ locationServiceIntent\r
+ .setAction("eu.alefzero.owncloud.location.LocationLauncher");\r
+ sendBroadcast(locationServiceIntent);\r
+ }\r
+\r
+ }\r
+\r
+ @Override\r
+ protected void onRestart() {\r
+ super.onRestart();\r
+ // Check, if there are ownCloud accounts\r
+ if (!accountsAreSetup()) {\r
+ showDialog(DIALOG_SETUP_ACCOUNT);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {\r
+ super.onRestoreInstanceState(savedInstanceState);\r
+ // Check, if there are ownCloud accounts\r
+ if (!accountsAreSetup()) {\r
+ showDialog(DIALOG_SETUP_ACCOUNT);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ protected Dialog onCreateDialog(int id) {\r
+ Dialog dialog;\r
+ switch (id) {\r
+ case DIALOG_SETUP_ACCOUNT:\r
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);\r
+ builder.setTitle(R.string.main_tit_accsetup);\r
+ builder.setMessage(R.string.main_wrn_accsetup);\r
+ builder.setCancelable(false);\r
+ builder.setPositiveButton(R.string.common_ok, this);\r
+ builder.setNegativeButton(R.string.common_cancel, this);\r
+ dialog = builder.create();\r
+ break;\r
+ default:\r
+ dialog = null;\r
+ }\r
+\r
+ return dialog;\r
+ }\r
+\r
+ public void onClick(DialogInterface dialog, int which) {\r
+ // In any case - we won't need it anymore\r
+ dialog.dismiss();\r
+ switch (which) {\r
+ case DialogInterface.BUTTON_POSITIVE:\r
+ Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");\r
+ intent.putExtra("authorities",\r
+ new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });\r
+ startActivity(intent);\r
+ break;\r
+ case DialogInterface.BUTTON_NEGATIVE:\r
+ finish();\r
+ }\r
+\r
+ }\r
+\r
+ @Override\r
+ /**\r
+ * Start an activity based on the selection\r
+ * the user made\r
+ */\r
+ public void onItemClick(AdapterView<?> parent, View view, int position,\r
+ long id) {\r
+ Intent intent;\r
+ intent = (Intent) parent.getAdapter().getItem(position);\r
+ if (intent != null) {\r
+ startActivity(intent);\r
+ } else {\r
+ // TODO: Implement all of this and make this text go away ;-)\r
+ Toast toast = Toast.makeText(this, "Not yet implemented!",\r
+ Toast.LENGTH_SHORT);\r
+ toast.show();\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Checks, whether or not there are any ownCloud accounts setup.\r
+ * \r
+ * @return true, if there is at least one account.\r
+ */\r
+ private boolean accountsAreSetup() {\r
+ AccountManager accMan = AccountManager.get(this);\r
+ Account[] accounts = accMan\r
+ .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
+ return accounts.length > 0;\r
+ }\r
+\r
}\r
* \r
*/\r
public class Preferences extends SherlockPreferenceActivity implements\r
- OnPreferenceChangeListener {\r
- private static final String TAG = "OwnCloudPreferences";\r
- private final int mNewSession = 47;\r
- private final int mEditSession = 48;\r
- private DbHandler mDbHandler;\r
- private Vector<OwnCloudSession> mSessions;\r
- private Account[] mAccounts;\r
- private ListPreference mAccountList;\r
- private ListPreference mTrackingUpdateInterval;\r
- private CheckBoxPreference mDeviceTracking;\r
- private int mSelectedMenuItem;\r
+ OnPreferenceChangeListener {\r
+ private static final String TAG = "OwnCloudPreferences";\r
+ private final int mNewSession = 47;\r
+ private final int mEditSession = 48;\r
+ private DbHandler mDbHandler;\r
+ private Vector<OwnCloudSession> mSessions;\r
+ private Account[] mAccounts;\r
+ private ListPreference mAccountList;\r
+ private ListPreference mTrackingUpdateInterval;\r
+ private CheckBoxPreference mDeviceTracking;\r
+ private int mSelectedMenuItem;\r
\r
- @Override\r
- public void onCreate(Bundle savedInstanceState) {\r
- super.onCreate(savedInstanceState);\r
- mDbHandler = new DbHandler(getBaseContext());\r
- mSessions = new Vector<OwnCloudSession>();\r
- addPreferencesFromResource(R.xml.preferences);\r
- registerForContextMenu(getListView());\r
- populateAccountList();\r
- ActionBar actionBar = getSherlock().getActionBar();\r
- actionBar.setDisplayHomeAsUpEnabled(true);\r
+ @Override\r
+ public void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ mDbHandler = new DbHandler(getBaseContext());\r
+ mSessions = new Vector<OwnCloudSession>();\r
+ addPreferencesFromResource(R.xml.preferences);\r
+ registerForContextMenu(getListView());\r
+ populateAccountList();\r
+ ActionBar actionBar = getSherlock().getActionBar();\r
+ actionBar.setDisplayHomeAsUpEnabled(true);\r
\r
- // Update summary for device tracking preference\r
- mTrackingUpdateInterval = (ListPreference) findPreference("devicetracking_update_intervall");\r
- String trackingSummary = getResources().getString(\r
- R.string.prefs_trackmydevice_interval_summary);\r
- trackingSummary = String.format(trackingSummary,\r
- mTrackingUpdateInterval.getValue());\r
- mTrackingUpdateInterval.setSummary(trackingSummary);\r
- mTrackingUpdateInterval.setOnPreferenceChangeListener(this);\r
+ // Update summary for device tracking preference\r
+ mTrackingUpdateInterval = (ListPreference) findPreference("devicetracking_update_intervall");\r
+ String trackingSummary = getResources().getString(\r
+ R.string.prefs_trackmydevice_interval_summary);\r
+ trackingSummary = String.format(trackingSummary,\r
+ mTrackingUpdateInterval.getValue());\r
+ mTrackingUpdateInterval.setSummary(trackingSummary);\r
+ mTrackingUpdateInterval.setOnPreferenceChangeListener(this);\r
\r
- // Enable or disable device tracking service. Listen on events\r
- mDeviceTracking = (CheckBoxPreference) findPreference("enable_devicetracking");\r
- mDeviceTracking.setOnPreferenceChangeListener(this);\r
- \r
- // populateSessionList();\r
- }\r
+ // Enable or disable device tracking service. Listen on events\r
+ mDeviceTracking = (CheckBoxPreference) findPreference("enable_devicetracking");\r
+ mDeviceTracking.setOnPreferenceChangeListener(this);\r
\r
- private void populateSessionList() {\r
- mSessions.clear();\r
- mSessions = mDbHandler.getSessionList();\r
- PreferenceScreen ps = getPreferenceScreen();\r
- ps.removeAll();\r
- addPreferencesFromResource(R.xml.preferences);\r
- for (int i = 0; i < mSessions.size(); i++) {\r
- Preference preference = new Preference(getBaseContext());\r
- preference.setTitle(mSessions.get(i).getName());\r
- URI uri;\r
- try {\r
- uri = new URI(mSessions.get(i).getUrl());\r
- } catch (URISyntaxException e) {\r
- e.printStackTrace(); // should never happen\r
- continue;\r
- }\r
- preference.setSummary(uri.getScheme() + "://" + uri.getHost()\r
- + uri.getPath());\r
- ps.addPreference(preference);\r
- }\r
- }\r
+ // populateSessionList();\r
+ }\r
\r
- /**\r
- * Populates the account selector\r
- */\r
- private void populateAccountList() {\r
- AccountManager accMan = AccountManager.get(this);\r
- mAccounts = accMan.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
- mAccountList = (ListPreference) findPreference("select_oc_account");\r
- mAccountList.setOnPreferenceChangeListener(this);\r
+ private void populateSessionList() {\r
+ mSessions.clear();\r
+ mSessions = mDbHandler.getSessionList();\r
+ PreferenceScreen ps = getPreferenceScreen();\r
+ ps.removeAll();\r
+ addPreferencesFromResource(R.xml.preferences);\r
+ for (int i = 0; i < mSessions.size(); i++) {\r
+ Preference preference = new Preference(getBaseContext());\r
+ preference.setTitle(mSessions.get(i).getName());\r
+ URI uri;\r
+ try {\r
+ uri = new URI(mSessions.get(i).getUrl());\r
+ } catch (URISyntaxException e) {\r
+ e.printStackTrace(); // should never happen\r
+ continue;\r
+ }\r
+ preference.setSummary(uri.getScheme() + "://" + uri.getHost()\r
+ + uri.getPath());\r
+ ps.addPreference(preference);\r
+ }\r
+ }\r
\r
- // Display the name of the current account if there is any\r
- Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
- if (defaultAccount != null) {\r
- mAccountList.setSummary(defaultAccount.name);\r
- }\r
+ /**\r
+ * Populates the account selector\r
+ */\r
+ private void populateAccountList() {\r
+ AccountManager accMan = AccountManager.get(this);\r
+ mAccounts = accMan.getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);\r
+ mAccountList = (ListPreference) findPreference("select_oc_account");\r
+ mAccountList.setOnPreferenceChangeListener(this);\r
\r
- // Transform accounts into array of string for preferences to use\r
- String[] accNames = new String[mAccounts.length];\r
- for (int i = 0; i < mAccounts.length; i++) {\r
- Account account = mAccounts[i];\r
- accNames[i] = account.name;\r
- }\r
+ // Display the name of the current account if there is any\r
+ Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
+ if (defaultAccount != null) {\r
+ mAccountList.setSummary(defaultAccount.name);\r
+ }\r
\r
- mAccountList.setEntries(accNames);\r
- mAccountList.setEntryValues(accNames);\r
- }\r
+ // Transform accounts into array of string for preferences to use\r
+ String[] accNames = new String[mAccounts.length];\r
+ for (int i = 0; i < mAccounts.length; i++) {\r
+ Account account = mAccounts[i];\r
+ accNames[i] = account.name;\r
+ }\r
\r
- @Override\r
- public boolean onCreateOptionsMenu(Menu menu) {\r
- super.onCreateOptionsMenu(menu);\r
- MenuInflater inflater = getSherlock().getMenuInflater();\r
- inflater.inflate(R.menu.prefs_menu, menu);\r
- return true;\r
- }\r
+ mAccountList.setEntries(accNames);\r
+ mAccountList.setEntryValues(accNames);\r
+ }\r
\r
- @Override\r
- public boolean onMenuItemSelected(int featureId, MenuItem item) {\r
- super.onMenuItemSelected(featureId, item);\r
- Intent intent;\r
+ @Override\r
+ public boolean onCreateOptionsMenu(Menu menu) {\r
+ super.onCreateOptionsMenu(menu);\r
+ MenuInflater inflater = getSherlock().getMenuInflater();\r
+ inflater.inflate(R.menu.prefs_menu, menu);\r
+ return true;\r
+ }\r
\r
- switch (item.getItemId()) {\r
- case R.id.addSessionItem:\r
- intent = new Intent(this, PreferencesNewSession.class);\r
- startActivityForResult(intent, mNewSession);\r
- break;\r
- case R.id.SessionContextEdit:\r
- intent = new Intent(this, PreferencesNewSession.class);\r
- intent.putExtra("sessionId", mSessions.get(mSelectedMenuItem)\r
- .getEntryId());\r
- intent.putExtra("sessionName", mSessions.get(mSelectedMenuItem)\r
- .getName());\r
- intent.putExtra("sessionURL", mSessions.get(mSelectedMenuItem)\r
- .getUrl());\r
- startActivityForResult(intent, mEditSession);\r
- break;\r
- case R.id.SessionContextRemove:\r
- OwnCloudSession ocs = mSessions.get(mSelectedMenuItem);\r
- mDbHandler.removeSessionWithId(ocs.getEntryId());\r
- mSessions.remove(ocs);\r
- getPreferenceScreen().removePreference(\r
- getPreferenceScreen().getPreference(mSelectedMenuItem + 1));\r
- break;\r
- case android.R.id.home:\r
- intent = new Intent(getBaseContext(), LandingActivity.class);\r
- intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\r
- startActivity(intent);\r
- break;\r
- default:\r
- Log.w(TAG, "Unknown menu item triggered");\r
- return false;\r
- }\r
- return true;\r
- }\r
+ @Override\r
+ public boolean onMenuItemSelected(int featureId, MenuItem item) {\r
+ super.onMenuItemSelected(featureId, item);\r
+ Intent intent;\r
\r
- @Override\r
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {\r
- super.onActivityResult(requestCode, resultCode, data);\r
- if (resultCode == Activity.RESULT_OK) {\r
- switch (requestCode) {\r
- case mNewSession:\r
- mDbHandler.addSession(data.getStringExtra("sessionName"),\r
- data.getStringExtra("sessionURL"));\r
- getPreferenceScreen().removeAll();\r
- addPreferencesFromResource(R.xml.preferences);\r
- populateSessionList();\r
- break;\r
- case mEditSession:\r
- mDbHandler.changeSessionFields(\r
- data.getIntExtra("sessionId", -1),\r
- data.getStringExtra("sessionName"),\r
- data.getStringExtra("sessionURL"));\r
- populateSessionList();\r
- break;\r
- }\r
- }\r
- }\r
+ switch (item.getItemId()) {\r
+ case R.id.addSessionItem:\r
+ intent = new Intent(this, PreferencesNewSession.class);\r
+ startActivityForResult(intent, mNewSession);\r
+ break;\r
+ case R.id.SessionContextEdit:\r
+ intent = new Intent(this, PreferencesNewSession.class);\r
+ intent.putExtra("sessionId", mSessions.get(mSelectedMenuItem)\r
+ .getEntryId());\r
+ intent.putExtra("sessionName", mSessions.get(mSelectedMenuItem)\r
+ .getName());\r
+ intent.putExtra("sessionURL", mSessions.get(mSelectedMenuItem)\r
+ .getUrl());\r
+ startActivityForResult(intent, mEditSession);\r
+ break;\r
+ case R.id.SessionContextRemove:\r
+ OwnCloudSession ocs = mSessions.get(mSelectedMenuItem);\r
+ mDbHandler.removeSessionWithId(ocs.getEntryId());\r
+ mSessions.remove(ocs);\r
+ getPreferenceScreen().removePreference(\r
+ getPreferenceScreen().getPreference(mSelectedMenuItem + 1));\r
+ break;\r
+ case android.R.id.home:\r
+ intent = new Intent(getBaseContext(), LandingActivity.class);\r
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\r
+ startActivity(intent);\r
+ break;\r
+ default:\r
+ Log.w(TAG, "Unknown menu item triggered");\r
+ return false;\r
+ }\r
+ return true;\r
+ }\r
\r
- @Override\r
- public void onCreateContextMenu(ContextMenu menu, View v,\r
- ContextMenuInfo menuInfo) {\r
- super.onCreateContextMenu(menu, v, menuInfo);\r
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;\r
- mSelectedMenuItem = info.position - 1;\r
- menu.setHeaderTitle(mSessions.get(mSelectedMenuItem).getName());\r
+ @Override\r
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {\r
+ super.onActivityResult(requestCode, resultCode, data);\r
+ if (resultCode == Activity.RESULT_OK) {\r
+ switch (requestCode) {\r
+ case mNewSession:\r
+ mDbHandler.addSession(data.getStringExtra("sessionName"),\r
+ data.getStringExtra("sessionURL"));\r
+ getPreferenceScreen().removeAll();\r
+ addPreferencesFromResource(R.xml.preferences);\r
+ populateSessionList();\r
+ break;\r
+ case mEditSession:\r
+ mDbHandler.changeSessionFields(\r
+ data.getIntExtra("sessionId", -1),\r
+ data.getStringExtra("sessionName"),\r
+ data.getStringExtra("sessionURL"));\r
+ populateSessionList();\r
+ break;\r
+ }\r
+ }\r
+ }\r
\r
- MenuInflater inflater = getSherlock().getMenuInflater();\r
- inflater.inflate(R.menu.session_context_menu, (Menu) menu);\r
+ @Override\r
+ public void onCreateContextMenu(ContextMenu menu, View v,\r
+ ContextMenuInfo menuInfo) {\r
+ super.onCreateContextMenu(menu, v, menuInfo);\r
+ AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;\r
+ mSelectedMenuItem = info.position - 1;\r
+ menu.setHeaderTitle(mSessions.get(mSelectedMenuItem).getName());\r
\r
- }\r
+ MenuInflater inflater = getSherlock().getMenuInflater();\r
+ inflater.inflate(R.menu.session_context_menu, (Menu) menu);\r
\r
- @Override\r
- protected void onDestroy() {\r
- mDbHandler.close();\r
- super.onDestroy();\r
- }\r
+ }\r
\r
- @Override\r
- /**\r
- * Updates various summaries after updates. Also starts and stops \r
- * the\r
- */\r
- public boolean onPreferenceChange(Preference preference, Object newValue) {\r
- // Update current account summary\r
- if (preference.equals(mAccountList)) {\r
- mAccountList.setSummary(newValue.toString());\r
- } \r
- \r
- // Update tracking interval summary\r
- else if (preference.equals(mTrackingUpdateInterval)) {\r
- String trackingSummary = getResources().getString(\r
- R.string.prefs_trackmydevice_interval_summary);\r
- trackingSummary = String.format(trackingSummary,\r
- newValue.toString());\r
- mTrackingUpdateInterval.setSummary(trackingSummary);\r
- } \r
- \r
- // Start or stop tracking service\r
- else if (preference.equals(mDeviceTracking)) {\r
- Intent locationServiceIntent = new Intent();\r
- locationServiceIntent.setAction("eu.alefzero.owncloud.location.LocationLauncher");\r
- locationServiceIntent.putExtra("TRACKING_SETTING", (Boolean) newValue);\r
- sendBroadcast(locationServiceIntent);\r
- }\r
- return true;\r
- }\r
+ @Override\r
+ protected void onDestroy() {\r
+ mDbHandler.close();\r
+ super.onDestroy();\r
+ }\r
+\r
+ @Override\r
+ /**\r
+ * Updates various summaries after updates. Also starts and stops \r
+ * the\r
+ */\r
+ public boolean onPreferenceChange(Preference preference, Object newValue) {\r
+ // Update current account summary\r
+ if (preference.equals(mAccountList)) {\r
+ mAccountList.setSummary(newValue.toString());\r
+ }\r
+\r
+ // Update tracking interval summary\r
+ else if (preference.equals(mTrackingUpdateInterval)) {\r
+ String trackingSummary = getResources().getString(\r
+ R.string.prefs_trackmydevice_interval_summary);\r
+ trackingSummary = String.format(trackingSummary,\r
+ newValue.toString());\r
+ mTrackingUpdateInterval.setSummary(trackingSummary);\r
+ }\r
+\r
+ // Start or stop tracking service\r
+ else if (preference.equals(mDeviceTracking)) {\r
+ Intent locationServiceIntent = new Intent();\r
+ locationServiceIntent\r
+ .setAction("eu.alefzero.owncloud.location.LocationLauncher");\r
+ locationServiceIntent.putExtra("TRACKING_SETTING",\r
+ (Boolean) newValue);\r
+ sendBroadcast(locationServiceIntent);\r
+ }\r
+ return true;\r
+ }\r
\r
}\r
import android.view.View;\r
import android.view.View.OnClickListener;\r
\r
-public class PreferencesNewSession extends AccountAuthenticatorActivity implements OnClickListener {\r
- @Override\r
- public void onCreate(Bundle savedInstanceState){\r
- super.onCreate(savedInstanceState);\r
- //setContentView(R.layout.add_new_session);\r
- /*\r
- EditText et;// = (EditText) findViewById(R.id.newSession_sessionName);\r
- \r
- et = (EditText) findViewById(R.id.newSession_URL);\r
- if (getIntent().hasExtra("sessionURL")) {\r
- try {\r
- URI uri = new URI(getIntent().getStringExtra("sessionURL"));\r
- String url = uri.getHost();\r
- if (uri.getPort() != -1) {\r
- url += ":" + String.valueOf(uri.getPort());\r
- }\r
- if (uri.getPath() != null) {\r
- url += uri.getPath();\r
- } else {\r
- url += "/";\r
- }\r
- et.setText(url);\r
- et = (EditText) findViewById(R.id.newSession_username);\r
- if (uri.getAuthority() != null) {\r
- if (uri.getUserInfo().indexOf(':') != -1) {\r
- et.setText(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(':')));\r
- et = (EditText) findViewById(R.id.newSession_password);\r
- et.setText(uri.getUserInfo().substring(uri.getUserInfo().indexOf(':')+1));\r
- } else {\r
- et.setText(uri.getUserInfo());\r
- }\r
- }\r
- \r
- } catch (URISyntaxException e) {\r
- Log.e(TAG, "Incorrect URI syntax " + e.getLocalizedMessage());\r
- }\r
+public class PreferencesNewSession extends AccountAuthenticatorActivity\r
+ implements OnClickListener {\r
+ @Override\r
+ public void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ // setContentView(R.layout.add_new_session);\r
+ /*\r
+ * EditText et;// = (EditText)\r
+ * findViewById(R.id.newSession_sessionName);\r
+ * \r
+ * et = (EditText) findViewById(R.id.newSession_URL); if\r
+ * (getIntent().hasExtra("sessionURL")) { try { URI uri = new\r
+ * URI(getIntent().getStringExtra("sessionURL")); String url =\r
+ * uri.getHost(); if (uri.getPort() != -1) { url += ":" +\r
+ * String.valueOf(uri.getPort()); } if (uri.getPath() != null) { url +=\r
+ * uri.getPath(); } else { url += "/"; } et.setText(url); et =\r
+ * (EditText) findViewById(R.id.newSession_username); if\r
+ * (uri.getAuthority() != null) { if (uri.getUserInfo().indexOf(':') !=\r
+ * -1) { et.setText(uri.getUserInfo().substring(0,\r
+ * uri.getUserInfo().indexOf(':'))); et = (EditText)\r
+ * findViewById(R.id.newSession_password);\r
+ * et.setText(uri.getUserInfo().substring\r
+ * (uri.getUserInfo().indexOf(':')+1)); } else {\r
+ * et.setText(uri.getUserInfo()); } }\r
+ * \r
+ * } catch (URISyntaxException e) { Log.e(TAG, "Incorrect URI syntax " +\r
+ * e.getLocalizedMessage()); } }\r
+ * \r
+ * mReturnData = new Intent(); setResult(Activity.RESULT_OK,\r
+ * mReturnData); ((Button)\r
+ * findViewById(R.id.button1)).setOnClickListener(this); ((Button)\r
+ * findViewById(R.id.button2)).setOnClickListener(this);\r
+ */\r
+ }\r
+\r
+ @Override\r
+ protected void onResume() {\r
+ super.onResume();\r
+ }\r
+\r
+ public void onClick(View v) {\r
+ /*\r
+ * switch (v.getId()) { case R.id.button1: Intent intent = new Intent();\r
+ * if (getIntent().hasExtra("sessionId")) { intent.putExtra("sessionId",\r
+ * getIntent().getIntExtra("sessionId", -1)); } //String sessionName =\r
+ * ((EditText)\r
+ * findViewById(R.id.newSession_sessionName)).getText().toString(); //\r
+ * if (sessionName.trim().equals("") || !isNameValid(sessionName)) { //\r
+ * Toast.makeText(this, R.string.new_session_session_name_error,\r
+ * Toast.LENGTH_LONG).show(); // break; // } URI uri = prepareURI(); if\r
+ * (uri != null) { //intent.putExtra("sessionName", sessionName);\r
+ * intent.putExtra("sessionURL", uri.toString());\r
+ * setResult(Activity.RESULT_OK, intent); AccountManager accMgr =\r
+ * AccountManager.get(this); Account a = new Account("OwnCloud",\r
+ * AccountAuthenticatorService.ACCOUNT_TYPE);\r
+ * accMgr.addAccountExplicitly(a, "asd", null); finish(); } break; case\r
+ * R.id.button2: setResult(Activity.RESULT_CANCELED); finish(); break; }\r
+ */\r
}\r
- \r
- mReturnData = new Intent();\r
- setResult(Activity.RESULT_OK, mReturnData);\r
- ((Button) findViewById(R.id.button1)).setOnClickListener(this);\r
- ((Button) findViewById(R.id.button2)).setOnClickListener(this);*/\r
- }\r
- \r
- @Override\r
- protected void onResume() {\r
- super.onResume();\r
- }\r
\r
- public void onClick(View v) {\r
- /* switch (v.getId()) {\r
- case R.id.button1:\r
- Intent intent = new Intent();\r
- if (getIntent().hasExtra("sessionId")) {\r
- intent.putExtra("sessionId", getIntent().getIntExtra("sessionId", -1));\r
- }\r
- //String sessionName = ((EditText) findViewById(R.id.newSession_sessionName)).getText().toString();\r
- // if (sessionName.trim().equals("") || !isNameValid(sessionName)) {\r
- // Toast.makeText(this, R.string.new_session_session_name_error, Toast.LENGTH_LONG).show();\r
- // break;\r
- // }\r
- URI uri = prepareURI();\r
- if (uri != null) {\r
- //intent.putExtra("sessionName", sessionName);\r
- intent.putExtra("sessionURL", uri.toString());\r
- setResult(Activity.RESULT_OK, intent);\r
- AccountManager accMgr = AccountManager.get(this);\r
- Account a = new Account("OwnCloud", AccountAuthenticatorService.ACCOUNT_TYPE);\r
- accMgr.addAccountExplicitly(a, "asd", null);\r
- finish();\r
- }\r
- break;\r
- case R.id.button2:\r
+ /*\r
+ * private URI prepareURI() { URI uri = null; String url = ""; try { String\r
+ * username = ((EditText)\r
+ * findViewById(R.id.newSession_username)).getText().toString().trim();\r
+ * String password = ((EditText)\r
+ * findViewById(R.id.newSession_password)).getText().toString().trim();\r
+ * String hostname = ((EditText)\r
+ * findViewById(R.id.newSession_URL)).getText().toString().trim(); String\r
+ * scheme; if (hostname.matches("[A-Za-z]://")) { scheme =\r
+ * hostname.substring(0, hostname.indexOf("://")+3); hostname =\r
+ * hostname.substring(hostname.indexOf("://")+3); } else { scheme =\r
+ * "http://"; } if (!username.equals("")) { if (!password.equals("")) {\r
+ * username += ":" + password + "@"; } else { username += "@"; } } url =\r
+ * scheme + username + hostname; Log.i(TAG, url); uri = new URI(url); }\r
+ * catch (URISyntaxException e) { Log.e(TAG, "Incorrect URI syntax " +\r
+ * e.getLocalizedMessage()); Toast.makeText(this,\r
+ * R.string.new_session_uri_error, Toast.LENGTH_LONG).show(); } return uri;\r
+ * }\r
+ * \r
+ * private boolean isNameValid(String string) { return\r
+ * string.matches("[A-Za-z0-9 _-]*"); }\r
+ */\r
+\r
+ @Override\r
+ public void onBackPressed() {\r
setResult(Activity.RESULT_CANCELED);\r
- finish();\r
- break;\r
- }*/\r
- }\r
- \r
- /*private URI prepareURI() {\r
- URI uri = null;\r
- String url = "";\r
- try {\r
- String username = ((EditText) findViewById(R.id.newSession_username)).getText().toString().trim();\r
- String password = ((EditText) findViewById(R.id.newSession_password)).getText().toString().trim();\r
- String hostname = ((EditText) findViewById(R.id.newSession_URL)).getText().toString().trim();\r
- String scheme;\r
- if (hostname.matches("[A-Za-z]://")) {\r
- scheme = hostname.substring(0, hostname.indexOf("://")+3);\r
- hostname = hostname.substring(hostname.indexOf("://")+3);\r
- } else {\r
- scheme = "http://";\r
- }\r
- if (!username.equals("")) {\r
- if (!password.equals("")) {\r
- username += ":" + password + "@";\r
- } else {\r
- username += "@";\r
- }\r
- }\r
- url = scheme + username + hostname;\r
- Log.i(TAG, url);\r
- uri = new URI(url);\r
- } catch (URISyntaxException e) {\r
- Log.e(TAG, "Incorrect URI syntax " + e.getLocalizedMessage());\r
- Toast.makeText(this, R.string.new_session_uri_error, Toast.LENGTH_LONG).show();\r
+ super.onBackPressed();\r
}\r
- return uri;\r
- }\r
- \r
- private boolean isNameValid(String string) {\r
- return string.matches("[A-Za-z0-9 _-]*");\r
- }*/\r
- \r
- @Override\r
- public void onBackPressed() {\r
- setResult(Activity.RESULT_CANCELED);\r
- super.onBackPressed();\r
- }\r
- \r
+\r
}\r
public class FileListActionListAdapter implements ListAdapter {
- private Context mContext;
- private Account mAccount;
- private String mFilename, mFileType, mFilePath, mFileStoragePath;
-
- private final int ITEM_DOWNLOAD = 0;
- //private final int ITEM_SHARE = 1;
-
- public FileListActionListAdapter(Cursor c, Context co, Account account) {
- mContext = co;
- mFilename = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_NAME));
- mFileType = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE));
- mFilePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH));
- mFileStoragePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
- //mItemId = c.getString(c.getColumnIndex(ProviderTableMeta._ID));
- mAccount = account;
- }
-
- public boolean areAllItemsEnabled() {
- // TODO Auto-generated method stub
- return true;
- }
-
- public boolean isEnabled(int position) {
- // TODO Auto-generated method stub
- return true;
- }
-
- public int getCount() {
- // TODO Auto-generated method stub
- return 1;
- }
-
- public Object getItem(int position) {
- if (position == 0) {
- Intent intent = new Intent(Intent.ACTION_VIEW);
- if (TextUtils.isEmpty(mFileStoragePath)) {
- intent.putExtra("toDownload", true);
- AccountManager accm = (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE);
- String ocurl = accm.getUserData(mAccount, AccountAuthenticator.KEY_OC_URL);
- ocurl += mFilePath + mFilename;
- intent.setData(Uri.parse(ocurl));
- } else {
- intent.putExtra("toDownload", false);
- intent.setDataAndType(Uri.fromFile(new File(mFileStoragePath)), mFileType);
- }
- return intent;
+ private Context mContext;
+ private Account mAccount;
+ private String mFilename, mFileType, mFilePath, mFileStoragePath;
+
+ private final int ITEM_DOWNLOAD = 0;
+
+ // private final int ITEM_SHARE = 1;
+
+ public FileListActionListAdapter(Cursor c, Context co, Account account) {
+ mContext = co;
+ mFilename = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_NAME));
+ mFileType = c.getString(c
+ .getColumnIndex(ProviderTableMeta.FILE_CONTENT_TYPE));
+ mFilePath = c.getString(c.getColumnIndex(ProviderTableMeta.FILE_PATH));
+ mFileStoragePath = c.getString(c
+ .getColumnIndex(ProviderTableMeta.FILE_STORAGE_PATH));
+ // mItemId = c.getString(c.getColumnIndex(ProviderTableMeta._ID));
+ mAccount = account;
}
- return null;
- }
-
- public long getItemId(int position) {
- // TODO Auto-generated method stub
- return 0;
- }
-
- public int getItemViewType(int position) {
- // TODO Auto-generated method stub
- return 0;
- }
-
- public View getView(int position, View convertView, ViewGroup parent) {
- View v = convertView;
- if (v == null) {
- LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- v = vi.inflate(R.layout.file_display_action_list_element, null);
+
+ public boolean areAllItemsEnabled() {
+ // TODO Auto-generated method stub
+ return true;
}
- TextView tv;
- ImageView iv;
- switch (position) {
- case ITEM_DOWNLOAD :
- tv = (TextView) v.findViewById(R.id.textView1);
- if (mFileStoragePath == null) {
- tv.setText("Download");
- } else {
- setActionName(tv);
+ public boolean isEnabled(int position) {
+ // TODO Auto-generated method stub
+ return true;
+ }
+
+ public int getCount() {
+ // TODO Auto-generated method stub
+ return 1;
+ }
+
+ public Object getItem(int position) {
+ if (position == 0) {
+ Intent intent = new Intent(Intent.ACTION_VIEW);
+ if (TextUtils.isEmpty(mFileStoragePath)) {
+ intent.putExtra("toDownload", true);
+ AccountManager accm = (AccountManager) mContext
+ .getSystemService(Context.ACCOUNT_SERVICE);
+ String ocurl = accm.getUserData(mAccount,
+ AccountAuthenticator.KEY_OC_URL);
+ ocurl += mFilePath + mFilename;
+ intent.setData(Uri.parse(ocurl));
+ } else {
+ intent.putExtra("toDownload", false);
+ intent.setDataAndType(Uri.fromFile(new File(mFileStoragePath)),
+ mFileType);
+ }
+ return intent;
+ }
+ return null;
+ }
+
+ public long getItemId(int position) {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public int getItemViewType(int position) {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ public View getView(int position, View convertView, ViewGroup parent) {
+ View v = convertView;
+ if (v == null) {
+ LayoutInflater vi = (LayoutInflater) mContext
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ v = vi.inflate(R.layout.file_display_action_list_element, null);
+ }
+
+ TextView tv;
+ ImageView iv;
+ switch (position) {
+ case ITEM_DOWNLOAD:
+ tv = (TextView) v.findViewById(R.id.textView1);
+ if (mFileStoragePath == null) {
+ tv.setText("Download");
+ } else {
+ setActionName(tv);
+ }
+ iv = (ImageView) v.findViewById(R.id.imageView1);
+ iv.setImageResource(R.drawable.download);
+ break;
}
- iv = (ImageView) v.findViewById(R.id.imageView1);
- iv.setImageResource(R.drawable.download);
- break;
+
+ return v;
}
-
- return v;
- }
-
- public int getViewTypeCount() {
- // TODO Auto-generated method stub
- return 2;
- }
-
- public boolean hasStableIds() {
- // TODO Auto-generated method stub
- return false;
- }
-
- public boolean isEmpty() {
- // TODO Auto-generated method stub
- return false;
- }
-
- public void registerDataSetObserver(DataSetObserver observer) {
- // TODO Auto-generated method stub
-
- }
-
- public void unregisterDataSetObserver(DataSetObserver observer) {
- // TODO Auto-generated method stub
-
- }
-
- private void setActionName(TextView tv) {
- if (mFileType.matches("image/.*")) {
- tv.setText("View");
- } else if (mFileType.matches("audio/.*") || mFileType.matches("video/.*")) {
- tv.setText("Play");
- } else {
- tv.setText("Open");
+
+ public int getViewTypeCount() {
+ // TODO Auto-generated method stub
+ return 2;
+ }
+
+ public boolean hasStableIds() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public boolean isEmpty() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public void registerDataSetObserver(DataSetObserver observer) {
+ // TODO Auto-generated method stub
+
}
- }
-
+
+ public void unregisterDataSetObserver(DataSetObserver observer) {
+ // TODO Auto-generated method stub
+
+ }
+
+ private void setActionName(TextView tv) {
+ if (mFileType.matches("image/.*")) {
+ tv.setText("View");
+ } else if (mFileType.matches("audio/.*")
+ || mFileType.matches("video/.*")) {
+ tv.setText("Play");
+ } else {
+ tv.setText("Open");
+ }
+ }
+
}
import android.widget.TextView;\r
\r
/**\r
- * This Adapter populates a ListView with all files and \r
- * folders in an ownCloud instance.\r
+ * This Adapter populates a ListView with all files and folders in an ownCloud\r
+ * instance.\r
+ * \r
* @author Bartek Przybylski\r
- *\r
+ * \r
*/\r
public class FileListListAdapter implements ListAdapter {\r
- private Context mContext;\r
- private OCFile mFile;\r
- private Vector<OCFile> mFiles;\r
- private DataStorageManager mStorageManager;\r
- \r
- public FileListListAdapter(OCFile file, DataStorageManager storage_man, Context context) {\r
- mFile = file;\r
- mStorageManager = storage_man;\r
- mFiles = mStorageManager.getDirectoryContent(mFile);\r
- mContext = context;\r
- }\r
- \r
- @Override\r
- public boolean areAllItemsEnabled() {\r
- return true;\r
- }\r
-\r
- @Override\r
- public boolean isEnabled(int position) {\r
- // TODO Auto-generated method stub\r
- return true;\r
- }\r
-\r
- @Override\r
- public int getCount() {\r
- return mFiles != null ? mFiles.size() : 0;\r
- }\r
-\r
- @Override\r
- public Object getItem(int position) {\r
- if (mFiles.size() <= position)\r
- return null;\r
- return mFiles.get(position);\r
- }\r
-\r
- @Override\r
- public long getItemId(int position) {\r
- return mFiles != null ? mFiles.get(position).getFileId() : 0;\r
- }\r
-\r
- @Override\r
- public int getItemViewType(int position) {\r
- // TODO Auto-generated method stub\r
- return 0;\r
- }\r
-\r
- @Override\r
- public View getView(int position, View convertView, ViewGroup parent) {\r
- View view = convertView;\r
- if (view == null) {\r
- LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\r
- view = inflator.inflate(R.layout.list_layout, null);\r
+ private Context mContext;\r
+ private OCFile mFile;\r
+ private Vector<OCFile> mFiles;\r
+ private DataStorageManager mStorageManager;\r
+\r
+ public FileListListAdapter(OCFile file, DataStorageManager storage_man,\r
+ Context context) {\r
+ mFile = file;\r
+ mStorageManager = storage_man;\r
+ mFiles = mStorageManager.getDirectoryContent(mFile);\r
+ mContext = context;\r
+ }\r
+\r
+ @Override\r
+ public boolean areAllItemsEnabled() {\r
+ return true;\r
}\r
- if (mFiles.size() > position) {\r
- OCFile file = mFiles.get(position);\r
- TextView fileName = (TextView) view.findViewById(R.id.Filename);\r
- TextView ext_text = (TextView) view.findViewById(R.id.Extension);\r
- String name = file.getFileName();\r
- String ext = file.getFileName();\r
- if (name.lastIndexOf('.') != -1) {\r
- name = name.substring(0, name.lastIndexOf('.'));\r
- ext = ext.substring(ext.lastIndexOf('.'));\r
- } else {\r
- ext = "";\r
- }\r
- \r
- fileName.setText(DisplayUtils.HtmlDecode(name));\r
- ext_text.setText(ext);\r
- ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);\r
- if (!file.getMimetype().equals("DIR")) {\r
- fileIcon.setImageResource(R.drawable.file);\r
- } else {\r
- fileIcon.setImageResource(R.drawable.ic_menu_archive);\r
- }\r
- ImageView down = (ImageView) view.findViewById(R.id.imageView2);\r
- if (file.getStoragePath() != null) down.setVisibility(View.VISIBLE);\r
- else down.setVisibility(View.INVISIBLE);\r
- \r
+\r
+ @Override\r
+ public boolean isEnabled(int position) {\r
+ // TODO Auto-generated method stub\r
+ return true;\r
}\r
\r
- return view;\r
- }\r
-\r
- @Override\r
- public int getViewTypeCount() {\r
- return 4;\r
- }\r
-\r
- @Override\r
- public boolean hasStableIds() {\r
- return true;\r
- }\r
-\r
- @Override\r
- public boolean isEmpty() {\r
- return mFiles != null ? mFiles.isEmpty() : false;\r
- }\r
-\r
- @Override\r
- public void registerDataSetObserver(DataSetObserver observer) {\r
- // TODO Auto-generated method stub\r
- \r
- }\r
-\r
- @Override\r
- public void unregisterDataSetObserver(DataSetObserver observer) {\r
- // TODO Auto-generated method stub\r
- \r
- }\r
+ @Override\r
+ public int getCount() {\r
+ return mFiles != null ? mFiles.size() : 0;\r
+ }\r
+\r
+ @Override\r
+ public Object getItem(int position) {\r
+ if (mFiles.size() <= position)\r
+ return null;\r
+ return mFiles.get(position);\r
+ }\r
+\r
+ @Override\r
+ public long getItemId(int position) {\r
+ return mFiles != null ? mFiles.get(position).getFileId() : 0;\r
+ }\r
+\r
+ @Override\r
+ public int getItemViewType(int position) {\r
+ // TODO Auto-generated method stub\r
+ return 0;\r
+ }\r
+\r
+ @Override\r
+ public View getView(int position, View convertView, ViewGroup parent) {\r
+ View view = convertView;\r
+ if (view == null) {\r
+ LayoutInflater inflator = (LayoutInflater) mContext\r
+ .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\r
+ view = inflator.inflate(R.layout.list_layout, null);\r
+ }\r
+ if (mFiles.size() > position) {\r
+ OCFile file = mFiles.get(position);\r
+ TextView fileName = (TextView) view.findViewById(R.id.Filename);\r
+ TextView ext_text = (TextView) view.findViewById(R.id.Extension);\r
+ String name = file.getFileName();\r
+ String ext = file.getFileName();\r
+ if (name.lastIndexOf('.') != -1) {\r
+ name = name.substring(0, name.lastIndexOf('.'));\r
+ ext = ext.substring(ext.lastIndexOf('.'));\r
+ } else {\r
+ ext = "";\r
+ }\r
+\r
+ fileName.setText(DisplayUtils.HtmlDecode(name));\r
+ ext_text.setText(ext);\r
+ ImageView fileIcon = (ImageView) view.findViewById(R.id.imageView1);\r
+ if (!file.getMimetype().equals("DIR")) {\r
+ fileIcon.setImageResource(R.drawable.file);\r
+ } else {\r
+ fileIcon.setImageResource(R.drawable.ic_menu_archive);\r
+ }\r
+ ImageView down = (ImageView) view.findViewById(R.id.imageView2);\r
+ if (file.getStoragePath() != null)\r
+ down.setVisibility(View.VISIBLE);\r
+ else\r
+ down.setVisibility(View.INVISIBLE);\r
+\r
+ }\r
+\r
+ return view;\r
+ }\r
+\r
+ @Override\r
+ public int getViewTypeCount() {\r
+ return 4;\r
+ }\r
+\r
+ @Override\r
+ public boolean hasStableIds() {\r
+ return true;\r
+ }\r
+\r
+ @Override\r
+ public boolean isEmpty() {\r
+ return mFiles != null ? mFiles.isEmpty() : false;\r
+ }\r
+\r
+ @Override\r
+ public void registerDataSetObserver(DataSetObserver observer) {\r
+ // TODO Auto-generated method stub\r
+\r
+ }\r
+\r
+ @Override\r
+ public void unregisterDataSetObserver(DataSetObserver observer) {\r
+ // TODO Auto-generated method stub\r
+\r
+ }\r
}\r
\r
/**\r
* Populates the landing screen icons.\r
+ * \r
* @author Lennart Rosam\r
- *\r
+ * \r
*/\r
public class LandingScreenAdapter extends BaseAdapter {\r
- \r
- private Context mContext;\r
\r
- private final Integer[] mLandingScreenIcons = { R.drawable.home,\r
- R.drawable.music, R.drawable.contacts,\r
- R.drawable.calendar,\r
- android.R.drawable.ic_menu_agenda,\r
- R.drawable.settings };\r
+ private Context mContext;\r
+\r
+ private final Integer[] mLandingScreenIcons = { R.drawable.home,\r
+ R.drawable.music, R.drawable.contacts, R.drawable.calendar,\r
+ android.R.drawable.ic_menu_agenda, R.drawable.settings };\r
+\r
+ private final Integer[] mLandingScreenTexts = { R.string.main_files,\r
+ R.string.main_music, R.string.main_contacts,\r
+ R.string.main_calendar, R.string.main_bookmarks,\r
+ R.string.main_settings };\r
\r
- private final Integer[] mLandingScreenTexts = { R.string.main_files,\r
- R.string.main_music, R.string.main_contacts,\r
- R.string.main_calendar, R.string.main_bookmarks,\r
- R.string.main_settings };\r
+ public LandingScreenAdapter(Context context) {\r
+ mContext = context;\r
+ }\r
\r
- public LandingScreenAdapter(Context context) {\r
- mContext = context;\r
- }\r
+ @Override\r
+ public int getCount() {\r
+ return mLandingScreenIcons.length;\r
+ }\r
\r
- @Override\r
- public int getCount() {\r
- return mLandingScreenIcons.length;\r
- }\r
+ @Override\r
+ /**\r
+ * Returns the Intent associated with this object\r
+ * or null if the functionality is not yet implemented\r
+ */\r
+ public Object getItem(int position) {\r
+ Intent intent = new Intent();\r
\r
- @Override\r
- /**\r
- * Returns the Intent associated with this object\r
- * or null if the functionality is not yet implemented\r
- */\r
- public Object getItem(int position) {\r
- Intent intent = new Intent();\r
- \r
- switch (position) {\r
- case 0:\r
- /* \r
- * The FileDisplayActivity requires the ownCloud account as an parcableExtra.\r
- * We will put in the one that is selected in the preferences\r
- */\r
- intent.setClass(mContext, FileDisplayActivity.class); \r
- intent.putExtra("ACCOUNT", AccountUtils.getCurrentOwnCloudAccount(mContext));\r
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
- break;\r
- case 5:\r
- intent.setClass(mContext, Preferences.class);\r
- break;\r
- default:\r
- intent = null;\r
- }\r
- return intent;\r
- }\r
+ switch (position) {\r
+ case 0:\r
+ /*\r
+ * The FileDisplayActivity requires the ownCloud account as an\r
+ * parcableExtra. We will put in the one that is selected in the\r
+ * preferences\r
+ */\r
+ intent.setClass(mContext, FileDisplayActivity.class);\r
+ intent.putExtra("ACCOUNT",\r
+ AccountUtils.getCurrentOwnCloudAccount(mContext));\r
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r
+ break;\r
+ case 5:\r
+ intent.setClass(mContext, Preferences.class);\r
+ break;\r
+ default:\r
+ intent = null;\r
+ }\r
+ return intent;\r
+ }\r
\r
- @Override\r
- public long getItemId(int position) {\r
- return position;\r
- }\r
+ @Override\r
+ public long getItemId(int position) {\r
+ return position;\r
+ }\r
\r
- @Override\r
- public View getView(int position, View convertView, ViewGroup parent) {\r
- if (convertView == null) {\r
- LayoutInflater inflator = LayoutInflater.from(mContext);\r
- convertView = inflator\r
- .inflate(R.layout.landing_page_item, null);\r
+ @Override\r
+ public View getView(int position, View convertView, ViewGroup parent) {\r
+ if (convertView == null) {\r
+ LayoutInflater inflator = LayoutInflater.from(mContext);\r
+ convertView = inflator.inflate(R.layout.landing_page_item, null);\r
\r
- ImageView icon = (ImageView) convertView\r
- .findViewById(R.id.gridImage);\r
- TextView iconText = (TextView) convertView\r
- .findViewById(R.id.gridText);\r
+ ImageView icon = (ImageView) convertView\r
+ .findViewById(R.id.gridImage);\r
+ TextView iconText = (TextView) convertView\r
+ .findViewById(R.id.gridText);\r
\r
- icon.setImageResource(mLandingScreenIcons[position]);\r
- iconText.setText(mLandingScreenTexts[position]);\r
- }\r
- return convertView;\r
- }\r
+ icon.setImageResource(mLandingScreenIcons[position]);\r
+ iconText.setText(mLandingScreenTexts[position]);\r
+ }\r
+ return convertView;\r
+ }\r
}\r
* \r
*/\r
public class FileDetailFragment extends SherlockFragment implements\r
- OnClickListener {\r
-\r
- public static final String FILE = "FILE";\r
-\r
- private Intent mIntent;\r
- private View mView;\r
- private DownloadFinishReceiver mDownloadFinishReceiver;\r
- private OCFile mFile;\r
-\r
- private int mLayout;\r
- private boolean mEmptyLayout;\r
-\r
- /**\r
- * Default constructor. When inflated by android -> display empty layout\r
- */\r
- public FileDetailFragment() {\r
- mLayout = R.layout.file_details_empty;\r
- mEmptyLayout = true;\r
- }\r
-\r
- /**\r
- * Custom construtor. Use with a {@link FragmentTransaction}.\r
- * The intent has to contain {@link FileDetailFragment#FILE} with an OCFile\r
- * and also {@link FileDownloader#EXTRA_ACCOUNT} with the account.\r
- * \r
- * @param nonEmptyFragment\r
- * True, to enable file detail rendering\r
- */\r
- public FileDetailFragment(Intent intent) {\r
- mLayout = R.layout.file_details_fragment;\r
- mIntent = intent;\r
- mEmptyLayout = false;\r
- }\r
-\r
- @Override\r
- public void onResume() {\r
- super.onResume();\r
- mDownloadFinishReceiver = new DownloadFinishReceiver();\r
- IntentFilter filter = new IntentFilter(\r
- FileDownloader.DOWNLOAD_FINISH_MESSAGE);\r
- getActivity().registerReceiver(mDownloadFinishReceiver, filter);\r
- }\r
-\r
- @Override\r
- public void onPause() {\r
- super.onPause();\r
- getActivity().unregisterReceiver(mDownloadFinishReceiver);\r
- mDownloadFinishReceiver = null;\r
- }\r
-\r
- /**\r
- * Use this method to signal this Activity that it shall update its view.\r
- * \r
- * @param intent\r
- * The {@link Intent} that contains extra information about this\r
- * file The intent needs to have these extras:\r
- * <p>\r
- * \r
- * {@link FileDetailFragment#FILE}: An {@link OCFile}\r
- * {@link FileDownloader#EXTRA_ACCOUNT}: The Account that file\r
- * belongs to (required for downloading)\r
- */\r
- public void updateFileDetails(Intent intent) {\r
- mIntent = intent;\r
- updateFileDetails();\r
- }\r
-\r
- private void updateFileDetails() {\r
- mFile = mIntent.getParcelableExtra(FILE);\r
-\r
- if (mFile != null) {\r
- // set file details\r
- setFilename(mFile.getFileName());\r
- setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile\r
- .getMimetype()));\r
- setFilesize(mFile.getFileLength());\r
-\r
- // set file preview if available and possible\r
- VideoView videoView = (VideoView) mView\r
- .findViewById(R.id.videoView1);\r
- videoView.setVisibility(View.INVISIBLE);\r
- if (mFile.getPath() == null) {\r
- ImageView imageView = (ImageView) getView().findViewById(\r
- R.id.imageView2);\r
- imageView.setImageResource(R.drawable.download);\r
- imageView.setOnClickListener(this);\r
- } else {\r
- if (mFile.getMimetype().startsWith("image/")) {\r
- ImageView imageView = (ImageView) mView\r
- .findViewById(R.id.imageView2);\r
- Bitmap bmp = BitmapFactory.decodeFile(mFile.getPath());\r
- imageView.setImageBitmap(bmp);\r
- } else if (mFile.getMimetype().startsWith("video/")) {\r
- videoView.setVisibility(View.VISIBLE);\r
- videoView.setVideoPath(mFile.getPath());\r
- videoView.start();\r
- }\r
- }\r
- }\r
- }\r
-\r
- @Override\r
- public View onCreateView(LayoutInflater inflater, ViewGroup container,\r
- Bundle savedInstanceState) {\r
- View view = null;\r
-\r
- view = inflater.inflate(mLayout, container, false);\r
- mIntent = getActivity().getIntent();\r
- mView = view;\r
-\r
- // make sure we are not using the empty layout\r
- if (mEmptyLayout == false) {\r
- updateFileDetails();\r
- }\r
-\r
- return view;\r
- }\r
-\r
- @Override\r
- public View getView() {\r
- return mView == null ? super.getView() : mView;\r
- };\r
-\r
- private void setFilename(String filename) {\r
- TextView tv = (TextView) getView().findViewById(R.id.textView1);\r
- if (tv != null)\r
- tv.setText(filename);\r
- }\r
-\r
- private void setFiletype(String mimetype) {\r
- TextView tv = (TextView) getView().findViewById(R.id.textView2);\r
- if (tv != null)\r
- tv.setText(mimetype);\r
- }\r
-\r
- private void setFilesize(long filesize) {\r
- TextView tv = (TextView) getView().findViewById(R.id.textView3);\r
- if (tv != null)\r
- tv.setText(DisplayUtils.bitsToHumanReadable(filesize));\r
- }\r
-\r
- /**\r
- * Use this to check if the correct layout is loaded. When android\r
- * instanciates this class using the default constructor, the layout will be\r
- * empty.\r
- * \r
- * Once a user touches a file for the first time, you must instanciate a new\r
- * Fragment with the new FileDetailFragment(true) to inflate the actual\r
- * details\r
- * \r
- * @return If the layout is empty, this method will return true, otherwise\r
- * false\r
- */\r
- public boolean isEmptyLayout() {\r
- return mEmptyLayout;\r
- }\r
-\r
- @Override\r
- public void onClick(View v) {\r
- Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();\r
- Intent i = new Intent(getActivity(), FileDownloader.class);\r
- i.putExtra(FileDownloader.EXTRA_ACCOUNT,\r
- mIntent.getParcelableExtra(FileDownloader.EXTRA_ACCOUNT));\r
- i.putExtra(FileDownloader.EXTRA_FILE_PATH,\r
- mIntent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));\r
- getActivity().startService(i);\r
- }\r
-\r
- private class DownloadFinishReceiver extends BroadcastReceiver {\r
- @Override\r
- public void onReceive(Context context, Intent intent) {\r
- updateFileDetails();\r
- }\r
-\r
- }\r
+ OnClickListener {\r
+\r
+ public static final String FILE = "FILE";\r
+\r
+ private Intent mIntent;\r
+ private View mView;\r
+ private DownloadFinishReceiver mDownloadFinishReceiver;\r
+ private OCFile mFile;\r
+\r
+ private int mLayout;\r
+ private boolean mEmptyLayout;\r
+\r
+ /**\r
+ * Default constructor. When inflated by android -> display empty layout\r
+ */\r
+ public FileDetailFragment() {\r
+ mLayout = R.layout.file_details_empty;\r
+ mEmptyLayout = true;\r
+ }\r
+\r
+ /**\r
+ * Custom construtor. Use with a {@link FragmentTransaction}. The intent has\r
+ * to contain {@link FileDetailFragment#FILE} with an OCFile and also\r
+ * {@link FileDownloader#EXTRA_ACCOUNT} with the account.\r
+ * \r
+ * @param nonEmptyFragment\r
+ * True, to enable file detail rendering\r
+ */\r
+ public FileDetailFragment(Intent intent) {\r
+ mLayout = R.layout.file_details_fragment;\r
+ mIntent = intent;\r
+ mEmptyLayout = false;\r
+ }\r
+\r
+ @Override\r
+ public void onResume() {\r
+ super.onResume();\r
+ mDownloadFinishReceiver = new DownloadFinishReceiver();\r
+ IntentFilter filter = new IntentFilter(\r
+ FileDownloader.DOWNLOAD_FINISH_MESSAGE);\r
+ getActivity().registerReceiver(mDownloadFinishReceiver, filter);\r
+ }\r
+\r
+ @Override\r
+ public void onPause() {\r
+ super.onPause();\r
+ getActivity().unregisterReceiver(mDownloadFinishReceiver);\r
+ mDownloadFinishReceiver = null;\r
+ }\r
+\r
+ /**\r
+ * Use this method to signal this Activity that it shall update its view.\r
+ * \r
+ * @param intent\r
+ * The {@link Intent} that contains extra information about this\r
+ * file The intent needs to have these extras:\r
+ * <p>\r
+ * \r
+ * {@link FileDetailFragment#FILE}: An {@link OCFile}\r
+ * {@link FileDownloader#EXTRA_ACCOUNT}: The Account that file\r
+ * belongs to (required for downloading)\r
+ */\r
+ public void updateFileDetails(Intent intent) {\r
+ mIntent = intent;\r
+ updateFileDetails();\r
+ }\r
+\r
+ private void updateFileDetails() {\r
+ mFile = mIntent.getParcelableExtra(FILE);\r
+\r
+ if (mFile != null) {\r
+ // set file details\r
+ setFilename(mFile.getFileName());\r
+ setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile\r
+ .getMimetype()));\r
+ setFilesize(mFile.getFileLength());\r
+\r
+ // set file preview if available and possible\r
+ VideoView videoView = (VideoView) mView\r
+ .findViewById(R.id.videoView1);\r
+ videoView.setVisibility(View.INVISIBLE);\r
+ if (mFile.getPath() == null) {\r
+ ImageView imageView = (ImageView) getView().findViewById(\r
+ R.id.imageView2);\r
+ imageView.setImageResource(R.drawable.download);\r
+ imageView.setOnClickListener(this);\r
+ } else {\r
+ if (mFile.getMimetype().startsWith("image/")) {\r
+ ImageView imageView = (ImageView) mView\r
+ .findViewById(R.id.imageView2);\r
+ Bitmap bmp = BitmapFactory.decodeFile(mFile.getPath());\r
+ imageView.setImageBitmap(bmp);\r
+ } else if (mFile.getMimetype().startsWith("video/")) {\r
+ videoView.setVisibility(View.VISIBLE);\r
+ videoView.setVideoPath(mFile.getPath());\r
+ videoView.start();\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,\r
+ Bundle savedInstanceState) {\r
+ View view = null;\r
+\r
+ view = inflater.inflate(mLayout, container, false);\r
+ mIntent = getActivity().getIntent();\r
+ mView = view;\r
+\r
+ // make sure we are not using the empty layout\r
+ if (mEmptyLayout == false) {\r
+ updateFileDetails();\r
+ }\r
+\r
+ return view;\r
+ }\r
+\r
+ @Override\r
+ public View getView() {\r
+ return mView == null ? super.getView() : mView;\r
+ };\r
+\r
+ private void setFilename(String filename) {\r
+ TextView tv = (TextView) getView().findViewById(R.id.textView1);\r
+ if (tv != null)\r
+ tv.setText(filename);\r
+ }\r
+\r
+ private void setFiletype(String mimetype) {\r
+ TextView tv = (TextView) getView().findViewById(R.id.textView2);\r
+ if (tv != null)\r
+ tv.setText(mimetype);\r
+ }\r
+\r
+ private void setFilesize(long filesize) {\r
+ TextView tv = (TextView) getView().findViewById(R.id.textView3);\r
+ if (tv != null)\r
+ tv.setText(DisplayUtils.bitsToHumanReadable(filesize));\r
+ }\r
+\r
+ /**\r
+ * Use this to check if the correct layout is loaded. When android\r
+ * instanciates this class using the default constructor, the layout will be\r
+ * empty.\r
+ * \r
+ * Once a user touches a file for the first time, you must instanciate a new\r
+ * Fragment with the new FileDetailFragment(true) to inflate the actual\r
+ * details\r
+ * \r
+ * @return If the layout is empty, this method will return true, otherwise\r
+ * false\r
+ */\r
+ public boolean isEmptyLayout() {\r
+ return mEmptyLayout;\r
+ }\r
+\r
+ @Override\r
+ public void onClick(View v) {\r
+ Toast.makeText(getActivity(), "Downloading", Toast.LENGTH_LONG).show();\r
+ Intent i = new Intent(getActivity(), FileDownloader.class);\r
+ i.putExtra(FileDownloader.EXTRA_ACCOUNT,\r
+ mIntent.getParcelableExtra(FileDownloader.EXTRA_ACCOUNT));\r
+ i.putExtra(FileDownloader.EXTRA_FILE_PATH,\r
+ mIntent.getStringExtra(FileDownloader.EXTRA_FILE_PATH));\r
+ getActivity().startService(i);\r
+ }\r
+\r
+ private class DownloadFinishReceiver extends BroadcastReceiver {\r
+ @Override\r
+ public void onReceive(Context context, Intent intent) {\r
+ updateFileDetails();\r
+ }\r
+\r
+ }\r
\r
}\r
* \r
*/\r
public class FileListFragment extends FragmentListView {\r
- private Account mAccount;\r
- private Stack<String> mDirNames;\r
- private Vector<OCFile> mFiles;\r
- private DataStorageManager mStorageManager;\r
-\r
- public FileListFragment() {\r
- mDirNames = new Stack<String>();\r
- }\r
-\r
- @Override\r
- public void onCreate(Bundle savedInstanceState) {\r
- super.onCreate(savedInstanceState);\r
-\r
- mAccount = AccountUtils.getCurrentOwnCloudAccount(getActivity());\r
- getListView().setDivider(\r
- getResources().getDrawable(R.drawable.uploader_list_separator));\r
- getListView().setDividerHeight(1);\r
-\r
- populateFileList();\r
- }\r
-\r
- @Override\r
- public void onItemClick(AdapterView<?> l, View v, int position, long id) {\r
- if (mFiles.size() <= position) {\r
- throw new IndexOutOfBoundsException("Incorrect item selected");\r
- }\r
- OCFile file = mFiles.get(position);\r
-\r
- // Update ActionBarPath\r
- if (file.getMimetype().equals("DIR")) {\r
- String dirname = file.getFileName();\r
-\r
- mDirNames.push(dirname);\r
- ((FileDisplayActivity) getActivity()).pushPath(dirname);\r
-\r
- populateFileList();\r
- return;\r
- }\r
-\r
- Intent showDetailsIntent = new Intent(getActivity(),\r
- FileDetailActivity.class);\r
- showDetailsIntent.putExtra(FileDetailFragment.FILE, file);\r
- showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);\r
- \r
- // Try to find by tag first\r
- FileDetailFragment fd = (FileDetailFragment) getFragmentManager()\r
- .findFragmentByTag("FileDetails");\r
- \r
- // Could be the first time the user has touched a file. find by id\r
- if(fd == null){\r
- fd = (FileDetailFragment) getFragmentManager().findFragmentById(R.id.fileDetail);\r
- }\r
-\r
- // Tablets will have this fragment, phones not. Could still be null\r
- if (fd != null) {\r
- \r
- if(fd.isEmptyLayout()){\r
- // True, if this is the first time a user taps on a file\r
- fd = new FileDetailFragment(showDetailsIntent);\r
- FragmentTransaction transaction = getFragmentManager().beginTransaction();\r
- transaction.replace(R.id.file_details_container, fd, "FileDetails");\r
- transaction.commit();\r
- } else {\r
- fd.updateFileDetails(showDetailsIntent);\r
- }\r
- \r
- } else {\r
- startActivity(showDetailsIntent);\r
- }\r
- }\r
-\r
- @Override\r
- public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,\r
- long arg3) {\r
- ClipData.Item item = new ClipData.Item("ASD");\r
- ClipDescription cd = new ClipDescription("ASD",\r
- new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN });\r
- ClipData dragData = new ClipData(cd, item);\r
- arg1.startDrag(dragData,\r
- new View.DragShadowBuilder(arg0.getChildAt(arg2)), null, 0);\r
- return true;\r
- }\r
-\r
- /**\r
- * Call this, when the user presses the up button\r
- */\r
- public void onNavigateUp() {\r
- mDirNames.pop();\r
- populateFileList();\r
- }\r
-\r
- /**\r
- * Lists the directory\r
- */\r
- public void populateFileList() {\r
- String s = "/";\r
- for (String a : mDirNames)\r
- s += a + "/";\r
- Log.e("ASD", s);\r
-\r
- mStorageManager = new FileDataStorageManager(mAccount, getActivity()\r
- .getContentResolver());\r
- OCFile file = mStorageManager.getFileByPath(s);\r
- mFiles = mStorageManager.getDirectoryContent(file);\r
- if (mFiles == null || mFiles.size() == 0) {\r
- Toast.makeText(getActivity(), "There are no files here",\r
- Toast.LENGTH_LONG).show();\r
- }\r
- setListAdapter(new FileListListAdapter(file, mStorageManager,\r
- getActivity()));\r
- }\r
-\r
- // TODO: Delete this testing stuff.\r
- /*\r
- * private void addContact(Account account, String name, String username) {\r
- * Log.i("ASD", "Adding contact: " + name);\r
- * ArrayList<ContentProviderOperation> operationList = new\r
- * ArrayList<ContentProviderOperation>();\r
- * \r
- * //Create our RawContact ContentProviderOperation.Builder builder =\r
- * ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);\r
- * builder.withValue(RawContacts.ACCOUNT_NAME, account.name);\r
- * builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);\r
- * builder.withValue(RawContacts.SYNC1, username);\r
- * operationList.add(builder.build());\r
- * \r
- * //Create a Data record of common type 'StructuredName' for our RawContact\r
- * builder =\r
- * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);\r
- * builder\r
- * .withValueBackReference(ContactsContract.CommonDataKinds.StructuredName\r
- * .RAW_CONTACT_ID, 0); builder.withValue(ContactsContract.Data.MIMETYPE,\r
- * ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);\r
- * builder\r
- * .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,\r
- * name); operationList.add(builder.build());\r
- * \r
- * //Create a Data record of custom type\r
- * "vnd.android.cursor.item/vnd.fm.last.android.profile" to display a link\r
- * to the Last.fm profile builder =\r
- * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);\r
- * builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);\r
- * builder.withValue(ContactsContract.Data.MIMETYPE,\r
- * "vnd.android.cursor.item/vnd.owncloud.contact.profile");\r
- * builder.withValue(ContactsContract.Data.DATA1, username);\r
- * builder.withValue(ContactsContract.Data.DATA2, "Last.fm Profile");\r
- * builder.withValue(ContactsContract.Data.DATA3, "View profile");\r
- * operationList.add(builder.build());\r
- * \r
- * try {\r
- * getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY,\r
- * operationList); } catch (Exception e) { Log.e("ASD",\r
- * "Something went wrong during creation! " + e); e.printStackTrace(); } }\r
- */\r
+ private Account mAccount;\r
+ private Stack<String> mDirNames;\r
+ private Vector<OCFile> mFiles;\r
+ private DataStorageManager mStorageManager;\r
+\r
+ public FileListFragment() {\r
+ mDirNames = new Stack<String>();\r
+ }\r
+\r
+ @Override\r
+ public void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+\r
+ mAccount = AccountUtils.getCurrentOwnCloudAccount(getActivity());\r
+ getListView().setDivider(\r
+ getResources().getDrawable(R.drawable.uploader_list_separator));\r
+ getListView().setDividerHeight(1);\r
+\r
+ populateFileList();\r
+ }\r
+\r
+ @Override\r
+ public void onItemClick(AdapterView<?> l, View v, int position, long id) {\r
+ if (mFiles.size() <= position) {\r
+ throw new IndexOutOfBoundsException("Incorrect item selected");\r
+ }\r
+ OCFile file = mFiles.get(position);\r
+\r
+ // Update ActionBarPath\r
+ if (file.getMimetype().equals("DIR")) {\r
+ String dirname = file.getFileName();\r
+\r
+ mDirNames.push(dirname);\r
+ ((FileDisplayActivity) getActivity()).pushPath(dirname);\r
+\r
+ populateFileList();\r
+ return;\r
+ }\r
+\r
+ Intent showDetailsIntent = new Intent(getActivity(),\r
+ FileDetailActivity.class);\r
+ showDetailsIntent.putExtra(FileDetailFragment.FILE, file);\r
+ showDetailsIntent.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);\r
+\r
+ // Try to find by tag first\r
+ FileDetailFragment fd = (FileDetailFragment) getFragmentManager()\r
+ .findFragmentByTag("FileDetails");\r
+\r
+ // Could be the first time the user has touched a file. find by id\r
+ if (fd == null) {\r
+ fd = (FileDetailFragment) getFragmentManager().findFragmentById(\r
+ R.id.fileDetail);\r
+ }\r
+\r
+ // Tablets will have this fragment, phones not. Could still be null\r
+ if (fd != null) {\r
+\r
+ if (fd.isEmptyLayout()) {\r
+ // True, if this is the first time a user taps on a file\r
+ fd = new FileDetailFragment(showDetailsIntent);\r
+ FragmentTransaction transaction = getFragmentManager()\r
+ .beginTransaction();\r
+ transaction.replace(R.id.file_details_container, fd,\r
+ "FileDetails");\r
+ transaction.commit();\r
+ } else {\r
+ fd.updateFileDetails(showDetailsIntent);\r
+ }\r
+\r
+ } else {\r
+ startActivity(showDetailsIntent);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,\r
+ long arg3) {\r
+ ClipData.Item item = new ClipData.Item("ASD");\r
+ ClipDescription cd = new ClipDescription("ASD",\r
+ new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN });\r
+ ClipData dragData = new ClipData(cd, item);\r
+ arg1.startDrag(dragData,\r
+ new View.DragShadowBuilder(arg0.getChildAt(arg2)), null, 0);\r
+ return true;\r
+ }\r
+\r
+ /**\r
+ * Call this, when the user presses the up button\r
+ */\r
+ public void onNavigateUp() {\r
+ mDirNames.pop();\r
+ populateFileList();\r
+ }\r
+\r
+ /**\r
+ * Lists the directory\r
+ */\r
+ public void populateFileList() {\r
+ String s = "/";\r
+ for (String a : mDirNames)\r
+ s += a + "/";\r
+ Log.e("ASD", s);\r
+\r
+ mStorageManager = new FileDataStorageManager(mAccount, getActivity()\r
+ .getContentResolver());\r
+ OCFile file = mStorageManager.getFileByPath(s);\r
+ mFiles = mStorageManager.getDirectoryContent(file);\r
+ if (mFiles == null || mFiles.size() == 0) {\r
+ Toast.makeText(getActivity(), "There are no files here",\r
+ Toast.LENGTH_LONG).show();\r
+ }\r
+ setListAdapter(new FileListListAdapter(file, mStorageManager,\r
+ getActivity()));\r
+ }\r
+\r
+ // TODO: Delete this testing stuff.\r
+ /*\r
+ * private void addContact(Account account, String name, String username) {\r
+ * Log.i("ASD", "Adding contact: " + name);\r
+ * ArrayList<ContentProviderOperation> operationList = new\r
+ * ArrayList<ContentProviderOperation>();\r
+ * \r
+ * //Create our RawContact ContentProviderOperation.Builder builder =\r
+ * ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);\r
+ * builder.withValue(RawContacts.ACCOUNT_NAME, account.name);\r
+ * builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);\r
+ * builder.withValue(RawContacts.SYNC1, username);\r
+ * operationList.add(builder.build());\r
+ * \r
+ * //Create a Data record of common type 'StructuredName' for our RawContact\r
+ * builder =\r
+ * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);\r
+ * builder\r
+ * .withValueBackReference(ContactsContract.CommonDataKinds.StructuredName\r
+ * .RAW_CONTACT_ID, 0); builder.withValue(ContactsContract.Data.MIMETYPE,\r
+ * ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);\r
+ * builder\r
+ * .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,\r
+ * name); operationList.add(builder.build());\r
+ * \r
+ * //Create a Data record of custom type\r
+ * "vnd.android.cursor.item/vnd.fm.last.android.profile" to display a link\r
+ * to the Last.fm profile builder =\r
+ * ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);\r
+ * builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);\r
+ * builder.withValue(ContactsContract.Data.MIMETYPE,\r
+ * "vnd.android.cursor.item/vnd.owncloud.contact.profile");\r
+ * builder.withValue(ContactsContract.Data.DATA1, username);\r
+ * builder.withValue(ContactsContract.Data.DATA2, "Last.fm Profile");\r
+ * builder.withValue(ContactsContract.Data.DATA3, "View profile");\r
+ * operationList.add(builder.build());\r
+ * \r
+ * try {\r
+ * getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY,\r
+ * operationList); } catch (Exception e) { Log.e("ASD",\r
+ * "Something went wrong during creation! " + e); e.printStackTrace(); } }\r
+ */\r
\r
}\r
import eu.alefzero.owncloud.ui.adapter.LandingScreenAdapter;\r
\r
/**\r
- * Used on the Landing page to display what Components of \r
- * the ownCloud there are. Like Files, Music, Contacts, etc.\r
+ * Used on the Landing page to display what Components of the ownCloud there\r
+ * are. Like Files, Music, Contacts, etc.\r
* \r
* @author Lennart Rosam\r
- *\r
+ * \r
*/\r
public class LandingPageFragment extends SherlockFragment {\r
\r
- @Override\r
- public View onCreateView(LayoutInflater inflater, ViewGroup container,\r
- Bundle savedInstanceState) {\r
- View root = inflater.inflate(R.layout.landing_page_fragment, container);\r
- return root;\r
- }\r
+ @Override\r
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,\r
+ Bundle savedInstanceState) {\r
+ View root = inflater.inflate(R.layout.landing_page_fragment, container);\r
+ return root;\r
+ }\r
+\r
+ @Override\r
+ public void onActivityCreated(Bundle savedInstanceState) {\r
+ super.onActivityCreated(savedInstanceState);\r
\r
+ ListView landingScreenItems = (ListView) getView().findViewById(\r
+ R.id.homeScreenList);\r
+ landingScreenItems.setAdapter(new LandingScreenAdapter(getActivity()));\r
+ landingScreenItems\r
+ .setOnItemClickListener((LandingActivity) getActivity());\r
+ }\r
\r
- @Override\r
- public void onActivityCreated(Bundle savedInstanceState) {\r
- super.onActivityCreated(savedInstanceState);\r
- \r
- ListView landingScreenItems = (ListView) getView().findViewById(R.id.homeScreenList);\r
- landingScreenItems.setAdapter(new LandingScreenAdapter(getActivity()));\r
- landingScreenItems.setOnItemClickListener((LandingActivity) getActivity());\r
- }\r
- \r
- \r
}\r
package eu.alefzero.owncloud.utils;
public class OwnCloudVersion implements Comparable<OwnCloudVersion> {
- public static final OwnCloudVersion owncloud_v1 = new OwnCloudVersion(0x010000);
- public static final OwnCloudVersion owncloud_v2 = new OwnCloudVersion(0x020000);
- public static final OwnCloudVersion owncloud_v3 = new OwnCloudVersion(0x030000);
- public static final OwnCloudVersion owncloud_v4 = new OwnCloudVersion(0x040000);
-
- // format is in version
- // 0xAABBCC
- // for version AA.BB.CC
- // ie version 3.0.3 will be stored as 0x030003
- private int mVersion;
- private boolean mIsValid;
-
- public OwnCloudVersion(int version) {
- mVersion = version;
- mIsValid = true;
- }
+ public static final OwnCloudVersion owncloud_v1 = new OwnCloudVersion(
+ 0x010000);
+ public static final OwnCloudVersion owncloud_v2 = new OwnCloudVersion(
+ 0x020000);
+ public static final OwnCloudVersion owncloud_v3 = new OwnCloudVersion(
+ 0x030000);
+ public static final OwnCloudVersion owncloud_v4 = new OwnCloudVersion(
+ 0x040000);
- public OwnCloudVersion(String version) {
- mVersion = 0;
- mIsValid = false;
- parseVersionString(version);
- }
-
- public String toString() {
- return ((mVersion >> 16)%256) + "." +
- ((mVersion >> 8)%256) + "." +
- ((mVersion)%256);
- }
-
- public boolean isVersionValid() {
- return mIsValid;
- }
-
- @Override
- public int compareTo(OwnCloudVersion another) {
- return another.mVersion == mVersion ? 0 :
- another.mVersion < mVersion ? 1 : -1;
- }
-
- private void parseVersionString(String version) {
- try {
- String[] nums = version.split("\\.");
- if (nums.length > 0) {
- mVersion += Integer.parseInt(nums[0]);
- }
- mVersion = mVersion << 8;
- if (nums.length > 1) {
- mVersion += Integer.parseInt(nums[1]);
- }
- mVersion = mVersion << 8;
- if (nums.length > 2) {
- mVersion += Integer.parseInt(nums[2]);
- }
- mIsValid = true;
- } catch (Exception e) {
- mIsValid = false;
+ // format is in version
+ // 0xAABBCC
+ // for version AA.BB.CC
+ // ie version 3.0.3 will be stored as 0x030003
+ private int mVersion;
+ private boolean mIsValid;
+
+ public OwnCloudVersion(int version) {
+ mVersion = version;
+ mIsValid = true;
+ }
+
+ public OwnCloudVersion(String version) {
+ mVersion = 0;
+ mIsValid = false;
+ parseVersionString(version);
+ }
+
+ public String toString() {
+ return ((mVersion >> 16) % 256) + "." + ((mVersion >> 8) % 256) + "."
+ + ((mVersion) % 256);
+ }
+
+ public boolean isVersionValid() {
+ return mIsValid;
+ }
+
+ @Override
+ public int compareTo(OwnCloudVersion another) {
+ return another.mVersion == mVersion ? 0
+ : another.mVersion < mVersion ? 1 : -1;
+ }
+
+ private void parseVersionString(String version) {
+ try {
+ String[] nums = version.split("\\.");
+ if (nums.length > 0) {
+ mVersion += Integer.parseInt(nums[0]);
+ }
+ mVersion = mVersion << 8;
+ if (nums.length > 1) {
+ mVersion += Integer.parseInt(nums[1]);
+ }
+ mVersion = mVersion << 8;
+ if (nums.length > 2) {
+ mVersion += Integer.parseInt(nums[2]);
+ }
+ mIsValid = true;
+ } catch (Exception e) {
+ mIsValid = false;
+ }
}
- }
}
import android.widget.EditText;
public class ActionEditText extends EditText {
- private String s;
- private String optionOneString;
- private int optionOneColor;
- private String optionTwoString;
- private int optionTwoColor;
- private Rect mTextBounds, mButtonRect;
-
- private String badgeClickCallback;
- private Rect btn_rect;
-
- public ActionEditText(Context context, AttributeSet attrs) {
- super(context, attrs);
- getAttrs(attrs);
- s = optionOneString;
- mTextBounds = new Rect();
- mButtonRect = new Rect();
- }
-
- public ActionEditText(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- getAttrs(attrs);
- s = optionOneString;
- mTextBounds = new Rect();
- mButtonRect = new Rect();
- }
-
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
-
- Paint p = getPaint();
-
- p.getTextBounds(s, 0, s.length(), mTextBounds);
-
- getDrawingRect(mButtonRect);
- mButtonRect.top += 10;
- mButtonRect.bottom -= 10;
- mButtonRect.left = (int)(getWidth() - mTextBounds.width() - 18);
- mButtonRect.right = getWidth() - 10;
- btn_rect = mButtonRect;
-
- if (s.equals(optionOneString))
- p.setColor(optionOneColor);
- else
- p.setColor(optionTwoColor);
- canvas.drawRect(mButtonRect, p);
- p.setColor(Color.GRAY);
-
- canvas.drawText(s, mButtonRect.left + 3, mButtonRect.bottom - (mTextBounds.height()/2), p);
-
- invalidate();
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- int touchX = (int) event.getX();
- int touchY = (int) event.getY();
- boolean r = super.onTouchEvent(event);
- if (event.getAction() == MotionEvent.ACTION_UP) {
- if (btn_rect.contains(touchX, touchY)) {
- if (s.equals(optionTwoString)) s = optionOneString;
- else s = optionTwoString;
- if (badgeClickCallback != null) {
- @SuppressWarnings("rawtypes")
- Class[] paramtypes = new Class[2];
- paramtypes[0] = android.view.View.class;
- paramtypes[1] = String.class;
- Method method;
- try {
-
- method = getContext().getClass().getMethod(badgeClickCallback, paramtypes);
- method.invoke(getContext(), this, s);
-
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
-
- invalidate();
+ private String s;
+ private String optionOneString;
+ private int optionOneColor;
+ private String optionTwoString;
+ private int optionTwoColor;
+ private Rect mTextBounds, mButtonRect;
+
+ private String badgeClickCallback;
+ private Rect btn_rect;
+
+ public ActionEditText(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ getAttrs(attrs);
+ s = optionOneString;
+ mTextBounds = new Rect();
+ mButtonRect = new Rect();
+ }
+
+ public ActionEditText(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ getAttrs(attrs);
+ s = optionOneString;
+ mTextBounds = new Rect();
+ mButtonRect = new Rect();
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ super.onDraw(canvas);
+
+ Paint p = getPaint();
+
+ p.getTextBounds(s, 0, s.length(), mTextBounds);
+
+ getDrawingRect(mButtonRect);
+ mButtonRect.top += 10;
+ mButtonRect.bottom -= 10;
+ mButtonRect.left = (int) (getWidth() - mTextBounds.width() - 18);
+ mButtonRect.right = getWidth() - 10;
+ btn_rect = mButtonRect;
+
+ if (s.equals(optionOneString))
+ p.setColor(optionOneColor);
+ else
+ p.setColor(optionTwoColor);
+ canvas.drawRect(mButtonRect, p);
+ p.setColor(Color.GRAY);
+
+ canvas.drawText(s, mButtonRect.left + 3, mButtonRect.bottom
+ - (mTextBounds.height() / 2), p);
+
+ invalidate();
+ }
+
+ @Override
+ public boolean onTouchEvent(MotionEvent event) {
+ int touchX = (int) event.getX();
+ int touchY = (int) event.getY();
+ boolean r = super.onTouchEvent(event);
+ if (event.getAction() == MotionEvent.ACTION_UP) {
+ if (btn_rect.contains(touchX, touchY)) {
+ if (s.equals(optionTwoString))
+ s = optionOneString;
+ else
+ s = optionTwoString;
+ if (badgeClickCallback != null) {
+ @SuppressWarnings("rawtypes")
+ Class[] paramtypes = new Class[2];
+ paramtypes[0] = android.view.View.class;
+ paramtypes[1] = String.class;
+ Method method;
+ try {
+
+ method = getContext().getClass().getMethod(
+ badgeClickCallback, paramtypes);
+ method.invoke(getContext(), this, s);
+
+ } catch (NoSuchMethodException e) {
+ e.printStackTrace();
+ } catch (IllegalArgumentException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ } catch (InvocationTargetException e) {
+ e.printStackTrace();
+ }
+
+ invalidate();
+ }
+ }
}
- }
+ return r;
}
- return r;
- }
-
- private void getAttrs(AttributeSet attr) {
- TypedArray a = getContext().obtainStyledAttributes(attr, R.styleable.ActionEditText);
- optionOneString = a.getString(R.styleable.ActionEditText_optionOneString);
- optionTwoString = a.getString(R.styleable.ActionEditText_optionTwoString);
- optionOneColor = a.getColor(R.styleable.ActionEditText_optionOneColor, 0x00ff00);
- optionTwoColor = a.getColor(R.styleable.ActionEditText_optionTwoColor, 0xff0000);
- badgeClickCallback = a.getString(R.styleable.ActionEditText_onBadgeClick);
- }
-
+
+ private void getAttrs(AttributeSet attr) {
+ TypedArray a = getContext().obtainStyledAttributes(attr,
+ R.styleable.ActionEditText);
+ optionOneString = a
+ .getString(R.styleable.ActionEditText_optionOneString);
+ optionTwoString = a
+ .getString(R.styleable.ActionEditText_optionTwoString);
+ optionOneColor = a.getColor(R.styleable.ActionEditText_optionOneColor,
+ 0x00ff00);
+ optionTwoColor = a.getColor(R.styleable.ActionEditText_optionTwoColor,
+ 0xff0000);
+ badgeClickCallback = a
+ .getString(R.styleable.ActionEditText_onBadgeClick);
+ }
+
}
/**
* A RequestEntity that represents a File.
- *
+ *
*/
public class FileRequestEntity implements RequestEntity {
- final File file;
- final String contentType;
+ final File file;
+ final String contentType;
- public FileRequestEntity(final File file, final String contentType) {
- super();
- if (file == null) {
- throw new IllegalArgumentException("File may not be null");
+ public FileRequestEntity(final File file, final String contentType) {
+ super();
+ if (file == null) {
+ throw new IllegalArgumentException("File may not be null");
+ }
+ this.file = file;
+ this.contentType = contentType;
}
- this.file = file;
- this.contentType = contentType;
- }
- public long getContentLength() {
- return this.file.length();
- }
-
- public String getContentType() {
- return this.contentType;
- }
-
- public boolean isRepeatable() {
- return true;
- }
-
- public void writeRequest(final OutputStream out) throws IOException {
- byte[] tmp = new byte[4096];
- int i = 0;
- InputStream instream = new FileInputStream(this.file);
- try {
- while ((i = instream.read(tmp)) >= 0) {
- out.write(tmp, 0, i);
- }
- } finally {
- instream.close();
+
+ public long getContentLength() {
+ return this.file.length();
+ }
+
+ public String getContentType() {
+ return this.contentType;
+ }
+
+ public boolean isRepeatable() {
+ return true;
+ }
+
+ public void writeRequest(final OutputStream out) throws IOException {
+ byte[] tmp = new byte[4096];
+ int i = 0;
+ InputStream instream = new FileInputStream(this.file);
+ try {
+ while ((i = instream.read(tmp)) >= 0) {
+ out.write(tmp, 0, i);
+ }
+ } finally {
+ instream.close();
+ }
}
- }
}
\ No newline at end of file
* along with this program. If not, see <http://www.gnu.org/licenses/>.\r
*\r
*/\r
-package eu.alefzero.webdav;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
+package eu.alefzero.webdav;\r
+\r
+import java.io.BufferedInputStream;\r
+import java.io.File;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
import java.net.URLDecoder;\r
import java.net.URLEncoder;\r
-
+\r
import org.apache.commons.httpclient.Credentials;\r
import org.apache.commons.httpclient.HttpClient;\r
import org.apache.commons.httpclient.UsernamePasswordCredentials;\r
import org.apache.commons.httpclient.methods.PutMethod;\r
import org.apache.commons.httpclient.methods.RequestEntity;\r
import org.apache.commons.httpclient.params.HttpMethodParams;\r
-import org.apache.commons.httpclient.protocol.Protocol;
+import org.apache.commons.httpclient.protocol.Protocol;\r
import org.apache.http.HttpStatus;\r
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;\r
-
-import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;
-
+\r
+import eu.alefzero.owncloud.authenticator.EasySSLSocketFactory;\r
+\r
import android.net.Uri;\r
-import android.util.Log;
-
-public class WebdavClient extends HttpClient {
- private Uri mUri;\r
- private Credentials mCredentials;
- final private static String TAG = "WebdavClient";\r
- private static final String USER_AGENT = "Android-ownCloud";
-
- public WebdavClient(Uri uri) {
- mUri = uri;\r
- getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
- }
-
- public void setCredentials(String username, String password) {\r
- getParams().setAuthenticationPreemptive(true);
- getState().setCredentials(AuthScope.ANY, getCredentials(username, password));
- }
-
- private Credentials getCredentials(String username, String password) {\r
- if (mCredentials == null)\r
- mCredentials = new UsernamePasswordCredentials(username, password); \r
- return mCredentials;\r
- }\r
-\r
- public void allowUnsignedCertificates() {
- // https\r
- Protocol.registerProtocol("https", new Protocol("https", new EasySSLSocketFactory(), 443));
- }
-
- public boolean downloadFile(String filepath, File targetPath) {
- //HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ", "%20"));\r
- \r
- Log.e("ASD", mUri.toString() + URLDecoder.decode(filepath) + "");\r
- GetMethod get = new GetMethod(mUri.toString() + URLEncoder.encode(filepath));\r
-
-// get.setHeader("Host", mUri.getHost());
-// get.setHeader("User-Agent", "Android-ownCloud");
-
- try {\r
- Log.e("ASD", get.toString());
- int status = executeMethod(get);
- if (status != HttpStatus.SC_OK) {
- return false;
- }
- BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
- FileOutputStream fos = new FileOutputStream(targetPath);
-
- byte[] bytes = new byte[512];
- int readResult;
- while ((readResult = bis.read(bytes)) != -1) fos.write(bytes, 0, readResult);
-
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- return true;
- }
-
- public boolean putFile(String localFile,
- String remoteTarget,
- String contentType) {
- boolean result = true;
-
- try {\r
- Log.e("ASD", contentType+"");\r
- File f = new File(localFile);
- RequestEntity entity = new FileRequestEntity(f, contentType);\r
- Log.e("ASD", f.exists()+" " + entity.getContentLength());\r
- PutMethod put = new PutMethod(mUri.toString() + remoteTarget);\r
- put.setRequestEntity(entity);\r
- Log.d(TAG, "" + put.getURI().toString());\r
- int status = executeMethod(put);\r
- Log.d(TAG, "PUT method return with status "+status);
-
- Log.i(TAG, "Uploading, done");
- } catch (final Exception e) {
- Log.i(TAG, ""+e.getMessage());
- result = false;
- }
-
- return result;
- }
- \r
- public int tryToLogin() {\r
- int r = 0; \r
- HeadMethod head = new HeadMethod(mUri.toString());\r
- try {\r
- r = executeMethod(head);\r
- } catch (Exception e) {\r
- Log.e(TAG, "Error: " + e.getMessage());\r
+import android.util.Log;\r
+\r
+public class WebdavClient extends HttpClient {\r
+ private Uri mUri;\r
+ private Credentials mCredentials;\r
+ final private static String TAG = "WebdavClient";\r
+ private static final String USER_AGENT = "Android-ownCloud";\r
+\r
+ public WebdavClient(Uri uri) {\r
+ mUri = uri;\r
+ getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);\r
+ }\r
+\r
+ public void setCredentials(String username, String password) {\r
+ getParams().setAuthenticationPreemptive(true);\r
+ getState().setCredentials(AuthScope.ANY,\r
+ getCredentials(username, password));\r
+ }\r
+\r
+ private Credentials getCredentials(String username, String password) {\r
+ if (mCredentials == null)\r
+ mCredentials = new UsernamePasswordCredentials(username, password);\r
+ return mCredentials;\r
+ }\r
+\r
+ public void allowUnsignedCertificates() {\r
+ // https\r
+ Protocol.registerProtocol("https", new Protocol("https",\r
+ new EasySSLSocketFactory(), 443));\r
+ }\r
+\r
+ public boolean downloadFile(String filepath, File targetPath) {\r
+ // HttpGet get = new HttpGet(mUri.toString() + filepath.replace(" ",\r
+ // "%20"));\r
+\r
+ Log.e("ASD", mUri.toString() + URLDecoder.decode(filepath) + "");\r
+ GetMethod get = new GetMethod(mUri.toString()\r
+ + URLEncoder.encode(filepath));\r
+\r
+ // get.setHeader("Host", mUri.getHost());\r
+ // get.setHeader("User-Agent", "Android-ownCloud");\r
+\r
+ try {\r
+ Log.e("ASD", get.toString());\r
+ int status = executeMethod(get);\r
+ if (status != HttpStatus.SC_OK) {\r
+ return false;\r
+ }\r
+ BufferedInputStream bis = new BufferedInputStream(\r
+ get.getResponseBodyAsStream());\r
+ FileOutputStream fos = new FileOutputStream(targetPath);\r
+\r
+ byte[] bytes = new byte[512];\r
+ int readResult;\r
+ while ((readResult = bis.read(bytes)) != -1)\r
+ fos.write(bytes, 0, readResult);\r
+\r
+ } catch (IOException e) {\r
+ e.printStackTrace();\r
+ return false;\r
+ }\r
+ return true;\r
+ }\r
+\r
+ public boolean putFile(String localFile, String remoteTarget,\r
+ String contentType) {\r
+ boolean result = true;\r
+\r
+ try {\r
+ Log.e("ASD", contentType + "");\r
+ File f = new File(localFile);\r
+ RequestEntity entity = new FileRequestEntity(f, contentType);\r
+ Log.e("ASD", f.exists() + " " + entity.getContentLength());\r
+ PutMethod put = new PutMethod(mUri.toString() + remoteTarget);\r
+ put.setRequestEntity(entity);\r
+ Log.d(TAG, "" + put.getURI().toString());\r
+ int status = executeMethod(put);\r
+ Log.d(TAG, "PUT method return with status " + status);\r
+\r
+ Log.i(TAG, "Uploading, done");\r
+ } catch (final Exception e) {\r
+ Log.i(TAG, "" + e.getMessage());\r
+ result = false;\r
+ }\r
+\r
+ return result;\r
+ }\r
+\r
+ public int tryToLogin() {\r
+ int r = 0;\r
+ HeadMethod head = new HeadMethod(mUri.toString());\r
+ try {\r
+ r = executeMethod(head);\r
+ } catch (Exception e) {\r
+ Log.e(TAG, "Error: " + e.getMessage());\r
+ }\r
+ return r;\r
+ }\r
+\r
+ public boolean createDirectory(String path) {\r
+ try {\r
+ MkColMethod mkcol = new MkColMethod(mUri.toString() + "/" + path\r
+ + "/");\r
+ int status = executeMethod(mkcol);\r
+ Log.d(TAG, "Status returned " + status);\r
+ Log.d(TAG, "uri: " + mkcol.getURI().toString());\r
+ Log.i(TAG, "Creating dir completed");\r
+ } catch (final Exception e) {\r
+ e.printStackTrace();\r
+ return false;\r
+ }\r
+ return true;\r
}\r
- return r;\r
- }\r
-
- public boolean createDirectory(String path) {
- try {\r
- MkColMethod mkcol = new MkColMethod(mUri.toString() + "/" + path + "/");
- int status = executeMethod(mkcol);\r
- Log.d(TAG, "Status returned " + status);\r
- Log.d(TAG, "uri: " + mkcol.getURI().toString());
- Log.i(TAG, "Creating dir completed");
- } catch (final Exception e) {
- e.printStackTrace();
- return false;
- }
- return true;
- }
-}
+}\r
import android.util.Log;
public class WebdavEntry {
- private String mName, mPath, mUri, mContentType;
- private long mContentLength, mCreateTimestamp, mModifiedTimestamp;
-
- public WebdavEntry(MultiStatusResponse ms) {
- resetData();
- if (ms.getStatus().length != 0) {
- mUri = ms.getHref();
-
- mPath = mUri.split("webdav.php", 2)[1];
-
- int status = ms.getStatus()[0].getStatusCode();
- DavPropertySet propSet = ms.getProperties(status);
- @SuppressWarnings("rawtypes")
- DavProperty prop = propSet.get(DavPropertyName.DISPLAYNAME);
- if (prop != null) mName = (String) prop.getName().toString();
- else {
- String[] tmp = mPath.split("/");
- if (tmp.length > 0)
- mName = tmp[tmp.length-1];
- }
-
- prop = propSet.get(DavPropertyName.GETCONTENTTYPE);
- if (prop != null) {
- mContentType = (String) prop.getValue();
- } else {
- mContentType = "DIR";
- /*prop = propSet.get(DavPropertyName.ISCOLLECTION);
- if (prop != null && Boolean.parseBoolean((String) prop.getValue()))
- mContentType = "DIR";*/
- }
-
- prop = propSet.get(DavPropertyName.GETCONTENTLENGTH);
- if (prop != null)
- mContentLength = Long.parseLong((String) prop.getValue());
-
- prop = propSet.get(DavPropertyName.GETLASTMODIFIED);
- if (prop != null) {
- Date d = WebdavUtils.parseResponseDate((String)prop.getValue());
- mModifiedTimestamp = (d != null) ? d.getTime() : 0;
- }
-
- prop = propSet.get(DavPropertyName.CREATIONDATE);
- if (prop != null) {
- Date d = WebdavUtils.parseResponseDate((String)prop.getValue());
- mCreateTimestamp = (d != null) ? d.getTime() : 0;
- }
-
- } else {
- Log.e("WebdavEntry", "General fuckup, no status for webdav response");
+ private String mName, mPath, mUri, mContentType;
+ private long mContentLength, mCreateTimestamp, mModifiedTimestamp;
+
+ public WebdavEntry(MultiStatusResponse ms) {
+ resetData();
+ if (ms.getStatus().length != 0) {
+ mUri = ms.getHref();
+
+ mPath = mUri.split("webdav.php", 2)[1];
+
+ int status = ms.getStatus()[0].getStatusCode();
+ DavPropertySet propSet = ms.getProperties(status);
+ @SuppressWarnings("rawtypes")
+ DavProperty prop = propSet.get(DavPropertyName.DISPLAYNAME);
+ if (prop != null)
+ mName = (String) prop.getName().toString();
+ else {
+ String[] tmp = mPath.split("/");
+ if (tmp.length > 0)
+ mName = tmp[tmp.length - 1];
+ }
+
+ prop = propSet.get(DavPropertyName.GETCONTENTTYPE);
+ if (prop != null) {
+ mContentType = (String) prop.getValue();
+ } else {
+ mContentType = "DIR";
+ /*
+ * prop = propSet.get(DavPropertyName.ISCOLLECTION); if (prop !=
+ * null && Boolean.parseBoolean((String) prop.getValue()))
+ * mContentType = "DIR";
+ */
+ }
+
+ prop = propSet.get(DavPropertyName.GETCONTENTLENGTH);
+ if (prop != null)
+ mContentLength = Long.parseLong((String) prop.getValue());
+
+ prop = propSet.get(DavPropertyName.GETLASTMODIFIED);
+ if (prop != null) {
+ Date d = WebdavUtils
+ .parseResponseDate((String) prop.getValue());
+ mModifiedTimestamp = (d != null) ? d.getTime() : 0;
+ }
+
+ prop = propSet.get(DavPropertyName.CREATIONDATE);
+ if (prop != null) {
+ Date d = WebdavUtils
+ .parseResponseDate((String) prop.getValue());
+ mCreateTimestamp = (d != null) ? d.getTime() : 0;
+ }
+
+ } else {
+ Log.e("WebdavEntry",
+ "General fuckup, no status for webdav response");
+ }
+ }
+
+ public String path() {
+ return mPath;
+ }
+
+ public String name() {
+ return mName;
+ }
+
+ public boolean isDirectory() {
+ return mContentType.equals("DIR");
+ }
+
+ public String contentType() {
+ return mContentType;
+ }
+
+ public String uri() {
+ return mUri;
+ }
+
+ public long contentLength() {
+ return mContentLength;
+ }
+
+ public long createTimestamp() {
+ return mCreateTimestamp;
+ }
+
+ public long modifiedTimesamp() {
+ return mModifiedTimestamp;
+ }
+
+ private void resetData() {
+ mName = mUri = mContentType = null;
+ mContentLength = mCreateTimestamp = mModifiedTimestamp = 0;
}
- }
-
- public String path() {
- return mPath;
- }
-
- public String name() {
- return mName;
- }
-
- public boolean isDirectory() {
- return mContentType.equals("DIR");
- }
-
- public String contentType() {
- return mContentType;
- }
-
- public String uri() {
- return mUri;
- }
-
- public long contentLength() {
- return mContentLength;
- }
-
- public long createTimestamp() {
- return mCreateTimestamp;
- }
-
- public long modifiedTimesamp() {
- return mModifiedTimestamp;
- }
-
- private void resetData() {
- mName = mUri = mContentType = null;
- mContentLength = mCreateTimestamp = mModifiedTimestamp = 0;
- }
}
import java.util.Locale;
public class WebdavUtils {
- public static final SimpleDateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy hh:mm");
- private static final SimpleDateFormat DATETIME_FORMATS[] = {
- new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US),
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
- new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US),
- new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
- new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
- new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
- new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)};
-
- public static String prepareXmlForPropFind() {
- String ret = "<?xml version=\"1.0\" ?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>";
- return ret;
- }
-
- public static String prepareXmlForPatch() {
- return "<?xml version=\"1.0\" ?><D:propertyupdate xmlns:D=\"DAV:\"></D:propertyupdate>";
- }
-
- public static Date parseResponseDate(String date) {
- Date returnDate = null;
- for (int i = 0; i < DATETIME_FORMATS.length; ++i) {
- try {
- returnDate = DATETIME_FORMATS[i].parse(date);
- return returnDate;
- } catch (ParseException e) {}
+ public static final SimpleDateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat(
+ "dd.MM.yyyy hh:mm");
+ private static final SimpleDateFormat DATETIME_FORMATS[] = {
+ new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US),
+ new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
+ new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US),
+ new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US),
+ new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US),
+ new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
+ new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) };
+
+ public static String prepareXmlForPropFind() {
+ String ret = "<?xml version=\"1.0\" ?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>";
+ return ret;
+ }
+
+ public static String prepareXmlForPatch() {
+ return "<?xml version=\"1.0\" ?><D:propertyupdate xmlns:D=\"DAV:\"></D:propertyupdate>";
+ }
+
+ public static Date parseResponseDate(String date) {
+ Date returnDate = null;
+ for (int i = 0; i < DATETIME_FORMATS.length; ++i) {
+ try {
+ returnDate = DATETIME_FORMATS[i].parse(date);
+ return returnDate;
+ } catch (ParseException e) {
+ }
+ }
+ return null;
}
- return null;
- }
}